@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.
@@ -9,10 +9,8 @@
9
9
  * walk (`testStructure.ts`, shared with the backend's `integration/test-navigation.ts`
10
10
  * entry), which decides *where* the rules go, not whether a move is legal.
11
11
  */
12
- import type { SecureAssessment, SecureSection, SecureTestPart } from '../integration/api-contract.js';
12
+ import type { SecureSection } from '../integration/api-contract.js';
13
13
  import type { FlatItem } from './deliveryStructure.js';
14
- /** The part's effective QTI navigation mode (the assessment-level field is the fallback). */
15
- export declare function effectiveNavigationMode(testPart: SecureTestPart, assessment: SecureAssessment): 'linear' | 'nonlinear';
16
14
  /**
17
15
  * Whether jumping to a presented section is legal right now: in linear navigation there
18
16
  * is no jumping at all; in nonlinear navigation only sections of the current test part
@@ -22,7 +20,6 @@ export declare function effectiveNavigationMode(testPart: SecureTestPart, assess
22
20
  export declare function isLegalSectionTarget(options: {
23
21
  section: SecureSection;
24
22
  items: readonly FlatItem[];
25
- assessment: SecureAssessment;
26
23
  finalized: boolean;
27
24
  currentIndex: number;
28
25
  isItemLocked: (q: FlatItem) => boolean;
@@ -41,6 +38,5 @@ export declare function canNavigateByTestPart(options: {
41
38
  targetIndex: number;
42
39
  currentIndex: number;
43
40
  items: readonly FlatItem[];
44
- assessment: SecureAssessment;
45
41
  forward: () => number;
46
42
  }): boolean;
@@ -9,10 +9,6 @@
9
9
  * walk (`testStructure.ts`, shared with the backend's `integration/test-navigation.ts`
10
10
  * entry), which decides *where* the rules go, not whether a move is legal.
11
11
  */
12
- /** The part's effective QTI navigation mode (the assessment-level field is the fallback). */
13
- export function effectiveNavigationMode(testPart, assessment) {
14
- return testPart.navigationMode ?? assessment.navigationMode ?? 'nonlinear';
15
- }
16
12
  /**
17
13
  * Whether jumping to a presented section is legal right now: in linear navigation there
18
14
  * is no jumping at all; in nonlinear navigation only sections of the current test part
@@ -20,7 +16,7 @@ export function effectiveNavigationMode(testPart, assessment) {
20
16
  * legal targets.
21
17
  */
22
18
  export function isLegalSectionTarget(options) {
23
- const { section, items, assessment, finalized, currentIndex, isItemLocked, canReviewItem } = options;
19
+ const { section, items, finalized, currentIndex, isItemLocked, canReviewItem } = options;
24
20
  if (finalized)
25
21
  return false;
26
22
  const current = items[currentIndex];
@@ -29,7 +25,7 @@ export function isLegalSectionTarget(options) {
29
25
  const members = items.filter((q) => q.sections.some((s) => s.identifier === section.identifier));
30
26
  if (members.length === 0)
31
27
  return false;
32
- const mode = effectiveNavigationMode(current.testPart, assessment);
28
+ const mode = current.testPart.navigationMode;
33
29
  if (mode === 'linear') {
34
30
  return members.some((q) => q === current);
35
31
  }
@@ -47,7 +43,7 @@ export function isLegalSectionTarget(options) {
47
43
  * one back, never into a part whose precondition fails.
48
44
  */
49
45
  export function canNavigateByTestPart(options) {
50
- const { targetIndex, currentIndex, items, assessment, forward } = options;
46
+ const { targetIndex, currentIndex, items, forward } = options;
51
47
  if (targetIndex < 0 || targetIndex >= items.length)
52
48
  return false;
53
49
  const current = items[currentIndex];
@@ -56,7 +52,7 @@ export function canNavigateByTestPart(options) {
56
52
  return false;
57
53
  if (targetIndex === currentIndex)
58
54
  return true;
59
- const mode = effectiveNavigationMode(current.testPart, assessment);
55
+ const mode = current.testPart.navigationMode;
60
56
  if (current.testPart === target.testPart && mode === 'nonlinear')
61
57
  return true;
62
58
  if (targetIndex < currentIndex)
@@ -1 +1 @@
1
- {"version":3,"file":"navigationPolicy.js","sourceRoot":"","sources":["../../src/core/navigationPolicy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH,6FAA6F;AAC7F,MAAM,UAAU,uBAAuB,CACtC,QAAwB,EACxB,UAA4B;IAE5B,OAAO,QAAQ,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,IAAI,WAAW,CAAC;AAC5E,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAQ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AAO,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC;IACpC,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;IAClC,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,WAAW,KAAK,YAAY;QAAE,OAAO,IAAI,CAAC;IAC9C,MAAM,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IACnE,IAAI,OAAO,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC9E,IAAI,WAAW,GAAG,YAAY;QAAE,OAAO,KAAK,CAAC;IAC7C,OAAO,WAAW,KAAK,OAAO,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Client navigation legality.\n *\n * Whether the navigation *rules* let a candidate move or jump right now: linear\n * versus nonlinear delivery, test-part sequencing, time locks and review policy.\n * Moved out of `AssessmentPlayer.ts` verbatim (pure code motion): pure functions\n * over the delivery structure and predicates the orchestrator supplies — they\n * never take the transition lock, and they are kept separate from the delivery-rules\n * walk (`testStructure.ts`, shared with the backend's `integration/test-navigation.ts`\n * entry), which decides *where* the rules go, not whether a move is legal.\n */\n\nimport type { SecureAssessment, SecureSection, SecureTestPart } from '../integration/api-contract.js';\nimport type { FlatItem } from './deliveryStructure.js';\n\n/** The part's effective QTI navigation mode (the assessment-level field is the fallback). */\nexport function effectiveNavigationMode(\n\ttestPart: SecureTestPart,\n\tassessment: SecureAssessment,\n): 'linear' | 'nonlinear' {\n\treturn testPart.navigationMode ?? assessment.navigationMode ?? 'nonlinear';\n}\n\n/**\n * Whether jumping to a presented section is legal right now: in linear navigation there\n * is no jumping at all; in nonlinear navigation only sections of the current test part\n * are reachable, never locked items or items review has closed. Finalized tests have no\n * legal targets.\n */\nexport function isLegalSectionTarget(options: {\n\tsection: SecureSection;\n\titems: readonly FlatItem[];\n\tassessment: SecureAssessment;\n\tfinalized: boolean;\n\tcurrentIndex: number;\n\tisItemLocked: (q: FlatItem) => boolean;\n\tcanReviewItem: (q: FlatItem) => boolean;\n}): boolean {\n\tconst { section, items, assessment, finalized, currentIndex, isItemLocked, canReviewItem } = options;\n\tif (finalized) return false;\n\tconst current = items[currentIndex];\n\tif (!current) return false;\n\tconst members = items.filter((q) =>\n\t\tq.sections.some((s) => s.identifier === section.identifier),\n\t);\n\tif (members.length === 0) return false;\n\tconst mode = effectiveNavigationMode(current.testPart, assessment);\n\tif (mode === 'linear') {\n\t\treturn members.some((q) => q === current);\n\t}\n\treturn members.some(\n\t\t(q) =>\n\t\t\tq.testPart === current.testPart &&\n\t\t\t!isItemLocked(q) &&\n\t\t\tcanReviewItem(q),\n\t);\n}\n\n/**\n * Whether a candidate-initiated move from `currentIndex` to `targetIndex` follows the\n * navigation rules. Within a nonlinear test part any item is reachable. Otherwise the only\n * forward move is the forward step itself — `forward`, the item the backend's decision kept\n * for the current item or the delivery rules (branch rules, preconditions) deliver next,\n * passing over items an expired limit closed: in a linear part no item is skipped or\n * revisited, and test parts are entered in sequence — never a jump across a part, never\n * one back, never into a part whose precondition fails.\n */\nexport function canNavigateByTestPart(options: {\n\ttargetIndex: number;\n\tcurrentIndex: number;\n\titems: readonly FlatItem[];\n\tassessment: SecureAssessment;\n\tforward: () => number;\n}): boolean {\n\tconst { targetIndex, currentIndex, items, assessment, forward } = options;\n\tif (targetIndex < 0 || targetIndex >= items.length) return false;\n\tconst current = items[currentIndex];\n\tconst target = items[targetIndex];\n\tif (!current || !target) return false;\n\tif (targetIndex === currentIndex) return true;\n\tconst mode = effectiveNavigationMode(current.testPart, assessment);\n\tif (current.testPart === target.testPart && mode === 'nonlinear') return true;\n\tif (targetIndex < currentIndex) return false;\n\treturn targetIndex === forward();\n}\n"]}
1
+ {"version":3,"file":"navigationPolicy.js","sourceRoot":"","sources":["../../src/core/navigationPolicy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;G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IACjE,MAAM,OAAO,GAAG,KAAK,CAAC,YAAY,CAAC,CAAC;IACpC,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC;IAClC,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,WAAW,KAAK,YAAY;QAAE,OAAO,IAAI,CAAC;IAC9C,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAC7C,IAAI,OAAO,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC9E,IAAI,WAAW,GAAG,YAAY;QAAE,OAAO,KAAK,CAAC;IAC7C,OAAO,WAAW,KAAK,OAAO,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * Client navigation legality.\n *\n * Whether the navigation *rules* let a candidate move or jump right now: linear\n * versus nonlinear delivery, test-part sequencing, time locks and review policy.\n * Moved out of `AssessmentPlayer.ts` verbatim (pure code motion): pure functions\n * over the delivery structure and predicates the orchestrator supplies — they\n * never take the transition lock, and they are kept separate from the delivery-rules\n * walk (`testStructure.ts`, shared with the backend's `integration/test-navigation.ts`\n * entry), which decides *where* the rules go, not whether a move is legal.\n */\n\nimport type { SecureSection } from '../integration/api-contract.js';\nimport type { FlatItem } from './deliveryStructure.js';\n\n/**\n * Whether jumping to a presented section is legal right now: in linear navigation there\n * is no jumping at all; in nonlinear navigation only sections of the current test part\n * are reachable, never locked items or items review has closed. Finalized tests have no\n * legal targets.\n */\nexport function isLegalSectionTarget(options: {\n\tsection: SecureSection;\n\titems: readonly FlatItem[];\n\tfinalized: boolean;\n\tcurrentIndex: number;\n\tisItemLocked: (q: FlatItem) => boolean;\n\tcanReviewItem: (q: FlatItem) => boolean;\n}): boolean {\n\tconst { section, items, finalized, currentIndex, isItemLocked, canReviewItem } = options;\n\tif (finalized) return false;\n\tconst current = items[currentIndex];\n\tif (!current) return false;\n\tconst members = items.filter((q) =>\n\t\tq.sections.some((s) => s.identifier === section.identifier),\n\t);\n\tif (members.length === 0) return false;\n\tconst mode = current.testPart.navigationMode;\n\tif (mode === 'linear') {\n\t\treturn members.some((q) => q === current);\n\t}\n\treturn members.some(\n\t\t(q) =>\n\t\t\tq.testPart === current.testPart &&\n\t\t\t!isItemLocked(q) &&\n\t\t\tcanReviewItem(q),\n\t);\n}\n\n/**\n * Whether a candidate-initiated move from `currentIndex` to `targetIndex` follows the\n * navigation rules. Within a nonlinear test part any item is reachable. Otherwise the only\n * forward move is the forward step itself — `forward`, the item the backend's decision kept\n * for the current item or the delivery rules (branch rules, preconditions) deliver next,\n * passing over items an expired limit closed: in a linear part no item is skipped or\n * revisited, and test parts are entered in sequence — never a jump across a part, never\n * one back, never into a part whose precondition fails.\n */\nexport function canNavigateByTestPart(options: {\n\ttargetIndex: number;\n\tcurrentIndex: number;\n\titems: readonly FlatItem[];\n\tforward: () => number;\n}): boolean {\n\tconst { targetIndex, currentIndex, items, forward } = options;\n\tif (targetIndex < 0 || targetIndex >= items.length) return false;\n\tconst current = items[currentIndex];\n\tconst target = items[targetIndex];\n\tif (!current || !target) return false;\n\tif (targetIndex === currentIndex) return true;\n\tconst mode = current.testPart.navigationMode;\n\tif (current.testPart === target.testPart && mode === 'nonlinear') return true;\n\tif (targetIndex < currentIndex) return false;\n\treturn targetIndex === forward();\n}\n"]}
@@ -9,12 +9,9 @@
9
9
  * interactions require is read live from a detached item session by the orchestrator
10
10
  * (`responseValidationFor`) and only shapes the blocker's user-facing `requirement`.
11
11
  */
12
- import type { SecureAssessment, SecureTestPart } from '../integration/api-contract.js';
13
12
  import type { FlatItem } from './deliveryStructure.js';
14
13
  import { type ResponseDefault } from './AssessmentSessionCoordinator.js';
15
14
  import type { ItemSessionControlSettings } from './ItemSessionController.js';
16
- /** The part's effective QTI submission mode (the assessment-level field is the fallback). */
17
- export declare function effectiveSubmissionMode(testPart: SecureTestPart, assessment: SecureAssessment): 'individual' | 'simultaneous';
18
15
  /**
19
16
  * QTI itemSessionControl `allowSkipping` / `validateResponses` for one item's
20
17
  * responses. Both are "only applicable when the item is in a testPart with individual
@@ -11,10 +11,6 @@
11
11
  */
12
12
  import { isSkippedResponseSet } from './AssessmentSessionCoordinator.js';
13
13
  import { AssessmentPlayerError } from './errors.js';
14
- /** The part's effective QTI submission mode (the assessment-level field is the fallback). */
15
- export function effectiveSubmissionMode(testPart, assessment) {
16
- return testPart.submissionMode ?? assessment.submissionMode;
17
- }
18
14
  /**
19
15
  * QTI itemSessionControl `allowSkipping` / `validateResponses` for one item's
20
16
  * responses. Both are "only applicable when the item is in a testPart with individual
@@ -1 +1 @@
1
- {"version":3,"file":"submissionPolicy.js","sourceRoot":"","sources":["../../src/core/submissionPolicy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAAE,oBAAoB,EAAwB,MAAM,mCAAmC,CAAC;AAE/F,OAAO,EAAE,qBAAqB,EAAkC,MAAM,aAAa,CAAC;AAEpF,6FAA6F;AAC7F,MAAM,UAAU,uBAAuB,CACtC,QAAwB,EACxB,UAA4B;IAE5B,OAAO,QAAQ,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,OAK9B;IACA,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAC9D,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAC/D,MAAM,OAAO,GAAG,oBAAoB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC1D,OAAO;QACN,UAAU,EAAE,OAAO,IAAI,QAAQ,CAAC,aAAa,KAAK,KAAK;QACvD,QAAQ,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,iBAAiB,KAAK,IAAI;KACzD,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AAW,CAAC,IAAI,CAAC,GAAG,CAAC;QACtC,KAAK,EAAE,KAAK,CAAC,MAAM;KACnB,CACD,CAAC;AACH,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,oBAAoB,CACnC,CAAW,EACX,MAAmC,EACnC,WAAyD,EACzD,WAAoB;IAEpB,OAAO;QACN,UAAU,EAAE,CAAC,CAAC,UAAU;QACxB,KAAK,EAAE,CAAC,CAAC,KAAK;QACd,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG,CAAC;QACnB,MAAM;QACN,WAAW;QACX,SAAS,EAAE,WAAW;QACtB,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["/**\n * Submission policy.\n *\n * The QTI itemSessionControl submission gate (`allowSkipping` / `validateResponses`)\n * and the coded rejections for held-back items. Moved out of `AssessmentPlayer.ts`\n * verbatim (pure code motion): pure decisions over explicit inputs — no lock, no\n * session state. Kept deliberately separate from the constraint-validation layer:\n * *whether* an item may be skipped or must validate is policy; *what* the item's\n * interactions require is read live from a detached item session by the orchestrator\n * (`responseValidationFor`) and only shapes the blocker's user-facing `requirement`.\n */\n\nimport type { SecureAssessment, SecureTestPart } from '../integration/api-contract.js';\nimport type { FlatItem } from './deliveryStructure.js';\nimport { isSkippedResponseSet, type ResponseDefault } from './AssessmentSessionCoordinator.js';\nimport type { ItemSessionControlSettings } from './ItemSessionController.js';\nimport { AssessmentPlayerError, type AssessmentPlayerErrorCode } from './errors.js';\n\n/** The part's effective QTI submission mode (the assessment-level field is the fallback). */\nexport function effectiveSubmissionMode(\n\ttestPart: SecureTestPart,\n\tassessment: SecureAssessment,\n): 'individual' | 'simultaneous' {\n\treturn testPart.submissionMode ?? assessment.submissionMode;\n}\n\n/**\n * QTI itemSessionControl `allowSkipping` / `validateResponses` for one item's\n * responses. Both are \"only applicable when the item is in a testPart with individual\n * submission mode\", so a simultaneous part is never gated. A skipped item (no\n * response at all: every response NULL, empty or still equal to its declared default —\n * the test `numberResponded` applies) may be submitted only when skipping is allowed,\n * and is then not validated; an answered item validates when the item asks for it.\n */\nexport function submissionGate(options: {\n\tindividual: boolean;\n\tsettings: Pick<ItemSessionControlSettings, 'allowSkipping' | 'validateResponses'>;\n\tresponses: Record<string, unknown>;\n\tdefaults: Readonly<Record<string, ResponseDefault>>;\n}): { mustAnswer: boolean; validate: boolean } {\n\tconst { individual, settings, responses, defaults } = options;\n\tif (!individual) return { mustAnswer: false, validate: false };\n\tconst skipped = isSkippedResponseSet(responses, defaults);\n\treturn {\n\t\tmustAnswer: skipped && settings.allowSkipping === false,\n\t\tvalidate: !skipped && settings.validateResponses === true,\n\t};\n}\n\n/**\n * An item a candidate-initiated end of the test would refuse to submit\n * (`getSubmissionBlockers()`): QTI `allowSkipping=false` with no response (`required`),\n * or `validateResponses=true` with responses that do not satisfy the interactions\n * (`invalid`). Both apply only to items in individual submission parts.\n */\nexport interface SubmissionBlocker {\n\tidentifier: string;\n\t/** Flat delivery index (for `navigateTo`). */\n\tindex: number;\n\t/** 1-based position shown to the candidate. */\n\tnumber: number;\n\treason: 'required' | 'invalid';\n\t/** Whether the navigation rules let the candidate jump to it now. */\n\tjumpAllowed: boolean;\n\t/** False when the candidate can no longer reach the question (its part was left). */\n\treachable: boolean;\n\t/**\n\t * What the response still owes, when derivable from the item's interaction constraints\n\t * (a minimum number of selections, strings, associations or plays); absent when the\n\t * item only needs an answer. The shell localizes it into the entry text.\n\t */\n\trequirement?: { kind: 'minChoices' | 'minStrings' | 'minAssociations' | 'minPlays' | 'incomplete'; count?: number };\n}\n\n/** Reject a candidate-initiated end of the test (or part leave) that would submit held-back items, naming them. */\nexport function throwForBlockers(blockers: ReadonlyArray<SubmissionBlocker>, context: 'finalize' | 'leavePart'): void {\n\tconst required = blockers.filter((blocker) => blocker.reason === 'required');\n\tconst named = required.length > 0 ? required : blockers;\n\tif (named.length === 0) return;\n\tconst code: AssessmentPlayerErrorCode =\n\t\tcontext === 'finalize'\n\t\t\t? required.length > 0\n\t\t\t\t? 'finalizeResponseRequired'\n\t\t\t\t: 'finalizeResponseInvalid'\n\t\t\t: required.length > 0\n\t\t\t\t? 'leavePartResponseRequired'\n\t\t\t\t: 'leavePartResponseInvalid';\n\tconst identifiers = named.map((blocker) => blocker.identifier);\n\tconst what = context === 'finalize' ? 'the test can end' : 'leaving this test part';\n\tthrow new AssessmentPlayerError(\n\t\tcode,\n\t\trequired.length > 0\n\t\t\t? `These items need a response before ${what}: ${identifiers.join(', ')}`\n\t\t\t: `These items have responses that do not satisfy their interactions (before ${what}): ${identifiers.join(', ')}`,\n\t\t{\n\t\t\titems: named.map((blocker) => blocker.number).join(', '),\n\t\t\titemIdentifiers: identifiers.join(','),\n\t\t\tcount: named.length,\n\t\t},\n\t);\n}\n\n/** Assemble the blocker view for an item a submission control would refuse right now. */\nexport function submissionBlockerFor(\n\tq: FlatItem,\n\treason: SubmissionBlocker['reason'],\n\trequirement: SubmissionBlocker['requirement'] | undefined,\n\tjumpAllowed: boolean,\n): SubmissionBlocker {\n\treturn {\n\t\tidentifier: q.identifier,\n\t\tindex: q.index,\n\t\tnumber: q.index + 1,\n\t\treason,\n\t\tjumpAllowed,\n\t\treachable: jumpAllowed,\n\t\t...(requirement ? { requirement } : {}),\n\t};\n}\n"]}
1
+ {"version":3,"file":"submissionPolicy.js","sourceRoot":"","sources":["../../src/core/submissionPolicy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,oBAAoB,EAAwB,MAAM,mCAAmC,CAAC;AAE/F,OAAO,EAAE,qBAAqB,EAAkC,MAAM,aAAa,CAAC;AAEpF;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,OAK9B;IACA,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAC9D,IAAI,CAAC,UAAU;QAAE,OAAO,E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I,KAAK,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACzE,CAAC,CAAC,6EAA6E,IAAI,MAAM,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAClH;QACC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QACxD,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC;QACtC,KAAK,EAAE,KAAK,CAAC,MAAM;KACnB,CACD,CAAC;AACH,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,oBAAoB,CACnC,CAAW,EACX,MAAmC,EACnC,WAAyD,EACzD,WAAoB;IAEpB,OAAO;QACN,UAAU,EAAE,CAAC,CAAC,UAAU;QACxB,KAAK,EAAE,CAAC,CAAC,KAAK;QACd,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG,CAAC;QACnB,MAAM;QACN,WAAW;QACX,SAAS,EAAE,WAAW;QACtB,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvC,CAAC;AACH,CAAC","sourcesContent":["/**\n * Submission policy.\n *\n * The QTI itemSessionControl submission gate (`allowSkipping` / `validateResponses`)\n * and the coded rejections for held-back items. Moved out of `AssessmentPlayer.ts`\n * verbatim (pure code motion): pure decisions over explicit inputs — no lock, no\n * session state. Kept deliberately separate from the constraint-validation layer:\n * *whether* an item may be skipped or must validate is policy; *what* the item's\n * interactions require is read live from a detached item session by the orchestrator\n * (`responseValidationFor`) and only shapes the blocker's user-facing `requirement`.\n */\n\nimport type { FlatItem } from './deliveryStructure.js';\nimport { isSkippedResponseSet, type ResponseDefault } from './AssessmentSessionCoordinator.js';\nimport type { ItemSessionControlSettings } from './ItemSessionController.js';\nimport { AssessmentPlayerError, type AssessmentPlayerErrorCode } from './errors.js';\n\n/**\n * QTI itemSessionControl `allowSkipping` / `validateResponses` for one item's\n * responses. Both are \"only applicable when the item is in a testPart with individual\n * submission mode\", so a simultaneous part is never gated. A skipped item (no\n * response at all: every response NULL, empty or still equal to its declared default —\n * the test `numberResponded` applies) may be submitted only when skipping is allowed,\n * and is then not validated; an answered item validates when the item asks for it.\n */\nexport function submissionGate(options: {\n\tindividual: boolean;\n\tsettings: Pick<ItemSessionControlSettings, 'allowSkipping' | 'validateResponses'>;\n\tresponses: Record<string, unknown>;\n\tdefaults: Readonly<Record<string, ResponseDefault>>;\n}): { mustAnswer: boolean; validate: boolean } {\n\tconst { individual, settings, responses, defaults } = options;\n\tif (!individual) return { mustAnswer: false, validate: false };\n\tconst skipped = isSkippedResponseSet(responses, defaults);\n\treturn {\n\t\tmustAnswer: skipped && settings.allowSkipping === false,\n\t\tvalidate: !skipped && settings.validateResponses === true,\n\t};\n}\n\n/**\n * An item a candidate-initiated end of the test would refuse to submit\n * (`getSubmissionBlockers()`): QTI `allowSkipping=false` with no response (`required`),\n * or `validateResponses=true` with responses that do not satisfy the interactions\n * (`invalid`). Both apply only to items in individual submission parts.\n */\nexport interface SubmissionBlocker {\n\tidentifier: string;\n\t/** Flat delivery index (for `navigateTo`). */\n\tindex: number;\n\t/** 1-based position shown to the candidate. */\n\tnumber: number;\n\treason: 'required' | 'invalid';\n\t/** Whether the navigation rules let the candidate jump to it now. */\n\tjumpAllowed: boolean;\n\t/** False when the candidate can no longer reach the question (its part was left). */\n\treachable: boolean;\n\t/**\n\t * What the response still owes, when derivable from the item's interaction constraints\n\t * (a minimum number of selections, strings, associations or plays); absent when the\n\t * item only needs an answer. The shell localizes it into the entry text.\n\t */\n\trequirement?: { kind: 'minChoices' | 'minStrings' | 'minAssociations' | 'minPlays' | 'incomplete'; count?: number };\n}\n\n/** Reject a candidate-initiated end of the test (or part leave) that would submit held-back items, naming them. */\nexport function throwForBlockers(blockers: ReadonlyArray<SubmissionBlocker>, context: 'finalize' | 'leavePart'): void {\n\tconst required = blockers.filter((blocker) => blocker.reason === 'required');\n\tconst named = required.length > 0 ? required : blockers;\n\tif (named.length === 0) return;\n\tconst code: AssessmentPlayerErrorCode =\n\t\tcontext === 'finalize'\n\t\t\t? required.length > 0\n\t\t\t\t? 'finalizeResponseRequired'\n\t\t\t\t: 'finalizeResponseInvalid'\n\t\t\t: required.length > 0\n\t\t\t\t? 'leavePartResponseRequired'\n\t\t\t\t: 'leavePartResponseInvalid';\n\tconst identifiers = named.map((blocker) => blocker.identifier);\n\tconst what = context === 'finalize' ? 'the test can end' : 'leaving this test part';\n\tthrow new AssessmentPlayerError(\n\t\tcode,\n\t\trequired.length > 0\n\t\t\t? `These items need a response before ${what}: ${identifiers.join(', ')}`\n\t\t\t: `These items have responses that do not satisfy their interactions (before ${what}): ${identifiers.join(', ')}`,\n\t\t{\n\t\t\titems: named.map((blocker) => blocker.number).join(', '),\n\t\t\titemIdentifiers: identifiers.join(','),\n\t\t\tcount: named.length,\n\t\t},\n\t);\n}\n\n/** Assemble the blocker view for an item a submission control would refuse right now. */\nexport function submissionBlockerFor(\n\tq: FlatItem,\n\treason: SubmissionBlocker['reason'],\n\trequirement: SubmissionBlocker['requirement'] | undefined,\n\tjumpAllowed: boolean,\n): SubmissionBlocker {\n\treturn {\n\t\tidentifier: q.identifier,\n\t\tindex: q.index,\n\t\tnumber: q.index + 1,\n\t\treason,\n\t\tjumpAllowed,\n\t\treachable: jumpAllowed,\n\t\t...(requirement ? { requirement } : {}),\n\t};\n}\n"]}
@@ -14,8 +14,7 @@
14
14
  import { addItemVariableDeclarations, applyVariableMappings, evaluateTestExpression, itemSessionVariableValues, plainQtiValue, testOutcomeDeclarations, } from './testStructure.js';
15
15
  export function templateDefaultsFor(options) {
16
16
  const { q, items, assessment, outcomes, persistedSessions, byPart } = options;
17
- const mode = q.testPart.navigationMode ?? assessment.navigationMode ?? 'nonlinear';
18
- if (mode !== 'nonlinear') {
17
+ if (q.testPart.navigationMode !== 'nonlinear') {
19
18
  if (!q.item.templateDefaults?.length)
20
19
  return undefined;
21
20
  return evaluateTemplateDefaults(q, testOutcomeDeclarations(assessment, outcomes ?? undefined));
@@ -1 +1 @@
1
- {"version":3,"file":"templateDefaults.js","sourceRoot":"","sources":["../../src/core/templateDefaults.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,OAAO,EACN,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,EACzB,aAAa,EACb,uBAAuB,GACvB,MAAM,oBAAoB,CAAC;AAK5B,MAAM,UAAU,mBAAmB,CAAC,OAOnC;IACA,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC9E,MAAM,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,cAAc,IAAI,UAAU,CAAC,cAAc,IAAI,WAAW,CAAC;IACnF,IAAI,IAAI,KAAK,WAAW,EAAE,CAAC;QAC1B,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,gBAAgB,EAAE,MAAM;YAAE,OAAO,SAAS,CAAC;QACvD,OAAO,wBAAwB,CAAC,CAAC,EAAE,uBAAuB,CAAC,UAAU,EAAE,QAAQ,IAAI,SAAS,CAAC,CAAC,CAAC;IAChG,CAAC;IACD,IAAI,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IACjD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACf,MAAM,YAAY,GAAG,2BAA2B,CAC/C,uBAAuB,CAAC,UAAU,EAAE,QAAQ,IAAI,SAAS,CAAC,EAC1D,sBAAsB,CAAC,KAAK,EAAE,iBAAiB,CAAC,CAChD,CAAC;QACF,QAAQ,GAAG,IAAI,GAAG,CACjB,KAAK;aACH,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC;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esContent":["/**\n * Template defaults policy (QTI `templateDefault`).\n *\n * How an item's new session is seeded in a nonlinear test part: evaluated once,\n * at the start of the part, for every item ref in it — with the test outcomes and\n * the other items' variables (`ITEM.VARIABLE`, as persisted so far; NULL for an\n * item not instantiated yet) in scope — and cached for the part. Linear parts\n * evaluate each item's defaults on entering it, against the test outcomes.\n *\n * Moved out of `AssessmentPlayer.ts` verbatim (pure code motion): pure functions\n * over the delivery structure, the assessment and the persisted sessions — the\n * orchestrator passes the part cache in and keeps owning it. No lock.\n */\n\nimport type { DeclarationMap, QtiValue } from '@pie-qti/qti-processing';\nimport type { SerializedItemSessionState } from '@pie-qti/item-player';\nimport type { SecureAssessment, TestOutcomeValues } from '../integration/api-contract.js';\nimport type { FlatItem } from './deliveryStructure.js';\nimport {\n\taddItemVariableDeclarations,\n\tapplyVariableMappings,\n\tevaluateTestExpression,\n\titemSessionVariableValues,\n\tplainQtiValue,\n\ttestOutcomeDeclarations,\n} from './testStructure.js';\n\n/** Template defaults of nonlinear test parts, per part → item identifier (the player's part cache). */\nexport type TemplateDefaultsByPart = Map<string, Map<string, Record<string, unknown> | undefined>>;\n\nexport function templateDefaultsFor(options: {\n\tq: FlatItem;\n\titems: readonly FlatItem[];\n\tassessment: SecureAssessment;\n\toutcomes: TestOutcomeValues | null;\n\tpersistedSessions: Record<string, SerializedItemSessionState> | undefined;\n\tbyPart: TemplateDefaultsByPart;\n}): Record<string, unknown> | undefined {\n\tconst { q, items, assessment, outcomes, persistedSessions, byPart } = options;\n\tconst mode = q.testPart.navigationMode ?? assessment.navigationMode ?? 'nonlinear';\n\tif (mode !== 'nonlinear') {\n\t\tif (!q.item.templateDefaults?.length) return undefined;\n\t\treturn evaluateTemplateDefaults(q, testOutcomeDeclarations(assessment, outcomes ?? undefined));\n\t}\n\tlet defaults = byPart.get(q.testPart.identifier);\n\tif (!defaults) {\n\t\tconst declarations = addItemVariableDeclarations(\n\t\t\ttestOutcomeDeclarations(assessment, outcomes ?? undefined),\n\t\t\tpersistedItemVariables(items, persistedSessions),\n\t\t);\n\t\tdefaults = new Map(\n\t\t\titems\n\t\t\t\t.filter((item) => item.testPart === q.testPart)\n\t\t\t\t.map((item) => [item.identifier, evaluateTemplateDefaults(item, declarations)]),\n\t\t);\n\t\tbyPart.set(q.testPart.identifier, defaults);\n\t}\n\treturn defaults.get(q.identifier);\n}\n\n/** Every item's variables from its persisted session, as test-scope expressions read them. */\nfunction persistedItemVariables(\n\titems: readonly FlatItem[],\n\tpersistedSessions: Record<string, SerializedItemSessionState> | undefined,\n): Record<string, Record<string, QtiValue>> {\n\tconst out: Record<string, Record<string, QtiValue>> = {};\n\tfor (const item of items) {\n\t\tconst serialized = persistedSessions?.[item.identifier];\n\t\tif (!serialized) continue;\n\t\tout[item.identifier] = applyVariableMappings(itemSessionVariableValues(serialized), item.item.variableMappings);\n\t}\n\treturn out;\n}\n\nfunction evaluateTemplateDefaults(q: FlatItem, declarations: DeclarationMap): Record<string, unknown> | undefined {\n\tconst defaults = q.item.templateDefaults;\n\tif (!defaults?.length) return undefined;\n\tconst out: Record<string, unknown> = {};\n\tfor (const { templateIdentifier, expressionXml } of defaults) {\n\t\tout[templateIdentifier] = plainQtiValue(evaluateTestExpression(expressionXml, declarations, Math.random));\n\t}\n\treturn out;\n}\n"]}
1
+ {"version":3,"file":"templateDefaults.js","sourceRoot":"","sources":["../../src/core/templateDefaults.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,OAAO,EACN,2BAA2B,EAC3B,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,EACzB,aAAa,EACb,uBAAuB,GACvB,MAAM,oBAAoB,CAAC;AAK5B,MAAM,UAAU,mBAAmB,CAAC,OAOnC;IACA,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC9E,IAAI,CAAC,CAAC,QAAQ,CAAC,cAAc,KAAK,WAAW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AC,IAAI,CAAC,UAAU,CAAC,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACjH,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC;AAED,SAAS,wBAAwB,CAAC,CAAW,EAAE,YAA4B;IAC1E,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC;IACzC,IAAI,CAAC,QAAQ,EAAE,MAAM;QAAE,OAAO,SAAS,CAAC;IACxC,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,QAAQ,EAAE,CAAC;QAC9D,GAAG,CAAC,kBAAkB,CAAC,GAAG,aAAa,CAAC,sBAAsB,CAAC,aAAa,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3G,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["/**\n * Template defaults policy (QTI `templateDefault`).\n *\n * How an item's new session is seeded in a nonlinear test part: evaluated once,\n * at the start of the part, for every item ref in it — with the test outcomes and\n * the other items' variables (`ITEM.VARIABLE`, as persisted so far; NULL for an\n * item not instantiated yet) in scope — and cached for the part. Linear parts\n * evaluate each item's defaults on entering it, against the test outcomes.\n *\n * Moved out of `AssessmentPlayer.ts` verbatim (pure code motion): pure functions\n * over the delivery structure, the assessment and the persisted sessions — the\n * orchestrator passes the part cache in and keeps owning it. No lock.\n */\n\nimport type { DeclarationMap, QtiValue } from '@pie-qti/qti-processing';\nimport type { SerializedItemSessionState } from '@pie-qti/item-player';\nimport type { SecureAssessment, TestOutcomeValues } from '../integration/api-contract.js';\nimport type { FlatItem } from './deliveryStructure.js';\nimport {\n\taddItemVariableDeclarations,\n\tapplyVariableMappings,\n\tevaluateTestExpression,\n\titemSessionVariableValues,\n\tplainQtiValue,\n\ttestOutcomeDeclarations,\n} from './testStructure.js';\n\n/** Template defaults of nonlinear test parts, per part → item identifier (the player's part cache). */\nexport type TemplateDefaultsByPart = Map<string, Map<string, Record<string, unknown> | undefined>>;\n\nexport function templateDefaultsFor(options: {\n\tq: FlatItem;\n\titems: readonly FlatItem[];\n\tassessment: SecureAssessment;\n\toutcomes: TestOutcomeValues | null;\n\tpersistedSessions: Record<string, SerializedItemSessionState> | undefined;\n\tbyPart: TemplateDefaultsByPart;\n}): Record<string, unknown> | undefined {\n\tconst { q, items, assessment, outcomes, persistedSessions, byPart } = options;\n\tif (q.testPart.navigationMode !== 'nonlinear') {\n\t\tif (!q.item.templateDefaults?.length) return undefined;\n\t\treturn evaluateTemplateDefaults(q, testOutcomeDeclarations(assessment, outcomes ?? undefined));\n\t}\n\tlet defaults = byPart.get(q.testPart.identifier);\n\tif (!defaults) {\n\t\tconst declarations = addItemVariableDeclarations(\n\t\t\ttestOutcomeDeclarations(assessment, outcomes ?? undefined),\n\t\t\tpersistedItemVariables(items, persistedSessions),\n\t\t);\n\t\tdefaults = new Map(\n\t\t\titems\n\t\t\t\t.filter((item) => item.testPart === q.testPart)\n\t\t\t\t.map((item) => [item.identifier, evaluateTemplateDefaults(item, declarations)]),\n\t\t);\n\t\tbyPart.set(q.testPart.identifier, defaults);\n\t}\n\treturn defaults.get(q.identifier);\n}\n\n/** Every item's variables from its persisted session, as test-scope expressions read them. */\nfunction persistedItemVariables(\n\titems: readonly FlatItem[],\n\tpersistedSessions: Record<string, SerializedItemSessionState> | undefined,\n): Record<string, Record<string, QtiValue>> {\n\tconst out: Record<string, Record<string, QtiValue>> = {};\n\tfor (const item of items) {\n\t\tconst serialized = persistedSessions?.[item.identifier];\n\t\tif (!serialized) continue;\n\t\tout[item.identifier] = applyVariableMappings(itemSessionVariableValues(serialized), item.item.variableMappings);\n\t}\n\treturn out;\n}\n\nfunction evaluateTemplateDefaults(q: FlatItem, declarations: DeclarationMap): Record<string, unknown> | undefined {\n\tconst defaults = q.item.templateDefaults;\n\tif (!defaults?.length) return undefined;\n\tconst out: Record<string, unknown> = {};\n\tfor (const { templateIdentifier, expressionXml } of defaults) {\n\t\tout[templateIdentifier] = plainQtiValue(evaluateTestExpression(expressionXml, declarations, Math.random));\n\t}\n\treturn out;\n}\n"]}
@@ -46,7 +46,7 @@ export declare function deliveredItems(assessment: SecureAssessment): DeliveredI
46
46
  * remaining items are all skipped; undefined means the current item was the last. `onError`
47
47
  * receives any condition evaluation failure (see `evaluateTestCondition`).
48
48
  */
49
- export declare function nextItemIdentifier(assessment: SecureAssessment, delivered: DeliveredItem[], index: number, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
49
+ export declare function nextItemIdentifier(delivered: DeliveredItem[], index: number, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
50
50
  /** The delivered-item shape literal branch-target resolution reads (`DeliveredItem` and `FlatItem` both). */
51
51
  export type ScopedDeliveredItem = {
52
52
  item: {
@@ -77,7 +77,7 @@ export declare function firstForwardBranchTarget(target: string, items: readonly
77
77
  * navigation. A failing part or section skips everything inside it. `onError` receives any
78
78
  * condition evaluation failure (see `evaluateTestCondition`).
79
79
  */
80
- export declare function firstEligibleItem(assessment: SecureAssessment, delivered: DeliveredItem[], start: number, from: DeliveredItem | undefined, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
80
+ export declare function firstEligibleItem(delivered: DeliveredItem[], start: number, from: DeliveredItem | undefined, decls: DeclarationMap, rng: () => number, onError?: (expressionXml: string, error: unknown) => void): string | undefined;
81
81
  /**
82
82
  * Draws selection and ordering for one session. Required children are always selected; selected
83
83
  * children keep source order before ordering shuffles the non-fixed ones. A child selected more
@@ -113,15 +113,15 @@ export function deliveredItems(assessment) {
113
113
  * remaining items are all skipped; undefined means the current item was the last. `onError`
114
114
  * receives any condition evaluation failure (see `evaluateTestCondition`).
115
115
  */
116
- export function nextItemIdentifier(assessment, delivered, index, decls, rng, onError) {
117
- const start = branchTarget(assessment, delivered, index, decls, rng, onError) ?? index + 1;
118
- const next = firstEligibleItem(assessment, delivered, start, delivered[index], decls, rng, onError);
116
+ export function nextItemIdentifier(delivered, index, decls, rng, onError) {
117
+ const start = branchTarget(delivered, index, decls, rng, onError) ?? index + 1;
118
+ const next = firstEligibleItem(delivered, start, delivered[index], decls, rng, onError);
119
119
  return next ?? (index + 1 < delivered.length ? 'EXIT_TEST' : undefined);
120
120
  }
121
- function branchTarget(assessment, delivered, index, decls, rng, onError) {
121
+ function branchTarget(delivered, index, decls, rng, onError) {
122
122
  const current = delivered[index];
123
123
  const following = delivered[index + 1];
124
- const linear = isLinear(assessment, current.testPart);
124
+ const linear = current.testPart.navigationMode === 'linear';
125
125
  const holders = [];
126
126
  if (linear) {
127
127
  holders.push({ rules: current.item.branchRule, exitSection: current.sections[current.sections.length - 1] });
@@ -189,7 +189,7 @@ function resolveBranchTarget(target, delivered, index, exitSection) {
189
189
  * navigation. A failing part or section skips everything inside it. `onError` receives any
190
190
  * condition evaluation failure (see `evaluateTestCondition`).
191
191
  */
192
- export function firstEligibleItem(assessment, delivered, start, from, decls, rng, onError) {
192
+ export function firstEligibleItem(delivered, start, from, decls, rng, onError) {
193
193
  const holds = (conditions) => (conditions ?? []).every((condition) => evaluateTestCondition(condition, decls, rng, onError));
194
194
  const skipPast = (j, inside) => {
195
195
  let next = j + 1;
@@ -205,7 +205,7 @@ export function firstEligibleItem(assessment, delivered, start, from, decls, rng
205
205
  j = skipPast(j, (d) => d.testPart === candidate.testPart);
206
206
  continue;
207
207
  }
208
- if (isLinear(assessment, candidate.testPart)) {
208
+ if (candidate.testPart.navigationMode === 'linear') {
209
209
  for (const section of candidate.sections) {
210
210
  if (previous?.sections.includes(section) || holds(section.preConditions))
211
211
  continue;
@@ -221,9 +221,6 @@ export function firstEligibleItem(assessment, delivered, start, from, decls, rng
221
221
  }
222
222
  return undefined;
223
223
  }
224
- function isLinear(assessment, testPart) {
225
- return (testPart.navigationMode ?? assessment.navigationMode) === 'linear';
226
- }
227
224
  /**
228
225
  * Draws selection and ordering for one session. Required children are always selected; selected
229
226
  * children keep source order before ordering shuffles the non-fixed ones. A child selected more
@@ -1 +1 @@
1
- {"version":3,"file":"testStructure.js","sourceRoot":"","sources":["../../src/core/testStructure.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACN,eAAe,EACf,kBAAkB,EAElB,+BAA+B,EAC/B,QAAQ,EACR,QAAQ,EAER,OAAO,EACP,QAAQ,GACR,MAAM,yBAAyB,CAAC;AAejC,gGAAgG;AAChG,MAAM,CAAC,MAAM,4BAA4B,GAAyC,MAAM,CAAC,MAAM,CAAC;IAC/F,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,KAAK;IACnB,WAAW,EAAE,IAAI;IACjB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,KAAK;IACnB,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,KAAK;CACxB,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAA4C,CAAC;AAEvH,MAAM,kBAAkB,GAAG,yFAAyF,CAAC;AAErH,0DAA0D;AAC1D,MAAM,UAAU,iBAAiB,CAAC,OAAe;IAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACzC,CAAC;AASD;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAe;IACxD,MAAM,GAAG,GAAgC,EAAE,CAAC;IAC5C,IAAI,IAAI,GAAmB,IAAI,CAAC;IAChC,IAAI,CAAC;QACJ,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,eAAe,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,GAAG,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,IAAI;QAAE,OAAO,GAAG,CAAC;IACtB,MAAM,KAAK,GAAG,CAAC,OAAgB,EAAQ,EAAE;QACxC,MAAM,I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E,MAAM,QAAQ,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC;QACjC,IAAI,KAAK,KAAK,SAAS,IAAI,QAAQ,EAAE,WAAW,KAAK,QAAQ;YAAE,SAAS;QACxE,IAAI,QAAQ,EAAE,QAAQ,EAAE,CAAC;YACxB,GAAG,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC1F,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACtC,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QACtD,CAAC;aAAM,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACxD,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAC/D,CAAC;IACF,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["/**\n * QTI test structure shared by backends and the client: the itemSessionControl cascade, the\n * session-start draw of selection and ordering, delivery order, the delivery-rules walk\n * (branch rules, preconditions, eligibility), and test-scope expressions.\n */\n\nimport {\n\tbuildExpression,\n\tDeclarationContext,\n\ttype DeclarationMap,\n\tdurationSecondsFromMilliseconds,\n\tevalExpr,\n\tparseXml,\n\ttype QtiValue,\n\tqtiNull,\n\tqtiValue,\n} from '@pie-qti/qti-processing';\nimport type {\n\tSecureAssessment,\n\tSecureBranchRule,\n\tSecureItemRef,\n\tSecureItemSessionControl,\n\tSecureSection,\n\tSecureSectionComponent,\n\tSecureTestPart,\n\tTestOutcomeValue,\n\tTestOutcomeValues,\n} from '../integration/api-contract.js';\n\nexport type ResolvedItemSessionControl = Required<SecureItemSessionControl>;\n\n/** QTI itemSessionControl defaults, applied where no level of the cascade sets an attribute. */\nexport const DEFAULT_ITEM_SESSION_CONTROL: Readonly<ResolvedItemSessionControl> = Object.freeze({\n\tmaxAttempts: 1,\n\tshowFeedback: false,\n\tallowReview: true,\n\tshowSolution: false,\n\tallowComment: false,\n\tallowSkipping: true,\n\tvalidateResponses: false,\n});\n\nconst ITEM_SESSION_CONTROL_KEYS = Object.keys(DEFAULT_ITEM_SESSION_CONTROL) as Array<keyof ResolvedItemSessionControl>;\n\nconst ADAPTIVE_ITEM_ROOT = /<(?:[\\w-]+:)?(?:qti-assessment-item|assessmentItem)\\b[^>]*\\badaptive\\s*=\\s*[\"']true[\"']/;\n\n/** True when the item root declares `adaptive=\"true\"`. */\nexport function isAdaptiveItemXml(itemXml: string): boolean {\n\treturn ADAPTIVE_ITEM_ROOT.test(itemXml);\n}\n\nexport interface EndAttemptInteractionInfo {\n\t/** The response declaration the interaction is bound to. */\n\tresponseIdentifier: string;\n\t/** QTI `countAttempt` (QTI 3 `count-attempt`); true unless authored as false. */\n\tcountAttempt: boolean;\n}\n\n/**\n * The item's endAttemptInteraction bindings, read from the item XML. Assessment delivery uses this\n * to recognize an end-attempt response on the session's normal response path: activation counts the\n * attempt unless authored with countAttempt=\"false\" (a hint request).\n */\nexport function endAttemptInteractionInfo(itemXml: string): EndAttemptInteractionInfo[] {\n\tconst out: EndAttemptInteractionInfo[] = [];\n\tlet root: Element | null = null;\n\ttry {\n\t\troot = parseXml(itemXml).documentElement;\n\t} catch {\n\t\treturn out;\n\t}\n\tif (!root) return out;\n\tconst visit = (element: Element): void => {\n\t\tconst name = toCanonicalQtiName(element.localName ?? element.nodeName).toLowerCase();\n\t\tif (name === 'endattemptinteraction') {\n\t\t\tconst responseIdentifier =\n\t\t\t\telement.getAttribute('responseIdentifier') ?? element.getAttribute('response-identifier');\n\t\t\tconst raw = element.getAttribute('countAttempt') ?? element.getAttribute('count-attempt');\n\t\t\tif (responseIdentifier) {\n\t\t\t\tout.push({\n\t\t\t\t\tresponseIdentifier,\n\t\t\t\t\tcountAttempt: raw ? raw.trim().toLowerCase() !== 'false' : true,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tfor (let child = element.firstChild; child; child = child.nextSibling) {\n\t\t\tif (child.nodeType === 1) visit(child as Element);\n\t\t}\n\t};\n\tvisit(root);\n\treturn out;\n}\n\n/**\n * Effective itemSessionControl for an item: the test part, each enclosing section from outer to\n * inner, then the item ref, each set attribute overriding the level above. Adaptive items allow\n * unlimited attempts whatever maxAttempts says.\n */\nexport function resolveItemSessionControl(\n\ttestPart: SecureTestPart,\n\tsections: readonly SecureSection[],\n\titem: SecureItemRef,\n): ResolvedItemSessionControl {\n\tconst out: ResolvedItemSessionControl = { ...DEFAULT_ITEM_SESSION_CONTROL };\n\tconst levels = [testPart.itemSessionControl, ...sections.map((s) => s.itemSessionControl), item.itemSessionControl];\n\tfor (const level of levels) {\n\t\tif (!level) continue;\n\t\tfor (const key of ITEM_SESSION_CONTROL_KEYS) {\n\t\t\tconst value = level[key];\n\t\t\tif (value === undefined || (typeof value === 'number' && !Number.isFinite(value))) continue;\n\t\t\t(out as Record<string, unknown>)[key] = value;\n\t\t}\n\t}\n\tif (isAdaptiveItemXml(item.itemXml)) out.maxAttempts = 0;\n\treturn out;\n}\n\n/** Direct delivery components of a section, in document order. */\nexport function sectionComponents(section: SecureSection): SecureSectionComponent[] {\n\treturn section.children\n\t\t? [...section.children]\n\t\t: [\n\t\t\t...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item' as const, item })),\n\t\t\t...(section.sections ?? []).map((child) => ({ type: 'section' as const, section: child })),\n\t\t];\n}\n\nexport interface DeliveredItem {\n\titem: SecureItemRef;\n\ttestPart: SecureTestPart;\n\t/** Enclosing sections, outermost first. */\n\tsections: SecureSection[];\n}\n\n/** Items in delivery order. Draws nothing: call it on an assessment the backend has drawn. */\nexport function deliveredItems(assessment: SecureAssessment): DeliveredItem[] {\n\tconst out: DeliveredItem[] = [];\n\tconst visit = (section: SecureSection, testPart: SecureTestPart, path: SecureSection[]): void => {\n\t\tconst sections = [...path, section];\n\t\tfor (const component of sectionComponents(section)) {\n\t\t\tif (component.type === 'item') out.push({ item: component.item, testPart, sections });\n\t\t\telse visit(component.section, testPart, sections);\n\t\t}\n\t};\n\tfor (const testPart of assessment.testParts ?? []) {\n\t\tfor (const section of testPart.sections ?? []) visit(section, testPart, []);\n\t}\n\treturn out;\n}\n\n/**\n * Next item after `delivered[index]`. Branch rules come first: the item's, then each enclosing\n * section's it ends (inner to outer), then the test part's when it ends that too. Item and\n * section rules apply in linear navigation only. With no matching rule, navigation falls through\n * to the following item. Preconditions then skip forward from the target. EXIT_TEST means the\n * remaining items are all skipped; undefined means the current item was the last. `onError`\n * receives any condition evaluation failure (see `evaluateTestCondition`).\n */\nexport function nextItemIdentifier(\n\tassessment: SecureAssessment,\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): string | undefined {\n\tconst start = branchTarget(assessment, delivered, index, decls, rng, onError) ?? index + 1;\n\tconst next = firstEligibleItem(assessment, delivered, start, delivered[index], decls, rng, onError);\n\treturn next ?? (index + 1 < delivered.length ? 'EXIT_TEST' : undefined);\n}\n\nfunction branchTarget(\n\tassessment: SecureAssessment,\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): number | undefined {\n\tconst current = delivered[index]!;\n\tconst following = delivered[index + 1];\n\tconst linear = isLinear(assessment, current.testPart);\n\tconst holders: Array<{ rules?: SecureBranchRule[]; exitSection?: SecureSection }> = [];\n\tif (linear) {\n\t\tholders.push({ rules: current.item.branchRule, exitSection: current.sections[current.sections.length - 1] });\n\t\tfor (let level = current.sections.length - 1; level >= 0; level--) {\n\t\t\tconst section = current.sections[level]!;\n\t\t\tif (following?.sections.includes(section)) break;\n\t\t\tholders.push({ rules: section.branchRule, exitSection: current.sections[level - 1] });\n\t\t}\n\t}\n\tif (following?.testPart !== current.testPart) holders.push({ rules: current.testPart.branchRule });\n\n\tfor (const { rules, exitSection } of holders) {\n\t\tfor (const rule of rules ?? []) {\n\t\t\tif (rule.conditionXml && !evaluateTestCondition(rule.conditionXml, decls, rng, onError)) continue;\n\t\t\tconst target = resolveBranchTarget(rule.target, delivered, index, exitSection);\n\t\t\tif (target !== undefined) return target;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The delivered-item shape literal branch-target resolution reads (`DeliveredItem` and `FlatItem` both). */\nexport type ScopedDeliveredItem = {\n\titem: { identifier: string };\n\t/** Enclosing sections, outermost first. */\n\tsections: readonly { identifier: string }[];\n\ttestPart: { identifier: string };\n};\n\n/**\n * The one literal branch-target resolver both live engines share — the reference backend's\n * `resolveBranchTarget` and the client's `exitBoundaries.branchTargetIndex` — so identical\n * branch XML cannot branch differently on the two paths. Forward-only per QTI 2.2 §5.15\n * (\"the test jumps forward … the target must refer to an item or section … that has not yet\n * been presented\"): the first delivered item strictly after `currentIndex` whose item,\n * enclosing-section, or test-part identifier matches `target`, tried in that order;\n * `undefined` when none does. A target naming an already-presented item therefore resolves\n * to nothing (the rule is skipped, delivery falls through), never backwards.\n */\nexport function firstForwardBranchTarget(\n\ttarget: string,\n\titems: readonly ScopedDeliveredItem[],\n\tcurrentIndex: number,\n): number | undefined {\n\treturn (\n\t\tfirstAfter(items, currentIndex, (item) => item.item.identifier === target) ??\n\t\tfirstAfter(items, currentIndex, (item) => item.sections.some((section) => section.identifier === target)) ??\n\t\tfirstAfter(items, currentIndex, (item) => item.testPart.identifier === target)\n\t);\n}\n\n/** The first element strictly after `from` that satisfies `match`; undefined when none does. */\nfunction firstAfter<T>(items: readonly T[], from: number, match: (item: T) => boolean): number | undefined {\n\tfor (let j = from + 1; j < items.length; j++) if (match(items[j]!)) return j;\n\treturn undefined;\n}\n\n/** Index a branch target resolves to, forward of `index`; delivered.length ends the test. */\nfunction resolveBranchTarget(\n\ttarget: string,\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\texitSection: SecureSection | undefined,\n): number | undefined {\n\tconst current = delivered[index]!;\n\tswitch (target) {\n\t\tcase 'EXIT_TEST':\n\t\t\treturn delivered.length;\n\t\tcase 'EXIT_TESTPART':\n\t\t\treturn firstAfter(delivered, index, (d) => d.testPart !== current.testPart) ?? delivered.length;\n\t\tcase 'EXIT_SECTION':\n\t\t\tif (!exitSection) return undefined;\n\t\t\treturn firstAfter(delivered, index, (d) => !d.sections.includes(exitSection)) ?? delivered.length;\n\t\tdefault:\n\t\t\treturn firstForwardBranchTarget(target, delivered, index);\n\t}\n}\n\n/**\n * First item from `start` whose preconditions hold. A test part's are checked on entering it in\n * any navigation mode; a newly entered section's (outermost first) and the item's only in linear\n * navigation. A failing part or section skips everything inside it. `onError` receives any\n * condition evaluation failure (see `evaluateTestCondition`).\n */\nexport function firstEligibleItem(\n\tassessment: SecureAssessment,\n\tdelivered: DeliveredItem[],\n\tstart: number,\n\tfrom: DeliveredItem | undefined,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): string | undefined {\n\tconst holds = (conditions: string[] | undefined): boolean =>\n\t\t(conditions ?? []).every((condition) => evaluateTestCondition(condition, decls, rng, onError));\n\tconst skipPast = (j: number, inside: (d: DeliveredItem) => boolean): number => {\n\t\tlet next = j + 1;\n\t\twhile (next < delivered.length && inside(delivered[next]!)) next++;\n\t\treturn next;\n\t};\n\tlet j = start;\n\tcandidates: while (j < delivered.length) {\n\t\tconst candidate = delivered[j]!;\n\t\tconst previous = j === start ? from : delivered[j - 1];\n\t\tif (candidate.testPart !== previous?.testPart && !holds(candidate.testPart.preConditions)) {\n\t\t\tj = skipPast(j, (d) => d.testPart === candidate.testPart);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isLinear(assessment, candidate.testPart)) {\n\t\t\tfor (const section of candidate.sections) {\n\t\t\t\tif (previous?.sections.includes(section) || holds(section.preConditions)) continue;\n\t\t\t\tj = skipPast(j, (d) => d.sections.includes(section));\n\t\t\t\tcontinue candidates;\n\t\t\t}\n\t\t\tif (!holds(candidate.item.preConditions)) {\n\t\t\t\tj++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\treturn candidate.item.identifier;\n\t}\n\treturn undefined;\n}\n\nfunction isLinear(assessment: SecureAssessment, testPart: SecureTestPart): boolean {\n\treturn (testPart.navigationMode ?? assessment.navigationMode) === 'linear';\n}\n\n/**\n * Draws selection and ordering for one session. Required children are always selected; selected\n * children keep source order before ordering shuffles the non-fixed ones. A child selected more\n * than once with replacement is cloned, its identifier and every descendant identifier suffixed\n * `.2`, `.3` and so on. An invisible child section with keepTogether false is mixed into its\n * parent's shuffle. The result carries no selection or ordering, so drawing it again changes\n * nothing.\n */\nexport function drawAssessment(assessment: SecureAssessment, rng: () => number): SecureAssessment {\n\tconst copy = structuredClone(assessment);\n\treturn {\n\t\t...copy,\n\t\ttestParts: copy.testParts.map((testPart) => ({\n\t\t\t...testPart,\n\t\t\tsections: testPart.sections.map((section) => drawSection(section, rng)),\n\t\t})),\n\t};\n}\n\nfunction drawSection(section: SecureSection, rng: () => number): SecureSection {\n\tlet components = sectionComponents(section);\n\tif (section.selection) components = selectComponents(section, components, rng);\n\tcomponents = components.map((component) =>\n\t\tcomponent.type === 'section' ? { type: 'section', section: drawSection(component.section, rng) } : component\n\t);\n\n\tif (section.ordering?.shuffle) {\n\t\tconst sourceOf = new Map<SecureSection, SecureSection>();\n\t\tconst expanded: SecureSectionComponent[] = [];\n\t\tfor (const component of components) {\n\t\t\tif (component.type === 'section' && !component.section.visible && component.section.keepTogether === false) {\n\t\t\t\tfor (const child of sectionComponents(component.section)) {\n\t\t\t\t\tconst fragment = withComponents({ ...component.section, fixed: isFixedSectionComponent(child) }, [child]);\n\t\t\t\t\tsourceOf.set(fragment, component.section);\n\t\t\t\t\texpanded.push({ type: 'section', section: fragment });\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\texpanded.push(component);\n\t\t\t}\n\t\t}\n\t\tcomponents = mergeAdjacentFragments(shuffleSectionComponents(expanded, rng), sourceOf);\n\t}\n\n\tconst { selection: _selection, ordering: _ordering, ...rest } = section;\n\treturn withComponents(rest, components);\n}\n\nfunction selectComponents(\n\tsection: SecureSection,\n\tcomponents: SecureSectionComponent[],\n\trng: () => number,\n): SecureSectionComponent[] {\n\tconst count = Math.max(0, section.selection?.select ?? components.length);\n\tconst indexed = components.map((component, sourceIndex) => ({ component, sourceIndex }));\n\tconst required = indexed.filter(({ component }) => isRequiredSectionComponent(component));\n\tif (count < required.length) {\n\t\tthrow new Error(\n\t\t\t`Section \"${section.identifier}\" selects ${count} components but contains ${required.length} required components.`,\n\t\t);\n\t}\n\tlet chosen: typeof indexed;\n\tif (section.selection?.withReplacement === true) {\n\t\tif (indexed.length === 0 && count > 0) {\n\t\t\tthrow new Error(`Section \"${section.identifier}\" selects ${count} components but contains none.`);\n\t\t}\n\t\tconst draws = Array.from(\n\t\t\t{ length: count - required.length },\n\t\t\t() => indexed[Math.min(indexed.length - 1, Math.floor(rng() * indexed.length))]!,\n\t\t);\n\t\tchosen = [...required, ...draws];\n\t} else {\n\t\tif (count > indexed.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Section \"${section.identifier}\" selects ${count} components without replacement but only contains ${indexed.length}.`,\n\t\t\t);\n\t\t}\n\t\tconst optional = shuffleArray(indexed.filter(({ component }) => !isRequiredSectionComponent(component)), rng);\n\t\tchosen = [...required, ...optional.slice(0, count - required.length)];\n\t}\n\tconst seen = new Map<number, number>();\n\treturn chosen\n\t\t.sort((a, b) => a.sourceIndex - b.sourceIndex)\n\t\t.map(({ component, sourceIndex }) => {\n\t\t\tconst occurrence = (seen.get(sourceIndex) ?? 0) + 1;\n\t\t\tseen.set(sourceIndex, occurrence);\n\t\t\treturn occurrence === 1 ? component : renameComponent(component, `.${occurrence}`);\n\t\t});\n}\n\nfunction renameComponent(component: SecureSectionComponent, suffix: string): SecureSectionComponent {\n\tconst copy = structuredClone(component);\n\tconst renamed = new Set<object>();\n\tconst renameItem = (item: SecureItemRef): void => {\n\t\tif (renamed.has(item)) return;\n\t\trenamed.add(item);\n\t\titem.identifier += suffix;\n\t};\n\tconst renameSection = (section: SecureSection): void => {\n\t\tif (renamed.has(section)) return;\n\t\trenamed.add(section);\n\t\tsection.identifier += suffix;\n\t\tfor (const item of section.assessmentItemRefs ?? []) renameItem(item);\n\t\tfor (const child of section.sections ?? []) renameSection(child);\n\t\tfor (const child of section.children ?? []) {\n\t\t\tif (child.type === 'item') renameItem(child.item);\n\t\t\telse renameSection(child.section);\n\t\t}\n\t};\n\tif (copy.type === 'item') renameItem(copy.item);\n\telse renameSection(copy.section);\n\treturn copy;\n}\n\nfunction withComponents(section: SecureSection, components: SecureSectionComponent[]): SecureSection {\n\tconst sections = components.flatMap((c) => (c.type === 'section' ? [c.section] : []));\n\treturn {\n\t\t...section,\n\t\tchildren: components,\n\t\tassessmentItemRefs: components.flatMap((c) => (c.type === 'item' ? [c.item] : [])),\n\t\tsections: sections.length > 0 ? sections : undefined,\n\t};\n}\n\nfunction mergeAdjacentFragments(\n\tcomponents: SecureSectionComponent[],\n\tsourceOf: Map<SecureSection, SecureSection>,\n): SecureSectionComponent[] {\n\tconst out: SecureSectionComponent[] = [];\n\tfor (const component of components) {\n\t\tconst previous = out[out.length - 1];\n\t\tconst source = component.type === 'section' ? sourceOf.get(component.section) : undefined;\n\t\tif (source && previous?.type === 'section' && sourceOf.get(previous.section) === source && component.type === 'section') {\n\t\t\tconst merged = withComponents(previous.section, [\n\t\t\t\t...sectionComponents(previous.section),\n\t\t\t\t...sectionComponents(component.section),\n\t\t\t]);\n\t\t\tsourceOf.set(merged, source);\n\t\t\tout[out.length - 1] = { type: 'section', section: merged };\n\t\t} else {\n\t\t\tout.push(component);\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Fisher-Yates shuffle using a provided RNG (returns a new array). */\nexport function shuffleArray<T>(arr: readonly T[], rng: () => number): T[] {\n\tconst out = [...arr];\n\tfor (let i = out.length - 1; i > 0; i--) {\n\t\tconst j = Math.floor(rng() * (i + 1));\n\t\t[out[i], out[j]] = [out[j]!, out[i]!];\n\t}\n\treturn out;\n}\n\nfunction isRequiredSectionComponent(component: SecureSectionComponent): boolean {\n\treturn component.type === 'item' ? component.item.required === true : component.section.required === true;\n}\n\nfunction isFixedSectionComponent(component: SecureSectionComponent): boolean {\n\treturn component.type === 'item' ? component.item.fixed === true : component.section.fixed === true;\n}\n\n/** Shuffle non-fixed children while retaining fixed children at their post-selection positions. */\nfunction shuffleSectionComponents(components: SecureSectionComponent[], rng: () => number): SecureSectionComponent[] {\n\tconst result = [...components];\n\tconst movableIndexes = components.flatMap((component, index) => (isFixedSectionComponent(component) ? [] : [index]));\n\tconst shuffled = shuffleArray(movableIndexes.map((index) => components[index]!), rng);\n\tfor (let index = 0; index < movableIndexes.length; index++) {\n\t\tresult[movableIndexes[index]!] = shuffled[index]!;\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Test-scope expressions\n// ---------------------------------------------------------------------------\n\n/** Canonical QTI 2.x element name for a QTI 2.x or QTI 3 (`qti-` kebab-case) element name. */\nexport function toCanonicalQtiName(name: string | null | undefined): string {\n\tconst withoutPrefix = (name ?? '').replace(/^qti-/, '');\n\treturn withoutPrefix.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Reads QTI 2.x camelCase and QTI 3 `qti-` kebab-case element names alike. */\nexport const qtiElementNameMapper = {\n\tversion: 'qti2x-or-qti3',\n\ttoCanonical: (elementName: string) => toCanonicalQtiName(elementName).toLowerCase(),\n\ttoNative: (canonicalName: string) => canonicalName,\n\tisValidElementName: () => true,\n};\n\nfunction toQtiValue(baseType: string, cardinality: string, value: unknown): QtiValue {\n\tif (value === null || value === undefined) return qtiNull(baseType as never, cardinality as never);\n\treturn qtiValue(baseType as never, cardinality as never, value);\n}\n\nfunction declaration(identifier: string, value: QtiValue, defaultValue: QtiValue = value): DeclarationMap[string] {\n\treturn {\n\t\tidentifier,\n\t\tbaseType: value.baseType,\n\t\tcardinality: value.cardinality ?? 'single',\n\t\tdefaultValue,\n\t\tvalue: { ...value },\n\t};\n}\n\n/**\n * Declarations for the test's outcome variables, set to `outcomes` where given and to their\n * defaults otherwise. A numeric outcome with no declared default starts at 0.\n */\nexport function testOutcomeDeclarations(\n\tassessment: SecureAssessment,\n\toutcomes?: TestOutcomeValues | null,\n): DeclarationMap {\n\tconst decls: DeclarationMap = {};\n\tfor (const d of assessment.outcomeDeclarations ?? []) {\n\t\tconst defaultValue =\n\t\t\td.defaultValue !== undefined\n\t\t\t\t? toQtiValue(d.baseType, d.cardinality, d.defaultValue)\n\t\t\t\t: d.baseType === 'float' || d.baseType === 'integer'\n\t\t\t\t\t? qtiValue(d.baseType, 'single', 0)\n\t\t\t\t\t: qtiNull(d.baseType as never, d.cardinality as never);\n\t\tconst current = outcomes && d.identifier in outcomes\n\t\t\t? toQtiValue(d.baseType, d.cardinality, outcomes[d.identifier] as TestOutcomeValue)\n\t\t\t: defaultValue;\n\t\tdecls[d.identifier] = {\n\t\t\tidentifier: d.identifier,\n\t\t\tbaseType: d.baseType as never,\n\t\t\tcardinality: d.cardinality as never,\n\t\t\tdefaultValue,\n\t\t\tvalue: { ...current },\n\t\t};\n\t}\n\treturn decls;\n}\n\n/**\n * Adds item variables as `itemIdentifier.VARIABLE`, the form test-scope expressions use, and the\n * `unprefixed` variables under their own identifiers where the test declares no such outcome.\n */\nexport function addItemVariableDeclarations(\n\tdecls: DeclarationMap,\n\titemVariables: Record<string, Record<string, QtiValue>>,\n\tunprefixed: Record<string, QtiValue> = {},\n): DeclarationMap {\n\tfor (const [itemIdentifier, variables] of Object.entries(itemVariables)) {\n\t\tfor (const [identifier, value] of Object.entries(variables)) {\n\t\t\tconst key = `${itemIdentifier}.${identifier}`;\n\t\t\tif (!decls[key]) decls[key] = declaration(key, value);\n\t\t}\n\t}\n\tfor (const [identifier, value] of Object.entries(unprefixed)) {\n\t\tif (!decls[identifier]) decls[identifier] = declaration(identifier, value);\n\t}\n\treturn decls;\n}\n\n/** Millisecond scope clocks the timing state carries; absent clocks read as 0 seconds. */\nexport interface ScopeTiming {\n\t/** Total assessment elapsed time (ms). */\n\ttotalTime?: number;\n\t/** Elapsed time per testPart identifier (ms). */\n\ttestPartTimes?: Record<string, number>;\n\t/** Elapsed time per section identifier (ms). */\n\tsectionTimes?: Record<string, number>;\n}\n\n/**\n * Adds the QTI built-in duration variables test-scope expressions read: `duration` for the whole\n * test, `TESTPART_ID.duration` and `SECTION_ID.duration` for each delivered part and section.\n * QTI durations are seconds; the timing state keeps milliseconds, so the values are converted.\n * Authored identifiers win: an existing declaration is never replaced.\n */\nexport function addScopeDurationDeclarations(\n\tdecls: DeclarationMap,\n\tassessment: SecureAssessment,\n\ttiming: ScopeTiming | undefined,\n): DeclarationMap {\n\tconst durationSeconds = (ms: number | undefined): number =>\n\t\tdurationSecondsFromMilliseconds(Number(ms) || 0);\n\tconst putDuration = (identifier: string, seconds: number): void => {\n\t\tif (!decls[identifier]) decls[identifier] = declaration(identifier, qtiValue('duration', 'single', seconds));\n\t};\n\tputDuration('duration', durationSeconds(timing?.totalTime));\n\tconst visitSections = (sections: readonly SecureSection[]): void => {\n\t\tfor (const section of sections) {\n\t\t\tputDuration(`${section.identifier}.duration`, durationSeconds(timing?.sectionTimes?.[section.identifier]));\n\t\t\tvisitSections(section.sections ?? []);\n\t\t}\n\t};\n\tfor (const testPart of assessment.testParts ?? []) {\n\t\tputDuration(`${testPart.identifier}.duration`, durationSeconds(timing?.testPartTimes?.[testPart.identifier]));\n\t\tvisitSections(testPart.sections ?? []);\n\t}\n\treturn decls;\n}\n\n/** Item variables with each variableMapping's source also readable as its target identifier. */\nexport function applyVariableMappings(\n\tvariables: Record<string, QtiValue>,\n\tmappings: SecureItemRef['variableMappings'],\n): Record<string, QtiValue> {\n\tif (!mappings?.length) return variables;\n\tconst out = { ...variables };\n\tfor (const { sourceIdentifier, targetIdentifier } of mappings) {\n\t\tconst value = variables[sourceIdentifier];\n\t\tif (value) out[targetIdentifier] = value;\n\t}\n\treturn out;\n}\n\n/** Evaluates a serialized test-scope expression (QTI 2.x or 3) against `decls`. */\nexport function evaluateTestExpression(expressionXml: string, decls: DeclarationMap, rng: () => number): QtiValue {\n\tconst root = parseXml(expressionXml).documentElement;\n\tif (!root) return qtiNull();\n\tconst expr = buildExpression(root, { scope: 'test', elementNameMapper: qtiElementNameMapper });\n\treturn evalExpr({ ctx: new DeclarationContext(structuredClone(decls)), rng }, expr);\n}\n\n/**\n * True only when the expression evaluates to boolean true; NULL reads as false (QTI:\n * a NULL condition result is false).\n *\n * An evaluation ERROR also reads as false, but unlike a NULL it is reported: delivery\n * proceeds on the default path (a broken branchRule or preCondition must never abort a\n * candidate's test), yet the failure is never indistinguishable from an authored false.\n * Callers that own an error surface pass `onError` — the AssessmentPlayer reports a\n * coded `testConditionFailed` through `config.onError` — and without one the failure\n * stays a console warning (the reference backend's own evaluation).\n *\n * Documented divergence from the strict spec reading: QTI 2.1/3.0 leave undefined how\n * delivery proceeds when a condition expression cannot be evaluated; reading it as\n * false keeps delivery on the default path and reporting keeps it observable.\n */\nexport function evaluateTestCondition(\n\texpressionXml: string,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): boolean {\n\ttry {\n\t\tconst out = evaluateTestExpression(expressionXml, decls, rng);\n\t\treturn out.kind === 'value' && out.value === true;\n\t} catch (err) {\n\t\tif (onError) onError(expressionXml, err);\n\t\telse console.warn('[assessment-player] test condition failed to evaluate:', err);\n\t\treturn false;\n\t}\n}\n\n/** Plain value of a QTI value, null for NULL, in the shape item template defaults take. */\nexport function plainQtiValue(value: QtiValue): unknown {\n\treturn value.kind === 'value' ? value.value : null;\n}\n\n/** A serialized item-session variable, as `SerializedItemSessionState` carries it. */\ninterface SerializedVariableShape {\n\tbaseType?: string;\n\tcardinality: string;\n\tvalue: unknown;\n}\n\n/**\n * The QTI values of a serialized item session's response, outcome and template\n * variables (NULL where unset), keyed by variable identifier — the item's variables a\n * test-scope expression reads as `ITEM.VARIABLE`.\n */\nexport function itemSessionVariableValues(session: {\n\tresponseVariables?: Record<string, SerializedVariableShape>;\n\toutcomeVariables?: Record<string, SerializedVariableShape>;\n\ttemplateVariables?: Record<string, SerializedVariableShape>;\n}): Record<string, QtiValue> {\n\tconst out: Record<string, QtiValue> = {};\n\tfor (const group of [session.responseVariables, session.outcomeVariables, session.templateVariables]) {\n\t\tfor (const [identifier, variable] of Object.entries(group ?? {})) {\n\t\t\tout[identifier] = toQtiValue(variable.baseType as string, variable.cardinality, variable.value);\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * An item's variables as test-level branch rules and preconditions read them (`ITEM.VARIABLE`),\n * in the shape the reference backend records after a counted submission (its item test state):\n * the session's context (numAttempts, duration, completionStatus), template, outcome and response\n * variables, with `scoredOutcomes` — the backend's scored outcome values, authoritative where the\n * delivered item carries no response processing — over them, typed by the session's own\n * declarations (a value without one is read as the reference backend reads a bare score: a\n * number as float, anything else as string). Record outcomes keep the session's value.\n */\nexport function recordedItemVariableValues(\n\tsession:\n\t\t| {\n\t\t\t\tcontextVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\tresponseVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\toutcomeVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\ttemplateVariables?: Record<string, SerializedVariableShape>;\n\t\t }\n\t\t| undefined,\n\tscoredOutcomes: Record<string, unknown> | undefined,\n): Record<string, QtiValue> {\n\tconst out: Record<string, QtiValue> = {};\n\tfor (const group of [\n\t\tsession?.contextVariables,\n\t\tsession?.templateVariables,\n\t\tsession?.outcomeVariables,\n\t\tsession?.responseVariables,\n\t]) {\n\t\tfor (const [identifier, variable] of Object.entries(group ?? {})) {\n\t\t\tout[identifier] = toQtiValue(variable.baseType as string, variable.cardinality, variable.value);\n\t\t}\n\t}\n\tfor (const [identifier, value] of Object.entries(scoredOutcomes ?? {})) {\n\t\tconst declared = out[identifier];\n\t\tif (value === undefined || declared?.cardinality === 'record') continue;\n\t\tif (declared?.baseType) {\n\t\t\tout[identifier] = toQtiValue(declared.baseType, declared.cardinality ?? 'single', value);\n\t\t} else if (typeof value === 'number') {\n\t\t\tout[identifier] = qtiValue('float', 'single', value);\n\t\t} else if (value !== null && typeof value !== 'object') {\n\t\t\tout[identifier] = qtiValue('string', 'single', String(value));\n\t\t}\n\t}\n\treturn out;\n}\n"]}
1
+ {"version":3,"file":"testStructure.js","sourceRoot":"","sources":["../../src/core/testStructure.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACN,eAAe,EACf,kBAAkB,EAElB,+BAA+B,EAC/B,QAAQ,EACR,QAAQ,EAER,OAAO,EACP,QAAQ,GACR,MAAM,yBAAyB,CAAC;AAejC,gGAAgG;AAChG,MAAM,CAAC,MAAM,4BAA4B,GAAyC,MAAM,CAAC,MAAM,CAAC;IAC/F,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,KAAK;IACnB,WAAW,EAAE,IAAI;IACjB,YAAY,EAAE,KAAK;IACnB,YAAY,EAAE,KAAK;IACnB,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,KAAK;CACxB,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAA4C,CAAC;AAEvH,MAAM,kBAAkB,GAAG,yFAAyF,CAAC;AAErH,0DAA0D;AAC1D,MAAM,UAAU,iBAAiB,CAAC,OAAe;IAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACzC,CAAC;AASD;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAe;IACxD,MAAM,GAAG,GAAgC,EAAE,CAAC;IAC5C,IAAI,IAAI,GAAmB,IAAI,CAAC;IAChC,IAAI,CAAC;QACJ,IAAI,GAAG,QAAQ,CAAC,OAA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G,GAAG,CAAC,UAAU,CAAC,CAAC;QACjC,IAAI,KAAK,KAAK,SAAS,IAAI,QAAQ,EAAE,WAAW,KAAK,QAAQ;YAAE,SAAS;QACxE,IAAI,QAAQ,EAAE,QAAQ,EAAE,CAAC;YACxB,GAAG,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC1F,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACtC,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QACtD,CAAC;aAAM,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACxD,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAC/D,CAAC;IACF,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["/**\n * QTI test structure shared by backends and the client: the itemSessionControl cascade, the\n * session-start draw of selection and ordering, delivery order, the delivery-rules walk\n * (branch rules, preconditions, eligibility), and test-scope expressions.\n */\n\nimport {\n\tbuildExpression,\n\tDeclarationContext,\n\ttype DeclarationMap,\n\tdurationSecondsFromMilliseconds,\n\tevalExpr,\n\tparseXml,\n\ttype QtiValue,\n\tqtiNull,\n\tqtiValue,\n} from '@pie-qti/qti-processing';\nimport type {\n\tSecureAssessment,\n\tSecureBranchRule,\n\tSecureItemRef,\n\tSecureItemSessionControl,\n\tSecureSection,\n\tSecureSectionComponent,\n\tSecureTestPart,\n\tTestOutcomeValue,\n\tTestOutcomeValues,\n} from '../integration/api-contract.js';\n\nexport type ResolvedItemSessionControl = Required<SecureItemSessionControl>;\n\n/** QTI itemSessionControl defaults, applied where no level of the cascade sets an attribute. */\nexport const DEFAULT_ITEM_SESSION_CONTROL: Readonly<ResolvedItemSessionControl> = Object.freeze({\n\tmaxAttempts: 1,\n\tshowFeedback: false,\n\tallowReview: true,\n\tshowSolution: false,\n\tallowComment: false,\n\tallowSkipping: true,\n\tvalidateResponses: false,\n});\n\nconst ITEM_SESSION_CONTROL_KEYS = Object.keys(DEFAULT_ITEM_SESSION_CONTROL) as Array<keyof ResolvedItemSessionControl>;\n\nconst ADAPTIVE_ITEM_ROOT = /<(?:[\\w-]+:)?(?:qti-assessment-item|assessmentItem)\\b[^>]*\\badaptive\\s*=\\s*[\"']true[\"']/;\n\n/** True when the item root declares `adaptive=\"true\"`. */\nexport function isAdaptiveItemXml(itemXml: string): boolean {\n\treturn ADAPTIVE_ITEM_ROOT.test(itemXml);\n}\n\nexport interface EndAttemptInteractionInfo {\n\t/** The response declaration the interaction is bound to. */\n\tresponseIdentifier: string;\n\t/** QTI `countAttempt` (QTI 3 `count-attempt`); true unless authored as false. */\n\tcountAttempt: boolean;\n}\n\n/**\n * The item's endAttemptInteraction bindings, read from the item XML. Assessment delivery uses this\n * to recognize an end-attempt response on the session's normal response path: activation counts the\n * attempt unless authored with countAttempt=\"false\" (a hint request).\n */\nexport function endAttemptInteractionInfo(itemXml: string): EndAttemptInteractionInfo[] {\n\tconst out: EndAttemptInteractionInfo[] = [];\n\tlet root: Element | null = null;\n\ttry {\n\t\troot = parseXml(itemXml).documentElement;\n\t} catch {\n\t\treturn out;\n\t}\n\tif (!root) return out;\n\tconst visit = (element: Element): void => {\n\t\tconst name = toCanonicalQtiName(element.localName ?? element.nodeName).toLowerCase();\n\t\tif (name === 'endattemptinteraction') {\n\t\t\tconst responseIdentifier =\n\t\t\t\telement.getAttribute('responseIdentifier') ?? element.getAttribute('response-identifier');\n\t\t\tconst raw = element.getAttribute('countAttempt') ?? element.getAttribute('count-attempt');\n\t\t\tif (responseIdentifier) {\n\t\t\t\tout.push({\n\t\t\t\t\tresponseIdentifier,\n\t\t\t\t\tcountAttempt: raw ? raw.trim().toLowerCase() !== 'false' : true,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tfor (let child = element.firstChild; child; child = child.nextSibling) {\n\t\t\tif (child.nodeType === 1) visit(child as Element);\n\t\t}\n\t};\n\tvisit(root);\n\treturn out;\n}\n\n/**\n * Effective itemSessionControl for an item: the test part, each enclosing section from outer to\n * inner, then the item ref, each set attribute overriding the level above. Adaptive items allow\n * unlimited attempts whatever maxAttempts says.\n */\nexport function resolveItemSessionControl(\n\ttestPart: SecureTestPart,\n\tsections: readonly SecureSection[],\n\titem: SecureItemRef,\n): ResolvedItemSessionControl {\n\tconst out: ResolvedItemSessionControl = { ...DEFAULT_ITEM_SESSION_CONTROL };\n\tconst levels = [testPart.itemSessionControl, ...sections.map((s) => s.itemSessionControl), item.itemSessionControl];\n\tfor (const level of levels) {\n\t\tif (!level) continue;\n\t\tfor (const key of ITEM_SESSION_CONTROL_KEYS) {\n\t\t\tconst value = level[key];\n\t\t\tif (value === undefined || (typeof value === 'number' && !Number.isFinite(value))) continue;\n\t\t\t(out as Record<string, unknown>)[key] = value;\n\t\t}\n\t}\n\tif (isAdaptiveItemXml(item.itemXml)) out.maxAttempts = 0;\n\treturn out;\n}\n\n/** Direct delivery components of a section, in document order. */\nexport function sectionComponents(section: SecureSection): SecureSectionComponent[] {\n\treturn section.children\n\t\t? [...section.children]\n\t\t: [\n\t\t\t...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item' as const, item })),\n\t\t\t...(section.sections ?? []).map((child) => ({ type: 'section' as const, section: child })),\n\t\t];\n}\n\nexport interface DeliveredItem {\n\titem: SecureItemRef;\n\ttestPart: SecureTestPart;\n\t/** Enclosing sections, outermost first. */\n\tsections: SecureSection[];\n}\n\n/** Items in delivery order. Draws nothing: call it on an assessment the backend has drawn. */\nexport function deliveredItems(assessment: SecureAssessment): DeliveredItem[] {\n\tconst out: DeliveredItem[] = [];\n\tconst visit = (section: SecureSection, testPart: SecureTestPart, path: SecureSection[]): void => {\n\t\tconst sections = [...path, section];\n\t\tfor (const component of sectionComponents(section)) {\n\t\t\tif (component.type === 'item') out.push({ item: component.item, testPart, sections });\n\t\t\telse visit(component.section, testPart, sections);\n\t\t}\n\t};\n\tfor (const testPart of assessment.testParts ?? []) {\n\t\tfor (const section of testPart.sections ?? []) visit(section, testPart, []);\n\t}\n\treturn out;\n}\n\n/**\n * Next item after `delivered[index]`. Branch rules come first: the item's, then each enclosing\n * section's it ends (inner to outer), then the test part's when it ends that too. Item and\n * section rules apply in linear navigation only. With no matching rule, navigation falls through\n * to the following item. Preconditions then skip forward from the target. EXIT_TEST means the\n * remaining items are all skipped; undefined means the current item was the last. `onError`\n * receives any condition evaluation failure (see `evaluateTestCondition`).\n */\nexport function nextItemIdentifier(\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): string | undefined {\n\tconst start = branchTarget(delivered, index, decls, rng, onError) ?? index + 1;\n\tconst next = firstEligibleItem(delivered, start, delivered[index], decls, rng, onError);\n\treturn next ?? (index + 1 < delivered.length ? 'EXIT_TEST' : undefined);\n}\n\nfunction branchTarget(\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): number | undefined {\n\tconst current = delivered[index]!;\n\tconst following = delivered[index + 1];\n\tconst linear = current.testPart.navigationMode === 'linear';\n\tconst holders: Array<{ rules?: SecureBranchRule[]; exitSection?: SecureSection }> = [];\n\tif (linear) {\n\t\tholders.push({ rules: current.item.branchRule, exitSection: current.sections[current.sections.length - 1] });\n\t\tfor (let level = current.sections.length - 1; level >= 0; level--) {\n\t\t\tconst section = current.sections[level]!;\n\t\t\tif (following?.sections.includes(section)) break;\n\t\t\tholders.push({ rules: section.branchRule, exitSection: current.sections[level - 1] });\n\t\t}\n\t}\n\tif (following?.testPart !== current.testPart) holders.push({ rules: current.testPart.branchRule });\n\n\tfor (const { rules, exitSection } of holders) {\n\t\tfor (const rule of rules ?? []) {\n\t\t\tif (rule.conditionXml && !evaluateTestCondition(rule.conditionXml, decls, rng, onError)) continue;\n\t\t\tconst target = resolveBranchTarget(rule.target, delivered, index, exitSection);\n\t\t\tif (target !== undefined) return target;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The delivered-item shape literal branch-target resolution reads (`DeliveredItem` and `FlatItem` both). */\nexport type ScopedDeliveredItem = {\n\titem: { identifier: string };\n\t/** Enclosing sections, outermost first. */\n\tsections: readonly { identifier: string }[];\n\ttestPart: { identifier: string };\n};\n\n/**\n * The one literal branch-target resolver both live engines share — the reference backend's\n * `resolveBranchTarget` and the client's `exitBoundaries.branchTargetIndex` — so identical\n * branch XML cannot branch differently on the two paths. Forward-only per QTI 2.2 §5.15\n * (\"the test jumps forward … the target must refer to an item or section … that has not yet\n * been presented\"): the first delivered item strictly after `currentIndex` whose item,\n * enclosing-section, or test-part identifier matches `target`, tried in that order;\n * `undefined` when none does. A target naming an already-presented item therefore resolves\n * to nothing (the rule is skipped, delivery falls through), never backwards.\n */\nexport function firstForwardBranchTarget(\n\ttarget: string,\n\titems: readonly ScopedDeliveredItem[],\n\tcurrentIndex: number,\n): number | undefined {\n\treturn (\n\t\tfirstAfter(items, currentIndex, (item) => item.item.identifier === target) ??\n\t\tfirstAfter(items, currentIndex, (item) => item.sections.some((section) => section.identifier === target)) ??\n\t\tfirstAfter(items, currentIndex, (item) => item.testPart.identifier === target)\n\t);\n}\n\n/** The first element strictly after `from` that satisfies `match`; undefined when none does. */\nfunction firstAfter<T>(items: readonly T[], from: number, match: (item: T) => boolean): number | undefined {\n\tfor (let j = from + 1; j < items.length; j++) if (match(items[j]!)) return j;\n\treturn undefined;\n}\n\n/** Index a branch target resolves to, forward of `index`; delivered.length ends the test. */\nfunction resolveBranchTarget(\n\ttarget: string,\n\tdelivered: DeliveredItem[],\n\tindex: number,\n\texitSection: SecureSection | undefined,\n): number | undefined {\n\tconst current = delivered[index]!;\n\tswitch (target) {\n\t\tcase 'EXIT_TEST':\n\t\t\treturn delivered.length;\n\t\tcase 'EXIT_TESTPART':\n\t\t\treturn firstAfter(delivered, index, (d) => d.testPart !== current.testPart) ?? delivered.length;\n\t\tcase 'EXIT_SECTION':\n\t\t\tif (!exitSection) return undefined;\n\t\t\treturn firstAfter(delivered, index, (d) => !d.sections.includes(exitSection)) ?? delivered.length;\n\t\tdefault:\n\t\t\treturn firstForwardBranchTarget(target, delivered, index);\n\t}\n}\n\n/**\n * First item from `start` whose preconditions hold. A test part's are checked on entering it in\n * any navigation mode; a newly entered section's (outermost first) and the item's only in linear\n * navigation. A failing part or section skips everything inside it. `onError` receives any\n * condition evaluation failure (see `evaluateTestCondition`).\n */\nexport function firstEligibleItem(\n\tdelivered: DeliveredItem[],\n\tstart: number,\n\tfrom: DeliveredItem | undefined,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): string | undefined {\n\tconst holds = (conditions: string[] | undefined): boolean =>\n\t\t(conditions ?? []).every((condition) => evaluateTestCondition(condition, decls, rng, onError));\n\tconst skipPast = (j: number, inside: (d: DeliveredItem) => boolean): number => {\n\t\tlet next = j + 1;\n\t\twhile (next < delivered.length && inside(delivered[next]!)) next++;\n\t\treturn next;\n\t};\n\tlet j = start;\n\tcandidates: while (j < delivered.length) {\n\t\tconst candidate = delivered[j]!;\n\t\tconst previous = j === start ? from : delivered[j - 1];\n\t\tif (candidate.testPart !== previous?.testPart && !holds(candidate.testPart.preConditions)) {\n\t\t\tj = skipPast(j, (d) => d.testPart === candidate.testPart);\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate.testPart.navigationMode === 'linear') {\n\t\t\tfor (const section of candidate.sections) {\n\t\t\t\tif (previous?.sections.includes(section) || holds(section.preConditions)) continue;\n\t\t\t\tj = skipPast(j, (d) => d.sections.includes(section));\n\t\t\t\tcontinue candidates;\n\t\t\t}\n\t\t\tif (!holds(candidate.item.preConditions)) {\n\t\t\t\tj++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\treturn candidate.item.identifier;\n\t}\n\treturn undefined;\n}\n\n\n/**\n * Draws selection and ordering for one session. Required children are always selected; selected\n * children keep source order before ordering shuffles the non-fixed ones. A child selected more\n * than once with replacement is cloned, its identifier and every descendant identifier suffixed\n * `.2`, `.3` and so on. An invisible child section with keepTogether false is mixed into its\n * parent's shuffle. The result carries no selection or ordering, so drawing it again changes\n * nothing.\n */\nexport function drawAssessment(assessment: SecureAssessment, rng: () => number): SecureAssessment {\n\tconst copy = structuredClone(assessment);\n\treturn {\n\t\t...copy,\n\t\ttestParts: copy.testParts.map((testPart) => ({\n\t\t\t...testPart,\n\t\t\tsections: testPart.sections.map((section) => drawSection(section, rng)),\n\t\t})),\n\t};\n}\n\nfunction drawSection(section: SecureSection, rng: () => number): SecureSection {\n\tlet components = sectionComponents(section);\n\tif (section.selection) components = selectComponents(section, components, rng);\n\tcomponents = components.map((component) =>\n\t\tcomponent.type === 'section' ? { type: 'section', section: drawSection(component.section, rng) } : component\n\t);\n\n\tif (section.ordering?.shuffle) {\n\t\tconst sourceOf = new Map<SecureSection, SecureSection>();\n\t\tconst expanded: SecureSectionComponent[] = [];\n\t\tfor (const component of components) {\n\t\t\tif (component.type === 'section' && !component.section.visible && component.section.keepTogether === false) {\n\t\t\t\tfor (const child of sectionComponents(component.section)) {\n\t\t\t\t\tconst fragment = withComponents({ ...component.section, fixed: isFixedSectionComponent(child) }, [child]);\n\t\t\t\t\tsourceOf.set(fragment, component.section);\n\t\t\t\t\texpanded.push({ type: 'section', section: fragment });\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\texpanded.push(component);\n\t\t\t}\n\t\t}\n\t\tcomponents = mergeAdjacentFragments(shuffleSectionComponents(expanded, rng), sourceOf);\n\t}\n\n\tconst { selection: _selection, ordering: _ordering, ...rest } = section;\n\treturn withComponents(rest, components);\n}\n\nfunction selectComponents(\n\tsection: SecureSection,\n\tcomponents: SecureSectionComponent[],\n\trng: () => number,\n): SecureSectionComponent[] {\n\tconst count = Math.max(0, section.selection?.select ?? components.length);\n\tconst indexed = components.map((component, sourceIndex) => ({ component, sourceIndex }));\n\tconst required = indexed.filter(({ component }) => isRequiredSectionComponent(component));\n\tif (count < required.length) {\n\t\tthrow new Error(\n\t\t\t`Section \"${section.identifier}\" selects ${count} components but contains ${required.length} required components.`,\n\t\t);\n\t}\n\tlet chosen: typeof indexed;\n\tif (section.selection?.withReplacement === true) {\n\t\tif (indexed.length === 0 && count > 0) {\n\t\t\tthrow new Error(`Section \"${section.identifier}\" selects ${count} components but contains none.`);\n\t\t}\n\t\tconst draws = Array.from(\n\t\t\t{ length: count - required.length },\n\t\t\t() => indexed[Math.min(indexed.length - 1, Math.floor(rng() * indexed.length))]!,\n\t\t);\n\t\tchosen = [...required, ...draws];\n\t} else {\n\t\tif (count > indexed.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Section \"${section.identifier}\" selects ${count} components without replacement but only contains ${indexed.length}.`,\n\t\t\t);\n\t\t}\n\t\tconst optional = shuffleArray(indexed.filter(({ component }) => !isRequiredSectionComponent(component)), rng);\n\t\tchosen = [...required, ...optional.slice(0, count - required.length)];\n\t}\n\tconst seen = new Map<number, number>();\n\treturn chosen\n\t\t.sort((a, b) => a.sourceIndex - b.sourceIndex)\n\t\t.map(({ component, sourceIndex }) => {\n\t\t\tconst occurrence = (seen.get(sourceIndex) ?? 0) + 1;\n\t\t\tseen.set(sourceIndex, occurrence);\n\t\t\treturn occurrence === 1 ? component : renameComponent(component, `.${occurrence}`);\n\t\t});\n}\n\nfunction renameComponent(component: SecureSectionComponent, suffix: string): SecureSectionComponent {\n\tconst copy = structuredClone(component);\n\tconst renamed = new Set<object>();\n\tconst renameItem = (item: SecureItemRef): void => {\n\t\tif (renamed.has(item)) return;\n\t\trenamed.add(item);\n\t\titem.identifier += suffix;\n\t};\n\tconst renameSection = (section: SecureSection): void => {\n\t\tif (renamed.has(section)) return;\n\t\trenamed.add(section);\n\t\tsection.identifier += suffix;\n\t\tfor (const item of section.assessmentItemRefs ?? []) renameItem(item);\n\t\tfor (const child of section.sections ?? []) renameSection(child);\n\t\tfor (const child of section.children ?? []) {\n\t\t\tif (child.type === 'item') renameItem(child.item);\n\t\t\telse renameSection(child.section);\n\t\t}\n\t};\n\tif (copy.type === 'item') renameItem(copy.item);\n\telse renameSection(copy.section);\n\treturn copy;\n}\n\nfunction withComponents(section: SecureSection, components: SecureSectionComponent[]): SecureSection {\n\tconst sections = components.flatMap((c) => (c.type === 'section' ? [c.section] : []));\n\treturn {\n\t\t...section,\n\t\tchildren: components,\n\t\tassessmentItemRefs: components.flatMap((c) => (c.type === 'item' ? [c.item] : [])),\n\t\tsections: sections.length > 0 ? sections : undefined,\n\t};\n}\n\nfunction mergeAdjacentFragments(\n\tcomponents: SecureSectionComponent[],\n\tsourceOf: Map<SecureSection, SecureSection>,\n): SecureSectionComponent[] {\n\tconst out: SecureSectionComponent[] = [];\n\tfor (const component of components) {\n\t\tconst previous = out[out.length - 1];\n\t\tconst source = component.type === 'section' ? sourceOf.get(component.section) : undefined;\n\t\tif (source && previous?.type === 'section' && sourceOf.get(previous.section) === source && component.type === 'section') {\n\t\t\tconst merged = withComponents(previous.section, [\n\t\t\t\t...sectionComponents(previous.section),\n\t\t\t\t...sectionComponents(component.section),\n\t\t\t]);\n\t\t\tsourceOf.set(merged, source);\n\t\t\tout[out.length - 1] = { type: 'section', section: merged };\n\t\t} else {\n\t\t\tout.push(component);\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Fisher-Yates shuffle using a provided RNG (returns a new array). */\nexport function shuffleArray<T>(arr: readonly T[], rng: () => number): T[] {\n\tconst out = [...arr];\n\tfor (let i = out.length - 1; i > 0; i--) {\n\t\tconst j = Math.floor(rng() * (i + 1));\n\t\t[out[i], out[j]] = [out[j]!, out[i]!];\n\t}\n\treturn out;\n}\n\nfunction isRequiredSectionComponent(component: SecureSectionComponent): boolean {\n\treturn component.type === 'item' ? component.item.required === true : component.section.required === true;\n}\n\nfunction isFixedSectionComponent(component: SecureSectionComponent): boolean {\n\treturn component.type === 'item' ? component.item.fixed === true : component.section.fixed === true;\n}\n\n/** Shuffle non-fixed children while retaining fixed children at their post-selection positions. */\nfunction shuffleSectionComponents(components: SecureSectionComponent[], rng: () => number): SecureSectionComponent[] {\n\tconst result = [...components];\n\tconst movableIndexes = components.flatMap((component, index) => (isFixedSectionComponent(component) ? [] : [index]));\n\tconst shuffled = shuffleArray(movableIndexes.map((index) => components[index]!), rng);\n\tfor (let index = 0; index < movableIndexes.length; index++) {\n\t\tresult[movableIndexes[index]!] = shuffled[index]!;\n\t}\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// Test-scope expressions\n// ---------------------------------------------------------------------------\n\n/** Canonical QTI 2.x element name for a QTI 2.x or QTI 3 (`qti-` kebab-case) element name. */\nexport function toCanonicalQtiName(name: string | null | undefined): string {\n\tconst withoutPrefix = (name ?? '').replace(/^qti-/, '');\n\treturn withoutPrefix.replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Reads QTI 2.x camelCase and QTI 3 `qti-` kebab-case element names alike. */\nexport const qtiElementNameMapper = {\n\tversion: 'qti2x-or-qti3',\n\ttoCanonical: (elementName: string) => toCanonicalQtiName(elementName).toLowerCase(),\n\ttoNative: (canonicalName: string) => canonicalName,\n\tisValidElementName: () => true,\n};\n\nfunction toQtiValue(baseType: string, cardinality: string, value: unknown): QtiValue {\n\tif (value === null || value === undefined) return qtiNull(baseType as never, cardinality as never);\n\treturn qtiValue(baseType as never, cardinality as never, value);\n}\n\nfunction declaration(identifier: string, value: QtiValue, defaultValue: QtiValue = value): DeclarationMap[string] {\n\treturn {\n\t\tidentifier,\n\t\tbaseType: value.baseType,\n\t\tcardinality: value.cardinality ?? 'single',\n\t\tdefaultValue,\n\t\tvalue: { ...value },\n\t};\n}\n\n/**\n * Declarations for the test's outcome variables, set to `outcomes` where given and to their\n * defaults otherwise. A numeric outcome with no declared default starts at 0.\n */\nexport function testOutcomeDeclarations(\n\tassessment: SecureAssessment,\n\toutcomes?: TestOutcomeValues | null,\n): DeclarationMap {\n\tconst decls: DeclarationMap = {};\n\tfor (const d of assessment.outcomeDeclarations ?? []) {\n\t\tconst defaultValue =\n\t\t\td.defaultValue !== undefined\n\t\t\t\t? toQtiValue(d.baseType, d.cardinality, d.defaultValue)\n\t\t\t\t: d.baseType === 'float' || d.baseType === 'integer'\n\t\t\t\t\t? qtiValue(d.baseType, 'single', 0)\n\t\t\t\t\t: qtiNull(d.baseType as never, d.cardinality as never);\n\t\tconst current = outcomes && d.identifier in outcomes\n\t\t\t? toQtiValue(d.baseType, d.cardinality, outcomes[d.identifier] as TestOutcomeValue)\n\t\t\t: defaultValue;\n\t\tdecls[d.identifier] = {\n\t\t\tidentifier: d.identifier,\n\t\t\tbaseType: d.baseType as never,\n\t\t\tcardinality: d.cardinality as never,\n\t\t\tdefaultValue,\n\t\t\tvalue: { ...current },\n\t\t};\n\t}\n\treturn decls;\n}\n\n/**\n * Adds item variables as `itemIdentifier.VARIABLE`, the form test-scope expressions use, and the\n * `unprefixed` variables under their own identifiers where the test declares no such outcome.\n */\nexport function addItemVariableDeclarations(\n\tdecls: DeclarationMap,\n\titemVariables: Record<string, Record<string, QtiValue>>,\n\tunprefixed: Record<string, QtiValue> = {},\n): DeclarationMap {\n\tfor (const [itemIdentifier, variables] of Object.entries(itemVariables)) {\n\t\tfor (const [identifier, value] of Object.entries(variables)) {\n\t\t\tconst key = `${itemIdentifier}.${identifier}`;\n\t\t\tif (!decls[key]) decls[key] = declaration(key, value);\n\t\t}\n\t}\n\tfor (const [identifier, value] of Object.entries(unprefixed)) {\n\t\tif (!decls[identifier]) decls[identifier] = declaration(identifier, value);\n\t}\n\treturn decls;\n}\n\n/** Millisecond scope clocks the timing state carries; absent clocks read as 0 seconds. */\nexport interface ScopeTiming {\n\t/** Total assessment elapsed time (ms). */\n\ttotalTime?: number;\n\t/** Elapsed time per testPart identifier (ms). */\n\ttestPartTimes?: Record<string, number>;\n\t/** Elapsed time per section identifier (ms). */\n\tsectionTimes?: Record<string, number>;\n}\n\n/**\n * Adds the QTI built-in duration variables test-scope expressions read: `duration` for the whole\n * test, `TESTPART_ID.duration` and `SECTION_ID.duration` for each delivered part and section.\n * QTI durations are seconds; the timing state keeps milliseconds, so the values are converted.\n * Authored identifiers win: an existing declaration is never replaced.\n */\nexport function addScopeDurationDeclarations(\n\tdecls: DeclarationMap,\n\tassessment: SecureAssessment,\n\ttiming: ScopeTiming | undefined,\n): DeclarationMap {\n\tconst durationSeconds = (ms: number | undefined): number =>\n\t\tdurationSecondsFromMilliseconds(Number(ms) || 0);\n\tconst putDuration = (identifier: string, seconds: number): void => {\n\t\tif (!decls[identifier]) decls[identifier] = declaration(identifier, qtiValue('duration', 'single', seconds));\n\t};\n\tputDuration('duration', durationSeconds(timing?.totalTime));\n\tconst visitSections = (sections: readonly SecureSection[]): void => {\n\t\tfor (const section of sections) {\n\t\t\tputDuration(`${section.identifier}.duration`, durationSeconds(timing?.sectionTimes?.[section.identifier]));\n\t\t\tvisitSections(section.sections ?? []);\n\t\t}\n\t};\n\tfor (const testPart of assessment.testParts ?? []) {\n\t\tputDuration(`${testPart.identifier}.duration`, durationSeconds(timing?.testPartTimes?.[testPart.identifier]));\n\t\tvisitSections(testPart.sections ?? []);\n\t}\n\treturn decls;\n}\n\n/** Item variables with each variableMapping's source also readable as its target identifier. */\nexport function applyVariableMappings(\n\tvariables: Record<string, QtiValue>,\n\tmappings: SecureItemRef['variableMappings'],\n): Record<string, QtiValue> {\n\tif (!mappings?.length) return variables;\n\tconst out = { ...variables };\n\tfor (const { sourceIdentifier, targetIdentifier } of mappings) {\n\t\tconst value = variables[sourceIdentifier];\n\t\tif (value) out[targetIdentifier] = value;\n\t}\n\treturn out;\n}\n\n/** Evaluates a serialized test-scope expression (QTI 2.x or 3) against `decls`. */\nexport function evaluateTestExpression(expressionXml: string, decls: DeclarationMap, rng: () => number): QtiValue {\n\tconst root = parseXml(expressionXml).documentElement;\n\tif (!root) return qtiNull();\n\tconst expr = buildExpression(root, { scope: 'test', elementNameMapper: qtiElementNameMapper });\n\treturn evalExpr({ ctx: new DeclarationContext(structuredClone(decls)), rng }, expr);\n}\n\n/**\n * True only when the expression evaluates to boolean true; NULL reads as false (QTI:\n * a NULL condition result is false).\n *\n * An evaluation ERROR also reads as false, but unlike a NULL it is reported: delivery\n * proceeds on the default path (a broken branchRule or preCondition must never abort a\n * candidate's test), yet the failure is never indistinguishable from an authored false.\n * Callers that own an error surface pass `onError` — the AssessmentPlayer reports a\n * coded `testConditionFailed` through `config.onError` — and without one the failure\n * stays a console warning (the reference backend's own evaluation).\n *\n * Documented divergence from the strict spec reading: QTI 2.1/3.0 leave undefined how\n * delivery proceeds when a condition expression cannot be evaluated; reading it as\n * false keeps delivery on the default path and reporting keeps it observable.\n */\nexport function evaluateTestCondition(\n\texpressionXml: string,\n\tdecls: DeclarationMap,\n\trng: () => number,\n\tonError?: (expressionXml: string, error: unknown) => void,\n): boolean {\n\ttry {\n\t\tconst out = evaluateTestExpression(expressionXml, decls, rng);\n\t\treturn out.kind === 'value' && out.value === true;\n\t} catch (err) {\n\t\tif (onError) onError(expressionXml, err);\n\t\telse console.warn('[assessment-player] test condition failed to evaluate:', err);\n\t\treturn false;\n\t}\n}\n\n/** Plain value of a QTI value, null for NULL, in the shape item template defaults take. */\nexport function plainQtiValue(value: QtiValue): unknown {\n\treturn value.kind === 'value' ? value.value : null;\n}\n\n/** A serialized item-session variable, as `SerializedItemSessionState` carries it. */\ninterface SerializedVariableShape {\n\tbaseType?: string;\n\tcardinality: string;\n\tvalue: unknown;\n}\n\n/**\n * The QTI values of a serialized item session's response, outcome and template\n * variables (NULL where unset), keyed by variable identifier — the item's variables a\n * test-scope expression reads as `ITEM.VARIABLE`.\n */\nexport function itemSessionVariableValues(session: {\n\tresponseVariables?: Record<string, SerializedVariableShape>;\n\toutcomeVariables?: Record<string, SerializedVariableShape>;\n\ttemplateVariables?: Record<string, SerializedVariableShape>;\n}): Record<string, QtiValue> {\n\tconst out: Record<string, QtiValue> = {};\n\tfor (const group of [session.responseVariables, session.outcomeVariables, session.templateVariables]) {\n\t\tfor (const [identifier, variable] of Object.entries(group ?? {})) {\n\t\t\tout[identifier] = toQtiValue(variable.baseType as string, variable.cardinality, variable.value);\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * An item's variables as test-level branch rules and preconditions read them (`ITEM.VARIABLE`),\n * in the shape the reference backend records after a counted submission (its item test state):\n * the session's context (numAttempts, duration, completionStatus), template, outcome and response\n * variables, with `scoredOutcomes` — the backend's scored outcome values, authoritative where the\n * delivered item carries no response processing — over them, typed by the session's own\n * declarations (a value without one is read as the reference backend reads a bare score: a\n * number as float, anything else as string). Record outcomes keep the session's value.\n */\nexport function recordedItemVariableValues(\n\tsession:\n\t\t| {\n\t\t\t\tcontextVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\tresponseVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\toutcomeVariables?: Record<string, SerializedVariableShape>;\n\t\t\t\ttemplateVariables?: Record<string, SerializedVariableShape>;\n\t\t }\n\t\t| undefined,\n\tscoredOutcomes: Record<string, unknown> | undefined,\n): Record<string, QtiValue> {\n\tconst out: Record<string, QtiValue> = {};\n\tfor (const group of [\n\t\tsession?.contextVariables,\n\t\tsession?.templateVariables,\n\t\tsession?.outcomeVariables,\n\t\tsession?.responseVariables,\n\t]) {\n\t\tfor (const [identifier, variable] of Object.entries(group ?? {})) {\n\t\t\tout[identifier] = toQtiValue(variable.baseType as string, variable.cardinality, variable.value);\n\t\t}\n\t}\n\tfor (const [identifier, value] of Object.entries(scoredOutcomes ?? {})) {\n\t\tconst declared = out[identifier];\n\t\tif (value === undefined || declared?.cardinality === 'record') continue;\n\t\tif (declared?.baseType) {\n\t\t\tout[identifier] = toQtiValue(declared.baseType, declared.cardinality ?? 'single', value);\n\t\t} else if (typeof value === 'number') {\n\t\t\tout[identifier] = qtiValue('float', 'single', value);\n\t\t} else if (value !== null && typeof value !== 'object') {\n\t\t\tout[identifier] = qtiValue('string', 'single', String(value));\n\t\t}\n\t}\n\treturn out;\n}\n"]}
@@ -116,7 +116,7 @@ export class ReferenceBackendAdapter {
116
116
  // For reference implementation, we'll use demo data. Selection and ordering are drawn once
117
117
  // here; the stored draw is what a resume returns.
118
118
  const assessment = drawAssessment(this.getAssessment(request.assessmentId), this.rng);
119
- const firstItemIdentifier = firstEligibleItem(assessment, deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment), this.rng) ?? '';
119
+ const firstItemIdentifier = firstEligibleItem(deliveredItems(assessment), 0, undefined, testOutcomeDeclarations(assessment), this.rng) ?? '';
120
120
  const state = {
121
121
  currentItemIdentifier: firstItemIdentifier,
122
122
  visitedItems: [],
@@ -304,7 +304,7 @@ export class ReferenceBackendAdapter {
304
304
  ...applyVariableMappings(currentVariables, current.item.variableMappings),
305
305
  ...(currentVariables.SCORE ? {} : { SCORE: qtiValue('float', 'single', result.score) }),
306
306
  });
307
- const nextId = nextItemIdentifier(session.assessment, delivered, index, decls, this.rng);
307
+ const nextId = nextItemIdentifier(delivered, index, decls, this.rng);
308
308
  return {
309
309
  success: true,
310
310
  result,
@@ -503,11 +503,11 @@ export class ReferenceBackendAdapter {
503
503
  return {
504
504
  identifier: assessmentId,
505
505
  title: 'Demo Assessment',
506
- navigationMode: 'nonlinear',
507
- submissionMode: 'simultaneous',
508
506
  testParts: [
509
507
  {
510
508
  identifier: 'part1',
509
+ navigationMode: 'nonlinear',
510
+ submissionMode: 'simultaneous',
511
511
  rubricBlocks: [],
512
512
  itemSessionControl: {
513
513
  maxAttempts: 1,