@citolab/qti-components 10.0.0-next.27 → 10.0.0-next.28

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.
Files changed (35) hide show
  1. package/dist/{chunk-THV42AHU.js → chunk-4IWT7GLA.js} +5 -4
  2. package/dist/chunk-4IWT7GLA.js.map +1 -0
  3. package/dist/{chunk-U5HL4SF3.js → chunk-566LB3G2.js} +2 -2
  4. package/dist/{chunk-I2UB2NOX.js → chunk-ADTCTKXS.js} +2 -2
  5. package/dist/{chunk-EGN2SVIN.js → chunk-BBP7QV32.js} +2 -2
  6. package/dist/{chunk-EWX4R46G.js → chunk-CFTWXYBO.js} +2 -2
  7. package/dist/{chunk-EA7UK4NL.js → chunk-EECRJEZ3.js} +4 -4
  8. package/dist/{chunk-HZCPYU53.js → chunk-GAPMCYR5.js} +2 -2
  9. package/dist/{chunk-GYWC44CE.js → chunk-HFLK46W3.js} +2 -2
  10. package/dist/{chunk-FEWA5I3V.js → chunk-O2XRZPKA.js} +1 -1
  11. package/dist/chunk-O2XRZPKA.js.map +1 -0
  12. package/dist/corrections.d.ts +2 -2
  13. package/dist/corrections.js +5 -5
  14. package/dist/elements.js +3 -3
  15. package/dist/index.d.ts +3 -3
  16. package/dist/index.js +9 -9
  17. package/dist/item.js +3 -3
  18. package/dist/loader.js +2 -2
  19. package/dist/{qti-test-state-D-edVvB3.d.ts → qti-test-state-CzLBgPCW.d.ts} +6 -2
  20. package/dist/{qti-test-state.d-D8Q89RzZ.d.ts → qti-test-state.d-CjvdranT.d.ts} +5 -1
  21. package/dist/{qti-test.d-0fARwLm2.d.ts → qti-test.d-BPYBrsWS.d.ts} +1 -1
  22. package/dist/test-plugin-api.d.ts +2 -2
  23. package/dist/test.d.ts +5 -5
  24. package/dist/test.js +4 -4
  25. package/dist/transformers.js +1 -1
  26. package/package.json +3 -3
  27. package/dist/chunk-FEWA5I3V.js.map +0 -1
  28. package/dist/chunk-THV42AHU.js.map +0 -1
  29. /package/dist/{chunk-U5HL4SF3.js.map → chunk-566LB3G2.js.map} +0 -0
  30. /package/dist/{chunk-I2UB2NOX.js.map → chunk-ADTCTKXS.js.map} +0 -0
  31. /package/dist/{chunk-EGN2SVIN.js.map → chunk-BBP7QV32.js.map} +0 -0
  32. /package/dist/{chunk-EWX4R46G.js.map → chunk-CFTWXYBO.js.map} +0 -0
  33. /package/dist/{chunk-EA7UK4NL.js.map → chunk-EECRJEZ3.js.map} +0 -0
  34. /package/dist/{chunk-HZCPYU53.js.map → chunk-GAPMCYR5.js.map} +0 -0
  35. /package/dist/{chunk-GYWC44CE.js.map → chunk-HFLK46W3.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import { V as View } from './session.context.d-9gRdGK4T.js';
2
2
  import { a as PublicEventDeclaration } from './public-events.d-3dGip9pd.js';
3
- import { Q as QtiTestState } from './qti-test-state.d-D8Q89RzZ.js';
4
- export { a as QtiTestPluginState, b as QtiTestState, i as itemsInOrder, p as pluginState } from './qti-test-state-D-edVvB3.js';
3
+ import { Q as QtiTestState } from './qti-test-state.d-CjvdranT.js';
4
+ export { a as QtiTestPluginState, b as QtiTestState, i as itemsInOrder, p as pluginState } from './qti-test-state-CzLBgPCW.js';
5
5
  import * as lit from 'lit';
6
6
  import './variables.d-DWHlTszN.js';
7
7
  import './computed.types.d-DcAfzw8v.js';
package/dist/test.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { u as TestSubmit, v as ItemVariableValue, I as ITestNavigationMixin, a as ITestStateMixin } from './qti-test.d-0fARwLm2.js';
2
- export { b as ItemRefTemplateModel, Q as QtiAssessmentItemRef, c as QtiAssessmentSection, d as QtiAssessmentTest, e as QtiBranchRule, f as QtiItemSessionControl, g as QtiNumberPresented, h as QtiNumberSelected, i as QtiOutcomeProcessing, j as QtiOutcomeProcessingProcessor, k as QtiPreCondition, l as QtiTest, m as QtiTestFeedback, n as QtiTestPart, o as QtiTestVariables, p as QtiTestVariablesExpression, T as TestContainer, q as TestEndAttempt, r as TestNavigation, s as TestNext, t as TestPrev } from './qti-test.d-0fARwLm2.js';
3
- import { b as QtiTestState } from './qti-test-state-D-edVvB3.js';
4
- export { Q as QTI_TEST_STATE_VERSION, a as QtiTestPluginState, c as QtiTestStateItem, d as QtiTestStateSession, e as QtiTestStateValue, i as itemsInOrder, p as pluginState } from './qti-test-state-D-edVvB3.js';
1
+ import { u as TestSubmit, v as ItemVariableValue, I as ITestNavigationMixin, a as ITestStateMixin } from './qti-test.d-BPYBrsWS.js';
2
+ export { b as ItemRefTemplateModel, Q as QtiAssessmentItemRef, c as QtiAssessmentSection, d as QtiAssessmentTest, e as QtiBranchRule, f as QtiItemSessionControl, g as QtiNumberPresented, h as QtiNumberSelected, i as QtiOutcomeProcessing, j as QtiOutcomeProcessingProcessor, k as QtiPreCondition, l as QtiTest, m as QtiTestFeedback, n as QtiTestPart, o as QtiTestVariables, p as QtiTestVariablesExpression, T as TestContainer, q as TestEndAttempt, r as TestNavigation, s as TestNext, t as TestPrev } from './qti-test.d-BPYBrsWS.js';
3
+ import { b as QtiTestState } from './qti-test-state-CzLBgPCW.js';
4
+ export { Q as QTI_TEST_STATE_VERSION, a as QtiTestPluginState, c as QtiTestStateItem, d as QtiTestStateSession, e as QtiTestStateValue, i as itemsInOrder, p as pluginState } from './qti-test-state-CzLBgPCW.js';
5
5
  import { LitElement } from 'lit';
6
6
  import { b as OutcomeVariable, V as VariableDeclaration } from './variables.d-DWHlTszN.js';
7
7
  import { S as SessionContext } from './session.context.d-9gRdGK4T.js';
@@ -17,7 +17,7 @@ import './qti-feedback.d-CT0W-8Gm.js';
17
17
  import './qti-rule-base.d-CeKP0Ooi.js';
18
18
  import './qti.context.d-CejJMlfZ.js';
19
19
  import '@heximal/templates';
20
- import './qti-test-state.d-D8Q89RzZ.js';
20
+ import './qti-test-state.d-CjvdranT.js';
21
21
 
22
22
  /**
23
23
  * The plugins' `{ tag, ctor }` pairs, so a scoped registry (an item-ref template is stamped into
package/dist/test.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./chunk-GYWC44CE.js";
1
+ import "./chunk-HFLK46W3.js";
2
2
  import {
3
3
  pluginState
4
4
  } from "./chunk-DJ7PB252.js";
@@ -27,15 +27,15 @@ import {
27
27
  TestSubmit,
28
28
  pluginElements,
29
29
  stateFromContexts
30
- } from "./chunk-THV42AHU.js";
30
+ } from "./chunk-4IWT7GLA.js";
31
31
  import {
32
32
  itemsInOrder
33
33
  } from "./chunk-7ISPUOJG.js";
34
- import "./chunk-HZCPYU53.js";
34
+ import "./chunk-GAPMCYR5.js";
35
35
  import "./chunk-UCXLDQYA.js";
36
36
  import "./chunk-WWY2H2YO.js";
37
37
  import "./chunk-4DB4SC5K.js";
38
- import "./chunk-FEWA5I3V.js";
38
+ import "./chunk-O2XRZPKA.js";
39
39
  import "./chunk-GPC53O7P.js";
40
40
  import "./chunk-PZ5AY32C.js";
41
41
  export {
@@ -2,7 +2,7 @@ import {
2
2
  qtiTransformItem,
3
3
  qtiTransformManifest,
4
4
  qtiTransformTest
5
- } from "./chunk-FEWA5I3V.js";
5
+ } from "./chunk-O2XRZPKA.js";
6
6
  import "./chunk-PZ5AY32C.js";
7
7
  export {
8
8
  qtiTransformItem,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@citolab/qti-components",
3
3
  "description": "QTI component utilities",
4
- "version": "10.0.0-next.27",
4
+ "version": "10.0.0-next.28",
5
5
  "author": "",
6
6
  "dependencies": {
7
7
  "@heximal/templates": "^0.1.5",
@@ -12,13 +12,13 @@
12
12
  "devDependencies": {
13
13
  "@qti-components/base": "^3.0.0-next.10",
14
14
  "@qti-components/corrections": "^1.0.0-next.11",
15
- "@qti-components/delivery": "^0.1.0-next.3",
15
+ "@qti-components/delivery": "^0.1.0-next.4",
16
16
  "@qti-components/elements": "^2.0.0-next.7",
17
17
  "@qti-components/interactions": "^1.10.5-next.8",
18
18
  "@qti-components/item": "^1.5.1-next.7",
19
19
  "@qti-components/loader": "^1.3.4-next.2",
20
20
  "@qti-components/processing": "^1.6.1-next.5",
21
- "@qti-components/test": "^2.0.0-next.22",
21
+ "@qti-components/test": "^2.0.0-next.23",
22
22
  "@qti-components/theme": "^3.0.0-next.6",
23
23
  "@qti-components/transformers": "^1.8.0-next.4"
24
24
  },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../qti-transformers/src/item/cdata.ts","../../qti-transformers/src/item/configure-pci.ts","../../qti-transformers/src/item/extend.ts","../../qti-transformers/src/item/pci-hooks.ts","../../qti-delivery/src/random/seeded-random.ts","../../qti-delivery/src/random/selection.ts","../../qti-delivery/src/random/shuffle.ts","../../qti-delivery/src/state/delivery-state.ts","../../qti-transformers/src/item/shuffle-interactions.ts","../../qti-transformers/src/item/stylesheets.ts","../../qti-transformers/src/item/validate-bindings.ts","../../qti-transformers/src/shared/missing-seed-warning.ts","../../qti-transformers/src/shared/xml.ts","../../qti-transformers/src/qti-transform-item.ts","../../qti-transformers/src/qti-transform-manifest.ts","../../qti-transformers/src/test/items.ts","../../qti-transformers/src/test/section-refs.ts","../../qti-transformers/src/test/section-elements.ts","../../qti-transformers/src/test/select-sections.ts","../../qti-transformers/src/test/shuffle-sections.ts","../../qti-transformers/src/qti-transform-test.ts"],"sourcesContent":["export function convertCDATAtoComment(xmlFragment: DocumentFragment) {\n const cdataElements = xmlFragment.querySelectorAll('qti-custom-operator[class=\"js.org\"] > qti-base-value');\n cdataElements.forEach(element => {\n const commentText = document.createComment(element.textContent);\n element.replaceChild(commentText, element.firstChild);\n });\n}\n","// Type definition for module resolution config\nexport interface ModuleResolutionConfig {\n waitSeconds?: number;\n context?: string;\n catchError?: boolean;\n urlArgs?: string;\n paths: {\n [key: string]: string | string[];\n };\n shim?: {\n [key: string]: {\n deps?: string[]; // Array of dependencies\n exports?: string; // The global variable to use as the module's value\n };\n };\n}\n\nexport async function configurePci(\n xmlFragment: XMLDocument,\n baseUrl: string,\n getModuleResolutionConfig: (baseUrl: string, fileUrl: string) => Promise<ModuleResolutionConfig>,\n selector = 'qti-portable-custom-interaction'\n): Promise<void> {\n const customInteractionTypeIdentifiers: string[] = [];\n const portableCustomInteractions = xmlFragment.querySelectorAll(selector);\n\n // Avoid fetching module resolution configs for items that do not contain any PCIs.\n // This prevents unnecessary network requests when configurePci() is called for every item.\n if (portableCustomInteractions.length === 0) {\n return;\n }\n\n // Lazily load (and cache) the default module resolution configs.\n let moduleResolutionConfig: ModuleResolutionConfig | null = null;\n let moduleResolutionFallbackConfig: ModuleResolutionConfig | null = null;\n const ensureDefaultModuleResolutionConfigs = async () => {\n if (moduleResolutionConfig === null) {\n try {\n moduleResolutionConfig = await getModuleResolutionConfig(baseUrl, '/modules/module_resolution.js');\n } catch {\n moduleResolutionConfig = null;\n }\n }\n if (moduleResolutionFallbackConfig === null) {\n try {\n moduleResolutionFallbackConfig = await getModuleResolutionConfig(\n baseUrl,\n '/modules/fallback_module_resolution.js'\n );\n } catch {\n moduleResolutionFallbackConfig = null;\n }\n }\n };\n\n for (const interaction of Array.from(portableCustomInteractions)) {\n // set data-base-url\n interaction.setAttribute('data-base-url', baseUrl);\n\n let customInteractionTypeIdentifier = interaction.getAttribute('custom-interaction-type-identifier');\n if (customInteractionTypeIdentifier && customInteractionTypeIdentifiers.includes(customInteractionTypeIdentifier)) {\n customInteractionTypeIdentifier = customInteractionTypeIdentifier + customInteractionTypeIdentifiers.length;\n interaction.setAttribute('custom-interaction-type-identifier', customInteractionTypeIdentifier);\n customInteractionTypeIdentifiers.push(customInteractionTypeIdentifier);\n }\n if (customInteractionTypeIdentifier) {\n customInteractionTypeIdentifiers.push(customInteractionTypeIdentifier);\n }\n\n // Check if qti-interaction-modules already exists\n let modulesElement = interaction.querySelector('qti-interaction-modules');\n\n // If it exists and has primary-configuration, handle that format\n if (modulesElement && modulesElement.getAttribute('primary-configuration')) {\n await ensureDefaultModuleResolutionConfigs();\n const primaryConfigPath = modulesElement.getAttribute('primary-configuration');\n if (primaryConfigPath) {\n try {\n // Load the primary configuration\n const primaryConfig = await getModuleResolutionConfig(baseUrl, `/${primaryConfigPath}`);\n\n // Get existing module elements that only have id attributes\n const existingModules = Array.from(modulesElement.querySelectorAll('qti-interaction-module'));\n\n // Update existing modules with paths from config\n for (const moduleEl of existingModules) {\n const moduleId = moduleEl.getAttribute('id');\n if (moduleId && primaryConfig.paths && primaryConfig.paths[moduleId]) {\n const primaryPath = primaryConfig.paths[moduleId];\n const primaryPathString = Array.isArray(primaryPath) ? primaryPath[0] : primaryPath;\n moduleEl.setAttribute('primary-path', primaryPathString);\n\n // Check for fallback path\n if (\n moduleResolutionFallbackConfig &&\n moduleResolutionFallbackConfig.paths &&\n moduleResolutionFallbackConfig.paths[moduleId]\n ) {\n const fallbackPath = moduleResolutionFallbackConfig.paths[moduleId];\n if (Array.isArray(fallbackPath)) {\n moduleEl.setAttribute('fallback-path', fallbackPath[0]);\n } else {\n moduleEl.setAttribute('fallback-path', fallbackPath);\n }\n }\n }\n }\n\n // Add any additional modules from primary config that aren't already present\n if (primaryConfig.paths) {\n for (const moduleId in primaryConfig.paths) {\n const existingModule = modulesElement.querySelector(`qti-interaction-module[id=\"${moduleId}\"]`);\n if (!existingModule) {\n const newModuleElement = xmlFragment.createElement('qti-interaction-module');\n newModuleElement.setAttribute('id', moduleId);\n const primaryPathString = Array.isArray(primaryConfig.paths[moduleId])\n ? primaryConfig.paths[moduleId][0]\n : primaryConfig.paths[moduleId];\n newModuleElement.setAttribute('primary-path', primaryPathString);\n\n // Check for fallback path\n if (\n moduleResolutionFallbackConfig &&\n moduleResolutionFallbackConfig.paths &&\n moduleResolutionFallbackConfig.paths[moduleId]\n ) {\n const fallbackPath = moduleResolutionFallbackConfig.paths[moduleId];\n if (Array.isArray(fallbackPath)) {\n newModuleElement.setAttribute('fallback-path', fallbackPath[0]);\n } else {\n newModuleElement.setAttribute('fallback-path', fallbackPath);\n }\n }\n\n modulesElement.appendChild(newModuleElement);\n }\n }\n }\n\n // Apply urlArgs if present in config\n if (primaryConfig.urlArgs) {\n modulesElement.setAttribute('url-args', primaryConfig.urlArgs);\n }\n } catch (error) {\n console.warn(`Failed to load primary configuration: ${primaryConfigPath}`, error);\n }\n }\n } else {\n // Original logic for when there's no existing qti-interaction-modules or no primary-configuration\n await ensureDefaultModuleResolutionConfigs();\n if (moduleResolutionConfig) {\n // Create qti-interaction-modules if it doesn't exist\n if (interaction.querySelector('qti-interaction-modules') === null) {\n modulesElement = xmlFragment.createElement('qti-interaction-modules');\n interaction.appendChild(modulesElement);\n } else {\n modulesElement = interaction.querySelector('qti-interaction-modules');\n }\n\n for (const module in moduleResolutionConfig.paths) {\n const path = moduleResolutionConfig.paths[module];\n let fallbackPath: string | string[] = '';\n\n if (\n moduleResolutionFallbackConfig &&\n moduleResolutionFallbackConfig.paths &&\n moduleResolutionFallbackConfig.paths[module]\n ) {\n fallbackPath = moduleResolutionFallbackConfig.paths[module];\n }\n\n const primaryArray = Array.isArray(path) ? path : [path];\n const fallbackPathArray = Array.isArray(fallbackPath) ? fallbackPath : [fallbackPath];\n\n // create an array with primary and fallback paths.\n const paths = primaryArray.map((primaryPath, i) => {\n const fallbackPath = fallbackPathArray.length > i ? fallbackPathArray[i] : '';\n return {\n primaryPath,\n fallbackPath\n };\n });\n\n // check if all fallbackPath elements are in the array: paths, otherwise add\n for (const fallbackPath of fallbackPathArray) {\n if (!paths.some(p => p.fallbackPath === fallbackPath)) {\n paths.push({\n primaryPath: primaryArray.length > 0 ? primaryArray[0] : fallbackPath,\n fallbackPath\n });\n }\n }\n\n // add the paths to the qti-interaction-modules\n for (const path of paths) {\n const moduleElement = xmlFragment.createElement('qti-interaction-module');\n if (path.fallbackPath) {\n moduleElement.setAttribute('fallback-path', path.fallbackPath);\n }\n moduleElement.setAttribute('id', module);\n moduleElement.setAttribute('primary-path', path.primaryPath);\n\n if (modulesElement) {\n modulesElement.appendChild(moduleElement);\n }\n }\n }\n }\n }\n }\n}\n","// Function to extend elements with a specific tag name by adding an extension suffix\n// Uses localName matching to handle namespaced XML documents where querySelectorAll may not work\nexport function extendElementName(xmlFragment: XMLDocument, tagName: string, extension: string) {\n // Use getElementsByTagName with '*' to find all elements, then filter by localName\n // This works correctly for both namespaced and non-namespaced XML documents\n const allElements = Array.from(xmlFragment.getElementsByTagName('*'));\n const matchingElements = allElements.filter(\n element => element.localName === tagName || element.localName?.toLowerCase() === tagName.toLowerCase()\n );\n\n matchingElements.forEach(element => {\n const newTagName = `${tagName}-${extension}`;\n const newElement = createElementWithNewTagName(element, newTagName);\n element.replaceWith(newElement);\n });\n}\n\n// Function to extend any element with a specific class pattern (e.g., \"extend:suffix\")\nexport function extendElementsWithClass(xmlFragment: XMLDocument, classNamePattern: string) {\n xmlFragment.querySelectorAll('*').forEach(element => {\n const classList = element.classList;\n if (classList) {\n classList.forEach(className => {\n if (className.startsWith(`${classNamePattern}:`)) {\n const suffix = className.slice(`${classNamePattern}:`.length);\n const newTagName = `${element.nodeName}-${suffix}`;\n const newElement = createElementWithNewTagName(element, newTagName);\n element.replaceWith(newElement);\n }\n });\n }\n });\n}\n\n// Helper function to create a new element with a new tag name and copy attributes and children\nfunction createElementWithNewTagName(element: Element, newTagName: string) {\n // create Elements on the ownerDocument which is usually the XMLDocument\n const newElement = element.ownerDocument.createElement(newTagName);\n // Copy attributes\n for (const attr of element.attributes) {\n newElement.setAttribute(attr.name, attr.value);\n }\n // Copy child nodes\n while (element.firstChild) {\n newElement.appendChild(element.firstChild);\n }\n return newElement;\n}\n","export function pciHooks(xmlFragment: XMLDocument, uri: string): void {\n const attributes = ['hook', 'module'];\n const documentPath = uri.substring(0, uri.lastIndexOf('/'));\n for (const attribute of attributes) {\n const srcAttributes = xmlFragment.querySelectorAll('[' + attribute + ']');\n srcAttributes.forEach(node => {\n const srcValue = node.getAttribute(attribute)!;\n if (!srcValue.startsWith('data:') && !srcValue.startsWith('http')) {\n // Just paste the relative path of the src location after the documentrootPath\n // old pcis can have a .js, new pci's don't\n node.setAttribute('base-url', uri);\n node.setAttribute('module', documentPath + '/' + encodeURI(srcValue + (srcValue.endsWith('.js') ? '' : '.js')));\n }\n });\n }\n}\n","export interface SeededRandomSource {\n random(): number;\n}\n\n/**\n * Small, dependency-free seeded PRNG used for deterministic QTI shuffling\n * (sections and interactions). It intentionally exposes a `random()` method,\n * matching the TC39 seeded-random proposal shape so this can be swapped when a\n * standard implementation is available.\n *\n * xmur3-style seed hashing feeds mulberry32 (fast 32-bit generator).\n */\nexport class SeededRandom implements SeededRandomSource {\n #state: number;\n\n constructor(seed: Uint8Array) {\n if (!(seed instanceof Uint8Array)) {\n throw new TypeError('SeededRandom seed must be a Uint8Array.');\n }\n if (seed.length > 32) {\n throw new RangeError('SeededRandom seed must be 32 bytes or less.');\n }\n\n const paddedSeed = new Uint8Array(32);\n paddedSeed.set(seed, 32 - seed.length);\n this.#state = hashBytes(paddedSeed);\n }\n\n static fromSeed(seed: Uint8Array): SeededRandom {\n if (seed.length !== 32) {\n throw new RangeError('SeededRandom.fromSeed requires a 32-byte seed.');\n }\n return new SeededRandom(seed);\n }\n\n static fromFixed(byte: number): SeededRandom {\n if (typeof byte !== 'number') {\n throw new TypeError('SeededRandom.fromFixed requires a number.');\n }\n if (!Number.isInteger(byte) || byte < 0 || byte > 255) {\n throw new RangeError('SeededRandom.fromFixed requires an integer from 0 to 255.');\n }\n\n const seed = new Uint8Array(32);\n seed[31] = byte;\n return new SeededRandom(seed);\n }\n\n static fromSeedKey(seedKey: string | number): SeededRandom {\n const random = new SeededRandom(new Uint8Array());\n random.#state = hashString(`${seedKey}`);\n return random;\n }\n\n random(): number {\n this.#state |= 0;\n this.#state = (this.#state + 0x6d2b79f5) | 0;\n let t = Math.imul(this.#state ^ (this.#state >>> 15), 1 | this.#state);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n }\n}\n\nexport function createSeededRandom(seedKey: string | number): SeededRandomSource {\n return SeededRandom.fromSeedKey(seedKey);\n}\n\nfunction hashString(seedKey: string): number {\n let h = 1779033703 ^ seedKey.length;\n for (let i = 0; i < seedKey.length; i++) {\n h = Math.imul(h ^ seedKey.charCodeAt(i), 3432918353);\n h = (h << 13) | (h >>> 19);\n }\n return finalizeHash(h);\n}\n\nfunction hashBytes(seed: Uint8Array): number {\n let h = 1779033703 ^ seed.length;\n for (let i = 0; i < seed.length; i++) {\n h = Math.imul(h ^ seed[i], 3432918353);\n h = (h << 13) | (h >>> 19);\n }\n return finalizeHash(h);\n}\n\nfunction finalizeHash(hash: number): number {\n let h = Math.imul(hash ^ (hash >>> 16), 2246822507);\n h = Math.imul(h ^ (h >>> 13), 3266489909);\n return (h ^ (h >>> 16)) >>> 0;\n}\n","import type { RandomSource } from './shuffle.js';\n\n/** A child of a section that selection can pick: an item-ref or a subsection, which counts as one. */\nexport interface SelectionUnit {\n /** `required=\"true\"`: always in the selection. */\n required: boolean;\n}\n\n/** A section's `qti-selection` (QTI 3 info model §5.129). */\nexport interface SelectionRule {\n /** How many units to select. */\n select: number;\n /** Whether a unit may be selected more than once (its clones). Defaults to false. */\n withReplacement?: boolean;\n}\n\nconst randomValue = (source: RandomSource): number => (typeof source === 'function' ? source() : source.random());\n\n/**\n * Which units of a section a `qti-selection` selects, as indices into `units` in authored order; a\n * unit selected more than once (`with-replacement`) has its index repeated, the clones right after\n * it. Ordering is a later, separate step (implementation guide §4.5.1: selection \"should preserve\n * the original order\").\n *\n * Implementation guide §4.5.1, and exactly this use of `random`, so every runtime (a .NET port too)\n * selects the same units for the same seed:\n *\n * 1. Every required unit is in.\n * 2. The rest of the first `min(select, units.length)` come from the non-required units, each with\n * an equal chance: a partial Fisher-Yates over the non-required indices in authored order, for\n * `i` from 0 while fewer are picked than needed, swapping position `i` with\n * `i + floor(random() * (remaining - i))`. No draw when all of them, or none, are needed.\n * 3. With replacement and `select` above `units.length`, each unit is then in once, and each further\n * clone is `floor(random() * units.length)`: every unit an equal chance, required or not, however\n * often it was cloned before.\n *\n * Throws a `RangeError` for what QTI calls an error: a `select` that is not a whole number of zero or\n * more, below the number of required units, or above the number of units without replacement (or\n * above zero with no units at all).\n */\nexport function selectUnits(units: readonly SelectionUnit[], rule: SelectionRule, random: RandomSource): number[] {\n const { select, withReplacement = false } = rule;\n if (!Number.isInteger(select) || select < 0) {\n throw new RangeError(`qti-selection select=\"${select}\" is not a whole number of zero or more.`);\n }\n const required = units.flatMap((unit, index) => (unit.required ? [index] : []));\n if (select < required.length) {\n throw new RangeError(\n `qti-selection select=\"${select}\" is less than the ${required.length} required items and subsections.`\n );\n }\n if (select > units.length && (!withReplacement || units.length === 0)) {\n throw new RangeError(\n `qti-selection select=\"${select}\" is more than the ${units.length} items and subsections, without with-replacement=\"true\".`\n );\n }\n\n const optional = units.flatMap((unit, index) => (unit.required ? [] : [index]));\n const needed = Math.min(select, units.length) - required.length;\n if (needed < optional.length) {\n for (let i = 0; i < needed; i++) {\n const j = i + Math.floor(randomValue(random) * (optional.length - i));\n [optional[i], optional[j]] = [optional[j], optional[i]];\n }\n }\n const occurrences = new Array<number>(units.length).fill(0);\n for (const index of [...required, ...optional.slice(0, needed)]) occurrences[index] = 1;\n\n for (let clone = units.length; clone < select; clone++) {\n occurrences[Math.floor(randomValue(random) * units.length)]++;\n }\n\n return occurrences.flatMap((count, index) => new Array<number>(count).fill(index));\n}\n","import type { SeededRandomSource } from './seeded-random.js';\n\nexport type RandomSource = SeededRandomSource | (() => number);\n\nconst randomValue = (source: RandomSource): number => (typeof source === 'function' ? source() : source.random());\n\n/**\n * Fisher-Yates over non-fixed units only. Fixed units keep their authored slot\n * index while movable units are shuffled into the remaining slots.\n */\nexport function shuffleKeepingFixed<T extends { fixed: boolean }>(units: T[], random: RandomSource): T[] {\n const movable = units.filter(unit => !unit.fixed);\n\n for (let i = movable.length - 1; i > 0; i--) {\n const j = Math.floor(randomValue(random) * (i + 1));\n [movable[i], movable[j]] = [movable[j], movable[i]];\n }\n\n let movableIndex = 0;\n return units.map(unit => (unit.fixed ? unit : movable[movableIndex++]));\n}\n","/**\n * The one source of truth for one candidate in one test: what a resumed test, or a server taking\n * over, needs to carry on. Written only through commands; every context is an input or a view\n * derived from it, and anything derivable (done, can*, scores) is never stored here. Plain JSON,\n * versioned, so a stored state can be read back by a later release (or a .NET port) and refused\n * when it cannot.\n *\n * Experimental (0.x): roadmap 1 fills in the target fields, phase by phase; see\n * `plans/delivery-state.md`.\n */\nexport const DELIVERY_STATE_VERSION = 1;\n\n/**\n * One item session. With `with-replacement` selection a single item-ref appears more than once,\n * so a session is keyed by its instance, never by the item-ref identifier alone.\n */\nexport type ItemInstanceId = string;\n\nexport interface ItemDeliveryState {\n /** The `identifier` of the `qti-assessment-item-ref` this instance was selected from. */\n itemRefIdentifier: string;\n /** 1 for the first time the item-ref was selected, 2 for its first clone, and so on. */\n occurrence: number;\n}\n\nexport interface DeliveryState {\n version: typeof DELIVERY_STATE_VERSION;\n /**\n * The seed actually used for selection and ordering; the same seed gives the same test on every\n * runtime. On a first start it comes from the host (`qtiContext.seed`); on resume this one wins.\n */\n seed: string | null;\n /** When the test started, in milliseconds since the epoch, read from the injected clock. */\n startedAt: number;\n /** The item instance on screen, or null before the first navigation and after the end. */\n current: ItemInstanceId | null;\n /**\n * Every item instance of the test after selection and ordering, in the order the candidate meets\n * them; written once, when the test starts. Each one is a key of `items`.\n */\n order: ItemInstanceId[];\n /**\n * What test plugins keep, by plugin name: JSON, stored and restored without being read (a\n * plugin reads its own entry).\n */\n plugins: Record<string, unknown>;\n /** One entry per instance in `order`. */\n items: Record<ItemInstanceId, ItemDeliveryState>;\n}\n\n/** The instance id of the `occurrence`th selection of an item-ref: `item-3`, `item-3#2`. */\nexport const itemInstanceId = (itemRefIdentifier: string, occurrence = 1): ItemInstanceId =>\n occurrence === 1 ? itemRefIdentifier : `${itemRefIdentifier}#${occurrence}`;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * Read a stored state back. Throws on a state this release cannot read rather than guessing, so a\n * host never resumes from something half understood: a `RangeError` for another version, a\n * `TypeError` for anything that is not a version 1 state (a missing or mistyped field, an `order`\n * or `current` that names an instance `items` does not have).\n */\nexport function parseDeliveryState(value: unknown): DeliveryState {\n if (!isRecord(value)) {\n throw new TypeError('A delivery state is an object.');\n }\n const { version } = value;\n if (version !== DELIVERY_STATE_VERSION) {\n throw new RangeError(\n `Delivery state version ${String(version)} is not supported; expected ${DELIVERY_STATE_VERSION}.`\n );\n }\n const { seed, startedAt, current, order, plugins, items } = value;\n const fail = (field: string, expected: string): never => {\n throw new TypeError(`A delivery state's ${field} must be ${expected}.`);\n };\n if (seed !== null && typeof seed !== 'string') fail('seed', 'a string or null');\n if (typeof startedAt !== 'number' || !Number.isFinite(startedAt)) fail('startedAt', 'a number');\n if (!isRecord(items)) fail('items', 'an object');\n for (const [id, item] of Object.entries(items as Record<string, unknown>)) {\n if (!isRecord(item) || typeof item.itemRefIdentifier !== 'string' || !Number.isInteger(item.occurrence)) {\n fail(`items[\"${id}\"]`, 'an object with an itemRefIdentifier and an integer occurrence');\n }\n }\n const known = (id: unknown) => typeof id === 'string' && Object.hasOwn(items as object, id);\n if (!Array.isArray(order) || !order.every(known)) fail('order', 'an array of instance ids in items');\n if (current !== null && !known(current)) fail('current', 'null or an instance id in items');\n if (!isRecord(plugins)) fail('plugins', 'an object');\n return value as unknown as DeliveryState;\n}\n","import { createSeededRandom, shuffleKeepingFixed } from '@qti-components/delivery';\n\nfunction getShuffleQuerySelectorByTagName(tagName: string): string | string[] | null {\n switch (tagName) {\n case 'qti-choice-interaction':\n case 'qti-order-interaction':\n return 'qti-simple-choice';\n case 'qti-inline-choice-interaction':\n return 'qti-inline-choice';\n case 'qti-match-interaction':\n return [\n 'qti-simple-match-set:first-of-type qti-simple-associable-choice',\n 'qti-simple-match-set:last-of-type > qti-simple-associable-choice'\n ];\n case 'qti-gap-match-interaction':\n return 'qti-gap-text';\n case 'qti-associate-interaction':\n return 'qti-simple-associable-choice';\n default:\n return null;\n }\n}\n\n/**\n * Shuffles the choices inside every interaction marked `shuffle=\"true\"`. When\n * `seed` is supplied, shuffling is deterministic and reproducible across\n * reloads; each interaction/group draws its own stream so they are independent\n * and stable even if siblings change. When `seed` is null/undefined, falls back\n * to Math.random.\n */\nexport function shuffleInteractions(xmlFragment: XMLDocument, seed?: string | number | null): void {\n const shuffleElements = xmlFragment.querySelectorAll(`[shuffle=\"true\"]`);\n const shuffleInteractions = Array.from(shuffleElements).filter(e =>\n e.tagName?.toLowerCase().endsWith('-interaction')\n );\n\n const seeded = seed != null && `${seed}`.length > 0;\n const itemId = xmlFragment.querySelector?.('qti-assessment-item')?.getAttribute('identifier') ?? '';\n\n let interactionIndex = 0;\n for (const shuffleInteraction of shuffleInteractions) {\n const responseId = shuffleInteraction.getAttribute('response-identifier') ?? `${interactionIndex}`;\n interactionIndex++;\n const query = getShuffleQuerySelectorByTagName(shuffleInteraction.tagName.toLowerCase());\n const queries = Array.isArray(query) ? query : [query];\n let shuffledAny = false;\n\n let queryIndex = 0;\n for (const q of queries) {\n if (!q) continue;\n const random = seeded ? createSeededRandom(`${seed}:${itemId}:${responseId}:${queryIndex}`) : Math.random;\n queryIndex++;\n const choices = (Array.from(shuffleInteraction.querySelectorAll(q)) as HTMLElement[]).filter(\n choice => choice.parentElement !== null\n );\n\n if (choices.filter(choice => choice.getAttribute('fixed') !== 'true').length <= 1) {\n console.warn('Shuffling is not possible with fewer than 2 non-fixed elements.');\n continue;\n }\n\n const parent = choices[0].parentElement;\n if (!parent || choices.some(choice => choice.parentElement !== parent)) {\n console.warn('Shuffling is not possible when choices do not share the same parent element.');\n continue;\n }\n\n const anchor = choices[choices.length - 1].nextSibling;\n const orderedChoices = shuffleKeepingFixed(\n choices.map(choice => ({\n element: choice,\n fixed: choice.getAttribute('fixed') === 'true'\n })),\n random\n );\n\n for (const choice of choices) {\n choice.remove();\n }\n for (const { element } of orderedChoices) {\n parent.insertBefore(element, anchor);\n }\n\n shuffledAny = true;\n }\n\n if (shuffledAny) {\n shuffleInteraction.removeAttribute('shuffle');\n }\n }\n}\n","export function stripStyleSheets(xmlFragment: DocumentFragment) {\n // remove qti-stylesheet tag\n xmlFragment.querySelectorAll('qti-stylesheet').forEach(stylesheet => stylesheet.remove());\n}\n","/**\n * What response variable each interaction must be bound to, as the QTI 3 information model states it\n * in the interaction's description (section in each comment). `max` is the attribute that, when it is\n * greater than 1 or 0, requires multiple cardinality, with its default. A record declaration has no\n * base-type of its own, so the base-type is only checked for the other cardinalities.\n *\n * Custom and portable custom interactions state no binding rule, so they are not listed.\n */\nconst BINDING_RULES: Record<\n string,\n { baseTypes: string[]; cardinalities: string[]; max?: { attribute: string; default: number } }\n> = {\n // §5.8\n 'qti-associate-interaction': {\n baseTypes: ['pair'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-associations', default: 1 }\n },\n // §5.30\n 'qti-choice-interaction': {\n baseTypes: ['identifier'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-choices', default: 1 }\n },\n // §5.44\n 'qti-drawing-interaction': { baseTypes: ['file'], cardinalities: ['single'] },\n // §5.45\n 'qti-end-attempt-interaction': { baseTypes: ['boolean'], cardinalities: ['single'] },\n // §5.48\n 'qti-extended-text-interaction': {\n baseTypes: ['string', 'integer', 'float'],\n cardinalities: ['single', 'multiple', 'ordered', 'record']\n },\n // §5.57\n 'qti-gap-match-interaction': {\n baseTypes: ['directedPair'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-associations', default: 1 }\n },\n // §5.59\n 'qti-graphic-associate-interaction': {\n baseTypes: ['pair'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-associations', default: 1 }\n },\n // §5.60\n 'qti-graphic-gap-match-interaction': { baseTypes: ['directedPair'], cardinalities: ['multiple'] },\n // §5.61\n 'qti-graphic-order-interaction': { baseTypes: ['identifier'], cardinalities: ['ordered'] },\n // §5.68\n 'qti-hotspot-interaction': {\n baseTypes: ['identifier'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-choices', default: 1 }\n },\n // §5.66\n 'qti-hottext-interaction': {\n baseTypes: ['identifier'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-choices', default: 1 }\n },\n // §5.74\n 'qti-inline-choice-interaction': { baseTypes: ['identifier'], cardinalities: ['single'] },\n // §5.89\n 'qti-match-interaction': {\n baseTypes: ['directedPair'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-associations', default: 1 }\n },\n // §5.92\n 'qti-media-interaction': { baseTypes: ['integer'], cardinalities: ['single'] },\n // §2.4.1.2; its own §5.97 states no rule\n 'qti-order-interaction': { baseTypes: ['identifier'], cardinalities: ['ordered'] },\n // §5.107\n 'qti-position-object-interaction': {\n baseTypes: ['point'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-choices', default: 1 }\n },\n // §5.128\n 'qti-select-point-interaction': {\n baseTypes: ['point'],\n cardinalities: ['single', 'multiple'],\n max: { attribute: 'max-choices', default: 0 }\n },\n // §5.134\n 'qti-slider-interaction': { baseTypes: ['integer', 'float'], cardinalities: ['single'] },\n // §5.162\n 'qti-text-entry-interaction': { baseTypes: ['string', 'integer', 'float'], cardinalities: ['single', 'record'] },\n // §5.165\n 'qti-upload-interaction': { baseTypes: ['file'], cardinalities: ['single'] }\n};\n\nconst either = (values: string[]) =>\n values.length === 1 ? values[0] : `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;\n\n/**\n * Rejects an item that binds an interaction to a response it cannot hold.\n *\n * The document can be well-formed and schema-valid and still break this: no XSD ties an interaction's\n * `response-identifier` to the declaration it names. Every violation is listed in one error. An\n * interaction whose response is not declared is left alone; nothing here says what it should be.\n */\nexport function validateBindings(xmlFragment: XMLDocument): void {\n const declarations = new Map(\n Array.from(xmlFragment.querySelectorAll('qti-response-declaration'), d => [d.getAttribute('identifier'), d])\n );\n const violations: string[] = [];\n\n for (const [tagName, rule] of Object.entries(BINDING_RULES)) {\n for (const interaction of Array.from(xmlFragment.querySelectorAll(tagName))) {\n const responseIdentifier = interaction.getAttribute('response-identifier');\n const declaration = declarations.get(responseIdentifier);\n if (!declaration) continue;\n\n const where = `${tagName} (response \"${responseIdentifier}\")`;\n const cardinality = declaration.getAttribute('cardinality');\n const baseType = declaration.getAttribute('base-type');\n\n if (cardinality && !rule.cardinalities.includes(cardinality)) {\n violations.push(\n `${where}: ${cardinality} cardinality is not permitted; it must be ${either(rule.cardinalities)}`\n );\n } else if (cardinality && rule.max && cardinality !== 'multiple') {\n const value = interaction.getAttribute(rule.max.attribute);\n const max = value === null ? rule.max.default : Number(value);\n if (max === 0 || max > 1) {\n violations.push(`${where}: ${rule.max.attribute} ${max} requires multiple cardinality, not ${cardinality}`);\n }\n }\n\n if (cardinality !== 'record' && baseType && !rule.baseTypes.includes(baseType)) {\n violations.push(`${where}: base-type ${baseType} is not permitted; it must be ${either(rule.baseTypes)}`);\n }\n }\n }\n\n if (violations.length > 0) {\n throw new Error(`QTI validation error: ${violations.join('; ')}.`);\n }\n}\n","/**\n * The missing-seed warning is advice about configuration, not about the document being\n * transformed — say it once per session, shared by the item and test transformers since\n * both are pointing at the same missing `QTI_CONTEXT.seed`.\n *\n * Deliberately not re-exported from the package entry: `resetMissingSeedWarning` exists so\n * tests can restore the once-per-session state, not as public API.\n */\nlet missingSeedWarned = false;\n\nexport function warnMissingSeed(scope: string, fallbackSeed: string): void {\n if (missingSeedWarned) return;\n missingSeedWarned = true;\n console.warn(`[${scope}] No QTI_CONTEXT.seed provided; using \"${fallbackSeed}\" as deterministic fallback seed.`);\n}\n\nexport function resetMissingSeedWarning(): void {\n missingSeedWarned = false;\n}\n","/**\n * Parse XML, reporting a malformed document instead of handing one on.\n *\n * `DOMParser.parseFromString` never throws for `text/xml`: it returns a *document describing the\n * failure*, whose root is an HTML page reading \"This page contains the following errors…\". Nothing\n * downstream distinguishes that from a real item, so `toHTML` copied the error page into the DOM\n * and the player rendered the browser's parse error as the item — silently, past every try/catch,\n * because nothing ever threw.\n *\n * Leading whitespace and a BOM are stripped first. XML forbids anything before the declaration, so\n * a stray newline in front of `<?xml` is fatal to the letter of the spec — and it is also one of\n * the most common artefacts of an item that has been through an editor, a template or a copy and\n * paste. Accepting it costs nothing and keeps real authoring mistakes visible.\n */\n/**\n * The one useful sentence out of the error document — \"error on line N at column M: …\" — without\n * the page boilerplate the browser wraps it in.\n */\nfunction readParserMessage(error: Element): string {\n const text = (error.textContent || '').replace(/\\s+/g, ' ').trim();\n return (\n text\n .replace(/^This page contains the following errors:\\s*/i, '')\n .replace(/\\s*Below is a rendering of the page up to the first error\\.?\\s*$/i, '')\n .trim() || 'malformed XML'\n );\n}\n\nfunction parseXMLOrThrow(text: string, describeSource: (message: string) => string): XMLDocument {\n const parser = new DOMParser();\n const xmlFragment = parser.parseFromString(text.replace(/^[\\s\\uFEFF]+/, ''), 'text/xml');\n\n /*\n * Matched by the error document's own namespace, so an item that legitimately contains an\n * element named `parsererror` cannot be mistaken for a failure. Blink and WebKit put it in the\n * XHTML namespace; Gecko has a namespace of its own.\n */\n const error =\n xmlFragment.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'parsererror')[0] ??\n xmlFragment.getElementsByTagNameNS('http://www.mozilla.org/newlayout/xml/parsererror.xml', 'parsererror')[0];\n\n if (error) {\n throw new Error(describeSource(readParserMessage(error)));\n }\n\n return xmlFragment;\n}\n\nexport function loadXML(url: string, signal?: AbortSignal): Promise<XMLDocument | null> {\n return fetch(url, { signal })\n .then(response => {\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n return response.text();\n })\n .then(text => parseXMLOrThrow(text, message => `is not well-formed XML: ${message}`))\n .catch(error => {\n if (error.name === 'AbortError') {\n throw error;\n }\n throw new Error(`Failed to load XML: ${error.message}`);\n });\n}\n\nexport function parseXML(xmlDocument: string): XMLDocument {\n return parseXMLOrThrow(xmlDocument, message => `Failed to parse XML: ${message}`);\n}\n\n// Function to strip unsupported namespaces (qti) from the nodes sent to the browser\nfunction stripNamespaces(node: Node, doc: Document, registry?: CustomElementRegistry): Node {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as Element;\n let newEl: Element;\n\n if (\n !el.namespaceURI ||\n el.namespaceURI.startsWith('http://www.imsglobal.org/xsd/qti/') ||\n el.namespaceURI.startsWith('http://www.imsglobal.org/xsd/imsqti')\n ) {\n newEl = registry\n ? doc.createElement(el.localName, { customElementRegistry: registry })\n : doc.createElement(el.localName);\n } else {\n newEl = doc.createElementNS(el.namespaceURI, el.tagName);\n }\n\n for (let i = 0; i < el.attributes.length; i++) {\n const attr = el.attributes[i];\n newEl.setAttribute(attr.localName, attr.value);\n }\n for (let i = 0; i < el.childNodes.length; i++) {\n newEl.appendChild(stripNamespaces(el.childNodes[i], doc, registry));\n }\n return newEl;\n }\n return node.cloneNode(false);\n}\n\nexport function toHTML(xmlFragment: Document, registry?: CustomElementRegistry): DocumentFragment {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < xmlFragment.childNodes.length; i++) {\n fragment.appendChild(stripNamespaces(xmlFragment.childNodes[i], document, registry));\n }\n return fragment;\n}\n\n// Updates src and href attributes with the base location\n// Uses querySelectorAll('*') to find all elements, then checks attributes manually\n// This handles namespaced XML documents where attribute selectors like [href] may not work\n// Note: primary-path is NOT processed here because it is resolved separately\n// by the PCI component using data-base-url in the iframe's module resolution\nexport function setLocation(xmlFragment: DocumentFragment, location: string) {\n if (!location.endsWith('/')) {\n location += '/';\n }\n\n // querySelectorAll('*') finds all descendant elements regardless of namespace\n const allElements = xmlFragment.querySelectorAll('*');\n\n allElements.forEach(el => {\n // Check each attribute we care about\n // src, srcset and poster are URLDType or xs:anyURI everywhere they're used, so we care about them\n // Note: primary-path is excluded - PCI handles module path resolution via data-base-url\n for (const attr of ['src', 'href', 'srcset', 'poster'] as const) {\n const attrValue = el.getAttribute(attr)?.trim();\n\n if (attrValue && !/^(data:|https?:|blob:)/.test(attrValue)) {\n const newValue = location + encodeURI(attrValue);\n el.setAttribute(attr, newValue);\n }\n }\n });\n}\n","/**\n * Browser based QTI-XML to HTML transformer.\n * Returns an object with methods to load, parse, transform and serialize QTI XML items.\n * @returns An object with methods to load, parse, transform and serialize QTI XML items.\n * @example\n * const qtiTransformer = qtiTransformItem();\n * await qtiTransformer.load('path/to/xml/file.xml');\n * qtiTransformer.path('/assessmentItem/itemBody');\n * const html = qtiTransformer.html();\n * const xml = qtiTransformer.xml();\n * const htmldoc = qtiTransformer.htmldoc();\n * const xmldoc = qtiTransformer.xmldoc();\n *\n * qtiTransformItem().parse(storyXML).html()\n */\nimport { convertCDATAtoComment } from './item/cdata';\nimport { configurePci, type ModuleResolutionConfig } from './item/configure-pci';\nimport { extendElementName, extendElementsWithClass } from './item/extend';\nimport { pciHooks } from './item/pci-hooks';\nimport { shuffleInteractions } from './item/shuffle-interactions';\nimport { stripStyleSheets } from './item/stylesheets';\nimport { validateBindings } from './item/validate-bindings';\nimport { warnMissingSeed } from './shared/missing-seed-warning';\nimport { loadXML, parseXML, setLocation, toHTML } from './shared/xml';\n\nexport type { ModuleResolutionConfig };\n\nexport type transformItemApi = {\n load: (uri: string, signal?: AbortSignal) => Promise<transformItemApi>;\n parse: (xmlString: string) => transformItemApi;\n path: (location: string) => transformItemApi;\n fn: (fn: (xmlFragment: XMLDocument) => void) => transformItemApi;\n pciHooks: (uri: string) => transformItemApi;\n configurePci: (\n baseUrl: string,\n getModuleResolutionConfig: (baseUrl: string, fileUrl: string) => Promise<ModuleResolutionConfig>,\n selector?: string\n ) => Promise<transformItemApi>;\n extendElementName: (elementName: string, extend: string) => transformItemApi;\n extendElementsWithClass: (param?: string) => transformItemApi;\n customInteraction: (baseRef: string, baseItem: string) => transformItemApi;\n convertCDATAtoComment: () => transformItemApi;\n shuffleInteractions: (seed?: string | number | null) => transformItemApi;\n stripStyleSheets: () => transformItemApi;\n validateBindings: () => transformItemApi;\n html: () => string;\n xml: () => string;\n htmlDoc: (registry?: CustomElementRegistry) => DocumentFragment;\n xmlDoc: () => XMLDocument;\n};\n\nexport const qtiTransformItem = () => {\n let xmlFragment: XMLDocument;\n let xmlUri = '';\n\n const api: transformItemApi = {\n load(uri: string, signal?: AbortSignal) {\n xmlUri = uri;\n return loadXML(uri, signal).then(xml => {\n xmlFragment = xml;\n return api;\n });\n },\n parse(xmlString: string): typeof api {\n xmlFragment = parseXML(xmlString);\n xmlUri = '';\n return api;\n },\n path: (location: string): typeof api => {\n setLocation(xmlFragment, location);\n xmlUri = null;\n return api;\n },\n fn(fn: (xmlFragment: XMLDocument) => void): typeof api {\n fn(xmlFragment);\n return api;\n },\n pciHooks(uri: string): typeof api {\n pciHooks(xmlFragment, uri);\n return api;\n },\n async configurePci(\n baseUrl: string,\n getModuleResolutionConfig: (baseUrl: string, fileUrl: string) => Promise<ModuleResolutionConfig>,\n selector = 'qti-portable-custom-interaction'\n ): Promise<typeof api> {\n await configurePci(xmlFragment, baseUrl, getModuleResolutionConfig, selector);\n return api;\n },\n shuffleInteractions(seed?: string | number | null): typeof api {\n const normalizedSeed = typeof seed === 'string' ? seed.trim() : seed;\n\n if (normalizedSeed === null || normalizedSeed === undefined || normalizedSeed === '') {\n const fallbackSeed = xmlUri || 'default-item-seed';\n warnMissingSeed('qtiTransformItem', fallbackSeed);\n shuffleInteractions(xmlFragment, fallbackSeed);\n return api;\n }\n\n shuffleInteractions(xmlFragment, normalizedSeed);\n return api;\n },\n extendElementName: (tagName: string, extension: string): typeof api => {\n extendElementName(xmlFragment, tagName, extension);\n return api;\n },\n extendElementsWithClass: (param: string = 'extend'): typeof api => {\n extendElementsWithClass(xmlFragment, param);\n return api;\n },\n customInteraction(baseRef: string, baseItem: string): typeof api {\n const qtiCustomInteraction = xmlFragment.querySelector('qti-custom-interaction');\n const qtiCustomInteractionObject = qtiCustomInteraction.querySelector('object');\n\n qtiCustomInteraction.setAttribute('data-base-ref', baseRef);\n qtiCustomInteraction.setAttribute('data-base-item', baseRef + baseItem);\n qtiCustomInteraction.setAttribute('data', qtiCustomInteractionObject.getAttribute('data'));\n qtiCustomInteraction.setAttribute('width', qtiCustomInteractionObject.getAttribute('width'));\n qtiCustomInteraction.setAttribute('height', qtiCustomInteractionObject.getAttribute('height'));\n\n qtiCustomInteraction.removeChild(qtiCustomInteractionObject);\n return api;\n },\n convertCDATAtoComment(): typeof api {\n convertCDATAtoComment(xmlFragment);\n return api;\n },\n stripStyleSheets(): typeof api {\n stripStyleSheets(xmlFragment);\n return api;\n },\n /** Throws a QTI validation error when an interaction is bound to a response it cannot hold. */\n validateBindings(): typeof api {\n validateBindings(xmlFragment);\n return api;\n },\n html() {\n if (xmlUri !== null) {\n setLocation(xmlFragment, xmlUri.substring(0, xmlUri.lastIndexOf('/')));\n }\n return new XMLSerializer().serializeToString(toHTML(xmlFragment));\n },\n xml(): string {\n return new XMLSerializer().serializeToString(xmlFragment);\n },\n htmlDoc(registry?: CustomElementRegistry) {\n if (xmlUri !== null) {\n setLocation(xmlFragment, xmlUri.substring(0, xmlUri.lastIndexOf('/')));\n }\n return toHTML(xmlFragment, registry);\n },\n xmlDoc(): XMLDocument {\n return xmlFragment; // new XMLSerializer().serializeToString(xmlFragment);\n }\n };\n return api;\n};\n","import { loadXML, parseXML } from './shared/xml';\n\nexport const qtiTransformManifest = (): {\n load: (uri: string, signal?: AbortSignal) => Promise<typeof api>;\n assessmentTest: () => { href: string; identifier: string };\n} => {\n let xmlFragment: XMLDocument;\n\n const api = {\n // Awaits loadXML so a failed fetch (network, CORS, non-2xx) rejects this\n // promise. Callers own the failure: they can render it, retry it or let it\n // bubble — rather than it escaping as an unhandled rejection while their\n // own `await` never settles.\n async load(uri: string, signal?: AbortSignal) {\n xmlFragment = await loadXML(uri, signal);\n return api;\n },\n parse(xmlString: string) {\n xmlFragment = parseXML(xmlString);\n },\n assessmentTest() {\n const el = xmlFragment.querySelector('resource[type=\"imsqti_test_xmlv3p0\"]');\n return { href: el.getAttribute('href'), identifier: el.getAttribute('identifier') };\n }\n };\n return api;\n};\n","export function itemsFromTest(xmlFragment: DocumentFragment) {\n const items: { identifier: string; href: string; category: string }[] = [];\n xmlFragment.querySelectorAll('qti-assessment-item-ref').forEach(el => {\n const identifier = el.getAttribute('identifier');\n const href = el.getAttribute('href');\n const category = el.getAttribute('category');\n items.push({ identifier, href, category });\n });\n return items;\n}\n","import { loadXML } from '../shared/xml';\n\n/**\n * `qti-assessment-section-ref` (QTI 3 info model §7.5): a section kept in a file of its own. The\n * reference is a facade: \"the document that contains the reference, with the refered-to section\n * merged in, should behave exactly the same as a document that has all the same sections aggregated\n * in one document\". So a loaded test has every reference replaced by the section it names, before\n * anything reads the test (ordering, the host's transform callback, the test model).\n */\n\nconst SECTION_REF = 'qti-assessment-section-ref';\nconst SECTION = 'qti-assessment-section';\nconst ITEM_REF = 'qti-assessment-item-ref';\n\n/** The attributes `setLocation` makes absolute; a referenced section's are rebased the same way. */\nconst URL_ATTRIBUTES = ['src', 'href', 'srcset', 'poster'] as const;\nconst ABSOLUTE = /^(data:|https?:|blob:)/;\n\nconst isLocal = (el: Element, name: string) => el.localName === name || el.localName?.toLowerCase() === name;\n\nconst refsIn = (root: Document | Element): Element[] =>\n Array.from(root.getElementsByTagName('*')).filter(el => isLocal(el, SECTION_REF));\n\n/** The folder part of a relative href, with its trailing slash: `sections/a.xml` → `sections/`. */\nconst folderOf = (href: string) => href.slice(0, href.lastIndexOf('/') + 1);\n\n/** A key for cycle detection: `a/../b.xml` and `b.xml` are the same file. */\nconst keyOf = (url: string) => new URL(url, 'https://base.invalid/').href;\n\n/**\n * Makes the relative URLs in a section that came from `folder` relative to the file that refers to\n * it, by putting `folder` in front, so the one `setLocation` pass over the test resolves them.\n */\nfunction rebase(section: Element, folder: string): void {\n if (!folder) return;\n for (const el of [section, ...Array.from(section.getElementsByTagName('*'))]) {\n for (const attr of URL_ATTRIBUTES) {\n const value = el.getAttribute(attr)?.trim();\n if (value && !ABSOLUTE.test(value)) el.setAttribute(attr, folder + value);\n }\n }\n}\n\n/**\n * Replaces every `qti-assessment-section-ref` in `root` by the section its `href` names, fetched\n * relative to `location` (the folder of the file `root` came from, with a trailing slash).\n *\n * - The merged section takes the reference's `identifier`: a test may refer to one section file more\n * than once, and each reference has its own identifier.\n * - A referenced section may itself refer to sections; those resolve relative to its own file.\n * - Relative URLs in a referenced section (its item-refs, images) are rewritten to be relative to the\n * referring file, so they keep pointing where they did.\n *\n * Rejects when a file cannot be loaded, is not a single `qti-assessment-section`, or refers back to\n * itself through its references, and when the merged test repeats an item-ref identifier. QTI lets a\n * test refer to one section file more than once (§7.5) but requires unique item-ref identifiers\n * (§5.6); a file of item-refs referenced twice cannot satisfy both, and no identifier is invented to\n * make it (decided 2026-11-27).\n */\nexport async function resolveSectionRefs(root: XMLDocument, location: string, signal?: AbortSignal): Promise<void> {\n if (!hasSectionRefs(root)) return;\n await resolve(root, location, signal, []);\n\n const seen = new Set<string>();\n for (const itemRef of Array.from(root.getElementsByTagName('*')).filter(el => isLocal(el, ITEM_REF))) {\n const identifier = itemRef.getAttribute('identifier') ?? '';\n if (seen.has(identifier)) {\n throw new Error(\n `The test repeats ${ITEM_REF} \"${identifier}\" once its ${SECTION_REF}s are included; item-ref identifiers must be unique.`\n );\n }\n seen.add(identifier);\n }\n}\n\nasync function resolve(\n root: XMLDocument,\n location: string,\n signal: AbortSignal | undefined,\n seen: readonly string[]\n): Promise<void> {\n const base = location.endsWith('/') ? location : `${location}/`;\n for (const ref of refsIn(root)) {\n const href = ref.getAttribute('href')?.trim();\n if (!href) throw new Error(`${SECTION_REF} \"${ref.getAttribute('identifier')}\" has no href.`);\n\n const url = ABSOLUTE.test(href) ? href : base + encodeURI(href);\n const key = keyOf(url);\n if (seen.includes(key)) throw new Error(`${SECTION_REF} \"${href}\" refers back to itself.`);\n\n const doc = await loadXML(url, signal);\n const section = doc?.documentElement;\n if (!section || !isLocal(section, SECTION)) {\n throw new Error(`${SECTION_REF} \"${href}\" does not hold a single ${SECTION}.`);\n }\n\n await resolve(doc, url.slice(0, url.lastIndexOf('/') + 1), signal, [...seen, key]);\n if (!ABSOLUTE.test(href)) rebase(section, folderOf(href));\n\n const identifier = ref.getAttribute('identifier');\n if (identifier) section.setAttribute('identifier', identifier);\n ref.replaceWith(root.importNode(section, true));\n }\n}\n\n/** Whether a test still holds a `qti-assessment-section-ref`. */\nexport const hasSectionRefs = (root: Document): boolean => refsIn(root).length > 0;\n","/** The test elements selection and ordering read, by local name (QTI 3, and the 2.x spellings these transforms still accept). */\n\nexport const isLocal = (el: Element, ...names: string[]): boolean =>\n names.includes(el.localName) || names.includes(el.localName?.toLowerCase?.());\n\nexport const isItemRef = (el: Element): boolean => isLocal(el, 'qti-assessment-item-ref', 'assessmentitemref');\n\nexport const isSection = (el: Element): boolean => isLocal(el, 'qti-assessment-section', 'assessmentsection');\n\nexport const attrIsTrue = (el: Element, ...names: string[]): boolean =>\n names.some(n => {\n const v = (el.getAttribute(n) ?? '').trim().toLowerCase();\n return v === 'true' || v === '1';\n });\n\nexport const attrIsFalse = (el: Element, ...names: string[]): boolean =>\n names.some(n => {\n const v = (el.getAttribute(n) ?? '').trim().toLowerCase();\n return v === 'false' || v === '0';\n });\n\nexport const isOrdering = (el: Element): boolean => isLocal(el, 'qti-ordering', 'ordering');\n\nexport const isSelection = (el: Element): boolean => isLocal(el, 'qti-selection', 'selection');\n\nexport const isSessionControl = (el: Element): boolean => isLocal(el, 'qti-item-session-control', 'itemsessioncontrol');\n\n/** The item-refs and sections directly inside a section: what selection and ordering move. */\nexport const sectionUnits = (section: Element): Element[] =>\n Array.from(section.children).filter(child => isItemRef(child) || isSection(child));\n","import { createSeededRandom, itemInstanceId, selectUnits } from '@qti-components/delivery';\n\nimport { attrIsTrue, isItemRef, isSection, isSelection, sectionUnits } from './section-elements';\n\n/**\n * A `qti-selection` this transform understands: `select` and `with-replacement` (and namespace\n * declarations), no child elements. Implementation guide §4.5.1: one with attributes or children the\n * delivery engine does not understand asks for another algorithm, and is ignored entirely.\n */\nconst isStandardSelection = (el: Element): boolean =>\n el.children.length === 0 &&\n Array.from(el.attributes).every(\n a => a.name === 'select' || a.name === 'with-replacement' || a.name === 'xmlns' || a.name.startsWith('xmlns:')\n );\n\nconst selectionOf = (section: Element): Element | undefined =>\n Array.from(section.children).find(child => isSelection(child) && isStandardSelection(child));\n\n/**\n * Gives a clone and everything in it the next instance id of each identifier (`item-3#2`,\n * `sectionB#2`), so every rendered item-ref and section stays unique and each cloned section draws\n * its own selection and ordering. The first instance keeps the authored identifier.\n */\nfunction renameClone(clone: Element, instances: Map<string, number>): void {\n for (const el of [clone, ...Array.from(clone.getElementsByTagName('*'))]) {\n if (!isItemRef(el) && !isSection(el)) continue;\n const identifier = el.getAttribute('identifier') ?? '';\n const occurrence = (instances.get(identifier) ?? 1) + 1;\n instances.set(identifier, occurrence);\n el.setAttribute('identifier', itemInstanceId(identifier, occurrence));\n }\n}\n\n/** Applies a section's own `qti-selection`, then those of the subsections it kept, top down. */\nfunction selectSection(section: Element, seed: string | number, instances: Map<string, number>): void {\n const selection = selectionOf(section);\n if (selection) {\n const identifier = section.getAttribute('identifier') ?? '';\n const children = sectionUnits(section);\n let selected: number[];\n try {\n selected = selectUnits(\n children.map(child => ({ required: attrIsTrue(child, 'required') })),\n {\n select: Number(selection.getAttribute('select') ?? Number.NaN),\n withReplacement: attrIsTrue(selection, 'with-replacement')\n },\n createSeededRandom(`${seed}:select:${identifier}`)\n );\n } catch (error) {\n throw new RangeError(`[qtiTransformTest] Section \"${identifier}\": ${(error as Error).message}`);\n }\n\n // Unselected children go; a child selected again gets its clones right after it, so the\n // authored order stays for ordering to shuffle (§4.5.1).\n const kept = new Set(selected);\n for (const [index, child] of children.entries()) {\n if (!kept.has(index)) child.remove();\n }\n let previous: number | null = null;\n let last: Element | null = null;\n for (const index of selected) {\n if (index !== previous) {\n last = children[index];\n } else {\n const clone = children[index].cloneNode(true) as Element;\n renameClone(clone, instances);\n last!.after(clone);\n last = clone;\n }\n previous = index;\n }\n selection.remove();\n }\n\n for (const child of sectionUnits(section)) {\n if (isSection(child)) selectSection(child, seed, instances);\n }\n}\n\n/** Whether anything in `doc` asks for a selection this transform applies. */\nexport function hasSelection(doc: XMLDocument): boolean {\n return Array.from(doc.getElementsByTagName('*')).some(el => isSelection(el) && isStandardSelection(el));\n}\n\n/**\n * Mutates `doc` in place: applies every `qti-selection` (implementation guide §4.5.1), top down, so a\n * subsection's own selection runs only when the subsection is selected. Each section draws from its\n * own stream (`seed:select:sectionId`), apart from ordering's, so the same seed selects the same\n * items and a test without selection keeps its order. Throws a `RangeError` for a selection QTI\n * calls an error.\n */\nexport function selectSections(doc: XMLDocument, seed: string | number): void {\n const instances = new Map<string, number>();\n const topLevel = Array.from(doc.getElementsByTagName('*')).filter(\n el => isSection(el) && !(el.parentElement && isSection(el.parentElement))\n );\n for (const section of topLevel) selectSection(section, seed, instances);\n}\n","import { createSeededRandom, shuffleKeepingFixed } from '@qti-components/delivery';\n\nimport {\n attrIsFalse,\n attrIsTrue,\n isItemRef,\n isOrdering,\n isSection,\n isSelection,\n isSessionControl,\n sectionUnits\n} from './section-elements';\n\n/**\n * A `qti-ordering` this transform understands: only `shuffle` (and namespace declarations), no\n * child elements. Impl. guide §4.5.2: one with attributes or children a delivery system does not\n * recognise is an extension point for another algorithm, and is ignored entirely.\n */\nconst isStandardOrdering = (el: Element): boolean =>\n el.children.length === 0 &&\n Array.from(el.attributes).every(a => a.name === 'shuffle' || a.name === 'xmlns' || a.name.startsWith('xmlns:'));\n\nconst shuffleOrderingElements = (section: Element): Element[] =>\n Array.from(section.children).filter(\n child => isOrdering(child) && isStandardOrdering(child) && attrIsTrue(child, 'shuffle')\n );\n\nconst rngFor = (seed: string | number, key: string) => createSeededRandom(`${seed}:${key}`);\n\n/** A movable unit in a section: one item-ref or one subsection, moved whole. */\ntype Unit = { node: Element; fixed: boolean };\n\n/**\n * Impl. guide §4.5.2: \"If visible=\"true\" or keep-together=\"true\" (the default), then the subsection\n * is shuffled as a unit\"; only when both are false are its children \"merged and shuffled together\n * with the items and subsections of the parent section\".\n */\nconst dissolves = (section: Element): boolean =>\n attrIsFalse(section, 'visible') && attrIsFalse(section, 'keep-together', 'keeptogether');\n\n/**\n * Hand a dissolved subsection's `qti-item-session-control` down to a child that leaves it: the\n * child's own attributes win, the subsection's fill the rest, as the cascade would have\n * (info model §7.19).\n */\nfunction inheritSessionControl(child: Element, from: Element | undefined): void {\n if (!from) return;\n let own = Array.from(child.children).find(isSessionControl);\n if (!own) {\n own = child.ownerDocument.createElementNS(from.namespaceURI, from.tagName);\n child.insertBefore(own, child.firstChild);\n }\n for (const attribute of Array.from(from.attributes)) {\n if (!own.hasAttribute(attribute.name)) own.setAttribute(attribute.name, attribute.value);\n }\n}\n\nfunction warnDroppedChildren(section: Element, dropped: string[]): void {\n if (dropped.length === 0) return;\n const identifier = section.getAttribute('identifier') ?? '(no identifier)';\n console.warn(\n `[qtiTransformTest] Subsection \"${identifier}\" (visible=\"false\", keep-together=\"false\") is merged into its ` +\n `parent by section ordering; discarding its ${[...new Set(dropped)].join(', ')}.`\n );\n}\n\n/**\n * The units a subsection gives its shuffling parent: itself, or, when it dissolves, its own\n * item-refs and subsections (recursively, for a dissolving one among them), each taking the\n * subsection's session control along.\n */\nfunction unitsOf(child: Element): Unit[] {\n if (isItemRef(child)) return [{ node: child, fixed: attrIsTrue(child, 'fixed') }];\n if (!dissolves(child)) return [{ node: child, fixed: attrIsTrue(child, 'fixed') }];\n\n const sessionControl = Array.from(child.children).find(isSessionControl);\n const dropped: string[] = [];\n const units: Unit[] = [];\n for (const grandchild of Array.from(child.children)) {\n if (isItemRef(grandchild) || isSection(grandchild)) {\n inheritSessionControl(grandchild, sessionControl);\n units.push(...unitsOf(grandchild));\n } else if (!isOrdering(grandchild) && !isSelection(grandchild) && !isSessionControl(grandchild)) {\n // Directives are transform config and session control is carried down; anything else (a\n // rubric block, a time limit, a pre-condition) belongs to the section that is going away.\n dropped.push(grandchild.localName);\n }\n }\n warnDroppedChildren(child, dropped);\n return units;\n}\n\n/**\n * Seed-deterministic QTI section shuffling (impl. guide §4.5.2).\n *\n * Reorders the children of every <qti-assessment-section> that carries a\n * <qti-ordering shuffle=\"true\">:\n *\n * - Depth-first: a subsection orders its own children before the parent\n * reorders it.\n * - Item refs and subsections with fixed=\"true\" stay in their authored slot;\n * the other units shuffle around them.\n * - A subsection that is visible, or keeps together (QTI's default), moves as\n * one unit: it stays a section, with its items in its own order.\n * - A subsection with visible=\"false\" and keep-together=\"false\" dissolves: its\n * item refs and subsections join the parent's pool and interleave with the\n * parent's own units, taking the subsection's session control along.\n *\n * The same `seed` always produces the same order, so a restarted session keeps\n * its sequence. Each section draws from its own PRNG stream (seed + section id)\n * so sibling sections are independent and stable.\n */\nfunction orderSection(section: Element, seed: string | number): void {\n // Depth-first: let every child section order itself first.\n for (const child of Array.from(section.children)) {\n if (isSection(child)) {\n orderSection(child, seed);\n }\n }\n\n const orderingEls = shuffleOrderingElements(section);\n if (orderingEls.length === 0) {\n return;\n }\n\n // The pool of movable units in document order. Other children (qti-ordering,\n // qti-selection, a rubric block, …) are left in place.\n const children = sectionUnits(section);\n const units = children.flatMap(unitsOf);\n\n // Where the reordered units go back in: after the last child we take out, so\n // any trailing structural children (a rubric block, say) keep their position.\n const anchor = children.length > 0 ? children[children.length - 1].nextSibling : null;\n\n const sectionKey = section.getAttribute('identifier') ?? '';\n const ordered = shuffleKeepingFixed(units, rngFor(seed, sectionKey));\n\n for (const child of children) {\n child.remove();\n }\n for (const unit of ordered) {\n section.insertBefore(unit.node, anchor);\n }\n\n // Ordering directives are consumed by this transform step.\n for (const orderingEl of orderingEls) {\n orderingEl.remove();\n }\n}\n\n/** Whether anything in `doc` asks to be shuffled at all. */\nexport function hasShuffleOrdering(doc: XMLDocument): boolean {\n return Array.from(doc.getElementsByTagName('*')).some(\n el => isOrdering(el) && isStandardOrdering(el) && attrIsTrue(el, 'shuffle')\n );\n}\n\n/**\n * Mutates `doc` in place: shuffles every section flagged with\n * <qti-ordering shuffle=\"true\">, deterministically from `seed`.\n */\nexport function shuffleSectionsOrdering(doc: XMLDocument, seed: string | number): void {\n const sections = Array.from(doc.getElementsByTagName('*')).filter(el => isSection(el));\n // Kick off recursion only for top-level sections; orderSection handles nesting\n // depth-first, so descendants are not double-processed.\n for (const section of sections) {\n // The snapshot above can contain wrappers that an ancestor has since\n // consumed. A detached element has no parentNode; a document element still\n // has one (the document), so this does not skip a section-rooted document.\n if (!section.parentNode) continue;\n\n const parent = section.parentElement;\n if (parent && isSection(parent)) continue;\n\n orderSection(section, seed);\n }\n}\n","/**\n * Returns an object with methods to load, parse and transform QTI tests.\n * @returns An object with methods to load, parse and transform QTI tests.\n * @example\n * const qtiTransformer = qtiTransformTest();\n * await qtiTransformer.load('https://example.com/test.xml');\n * const items = qtiTransformer.items();\n * const html = qtiTransformer.html();\n * const xml = qtiTransformer.xml();\n */\n\nimport { warnMissingSeed } from './shared/missing-seed-warning';\nimport { loadXML, parseXML, setLocation, toHTML } from './shared/xml';\nimport { itemsFromTest } from './test/items';\nimport { hasSectionRefs, resolveSectionRefs } from './test/section-refs';\nimport { hasSelection, selectSections } from './test/select-sections';\nimport { hasShuffleOrdering, shuffleSectionsOrdering } from './test/shuffle-sections';\n\nexport type transformTestApi = {\n /** Fetches the test, includes every `qti-assessment-section-ref`'s section, and makes URLs absolute. */\n load: (uri: string, signal?: AbortSignal) => Promise<transformTestApi>;\n parse: (xmlString: string) => transformTestApi;\n path: (location: string) => transformTestApi;\n fn: (fn: (xmlFragment: XMLDocument) => void) => transformTestApi;\n /**\n * Apply every `qti-selection`: keep the item-refs and subsections each section selects, required\n * ones always, the same for the same seed (implementation guide §4.5.1). A `with-replacement` clone\n * is a copy of the item-ref or subsection with the next instance id (`item-3#2`). Run it before\n * `shuffleOrdering`, with the same seed. Throws for a selection QTI calls an error.\n */\n applySelection: (seed?: string | number | null) => transformTestApi;\n /**\n * Deterministically shuffle the children of every section that carries a\n * <qti-ordering shuffle=\"true\">, honoring fixed items and nested\n * keep-together / visible rules. The same seed reproduces the same order.\n */\n shuffleOrdering: (seed?: string | number | null) => transformTestApi;\n items: () => { identifier: string; href: string; category: string }[];\n html: () => string;\n xml: () => string;\n htmlDoc: (registry?: CustomElementRegistry) => DocumentFragment;\n xmlDoc: () => XMLDocument;\n};\n\nexport const qtiTransformTest = (): transformTestApi => {\n let xmlFragment: XMLDocument;\n let xmlUri = '';\n\n /** The host's seed, or a fixed one from the test's URL, with a warning, so a test still loads the same. */\n const seedOrFallback = (seed?: string | number | null): string | number => {\n const normalizedSeed = typeof seed === 'string' ? seed.trim() : seed;\n if (normalizedSeed !== null && normalizedSeed !== undefined && normalizedSeed !== '') return normalizedSeed;\n const fallbackSeed = xmlUri || 'default-test-seed';\n warnMissingSeed('qtiTransformTest', fallbackSeed);\n return fallbackSeed;\n };\n\n const api: transformTestApi = {\n // Awaits loadXML so a failed fetch (network, CORS, non-2xx) rejects this\n // promise. Callers own the failure: they can render it, retry it or let it\n // bubble — rather than it escaping as an unhandled rejection while their\n // own `await` never settles.\n //\n // Every qti-assessment-section-ref is replaced by the section it names, fetched relative to the\n // test, before anything else reads the test: QTI makes the reference a facade (info model §7.5).\n async load(uri, signal) {\n xmlFragment = await loadXML(uri, signal);\n xmlUri = uri;\n\n const location = uri.substring(0, uri.lastIndexOf('/'));\n await resolveSectionRefs(xmlFragment, location, signal);\n api.path(location);\n return api;\n },\n // A test given as a string has no location to fetch referenced sections from, so a\n // qti-assessment-section-ref stays as it is (with a warning) and its items are not in the test.\n parse(xmlString: string) {\n xmlFragment = parseXML(xmlString);\n xmlUri = '';\n if (hasSectionRefs(xmlFragment)) {\n console.warn(\n \"[qtiTransformTest] qti-assessment-section-ref needs the test's location: load() the test by URL to include referenced sections.\"\n );\n }\n return api;\n },\n path: (location: string): typeof api => {\n setLocation(xmlFragment, location);\n return api;\n },\n fn(fn: (xmlFragment: XMLDocument) => void) {\n fn(xmlFragment);\n return api;\n },\n applySelection(seed?: string | number | null) {\n // Nothing to select: leave the test alone, and stay quiet about a missing seed.\n if (!hasSelection(xmlFragment)) return api;\n selectSections(xmlFragment, seedOrFallback(seed));\n return api;\n },\n shuffleOrdering(seed?: string | number | null) {\n // No section asks to be shuffled: leave the test alone, and stay quiet\n // about a missing seed that would never have been used.\n if (!hasShuffleOrdering(xmlFragment)) {\n return api;\n }\n shuffleSectionsOrdering(xmlFragment, seedOrFallback(seed));\n return api;\n },\n items() {\n return itemsFromTest(xmlFragment);\n },\n html() {\n return new XMLSerializer().serializeToString(toHTML(xmlFragment));\n },\n xml(): string {\n return new XMLSerializer().serializeToString(xmlFragment);\n },\n htmlDoc(registry?: CustomElementRegistry) {\n return toHTML(xmlFragment, registry);\n },\n xmlDoc(): XMLDocument {\n return xmlFragment;\n }\n };\n return api;\n};\n"],"mappings":";AAAM,SAAU,sBAAsB,aAA6B;AACjE,QAAM,gBAAgB,YAAY,iBAAiB,sDAAsD;AACzG,gBAAc,QAAQ,aAAU;AAC9B,UAAM,cAAc,SAAS,cAAc,QAAQ,WAAW;AAC9D,YAAQ,aAAa,aAAa,QAAQ,UAAU;EACtD,CAAC;AACH;;;ACWA,eAAsB,aACpB,aACA,SACA,2BACA,WAAW,mCAAiC;AAE5C,QAAM,mCAA6C,CAAA;AACnD,QAAM,6BAA6B,YAAY,iBAAiB,QAAQ;AAIxE,MAAI,2BAA2B,WAAW,GAAG;AAC3C;EACF;AAGA,MAAI,yBAAwD;AAC5D,MAAI,iCAAgE;AACpE,QAAM,uCAAuC,YAAW;AACtD,QAAI,2BAA2B,MAAM;AACnC,UAAI;AACF,iCAAyB,MAAM,0BAA0B,SAAS,+BAA+B;MACnG,QAAQ;AACN,iCAAyB;MAC3B;IACF;AACA,QAAI,mCAAmC,MAAM;AAC3C,UAAI;AACF,yCAAiC,MAAM,0BACrC,SACA,wCAAwC;MAE5C,QAAQ;AACN,yCAAiC;MACnC;IACF;EACF;AAEA,aAAW,eAAe,MAAM,KAAK,0BAA0B,GAAG;AAEhE,gBAAY,aAAa,iBAAiB,OAAO;AAEjD,QAAI,k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