@pie-qti/player-elements 0.1.24 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ItemToolBar-d36g3aw4-B6TGPyKt.js +3079 -0
- package/dist/ItemToolBar-d36g3aw4-B6TGPyKt.js.map +1 -0
- package/dist/{define-D7_K0JFy.js → define-D80uAEx4.js} +1902 -4395
- package/dist/define-D80uAEx4.js.map +1 -0
- package/dist/dist-BSG0NOza.js +229 -0
- package/dist/dist-BSG0NOza.js.map +1 -0
- package/dist/{dist-ffJZTPTU.js → dist-C8BDh5vZ.js} +987 -707
- package/dist/dist-C8BDh5vZ.js.map +1 -0
- package/dist/dist-CQel8-vi.js +2507 -0
- package/dist/dist-CQel8-vi.js.map +1 -0
- package/dist/{dist-BaQdJU08.js → dist-L-bDDBry.js} +116 -103
- package/dist/dist-L-bDDBry.js.map +1 -0
- package/dist/{element-DSCNeDLu.js → element-C5rTAwch.js} +2 -2
- package/dist/{element-DSCNeDLu.js.map → element-C5rTAwch.js.map} +1 -1
- package/dist/{element-class-DQy2cIPM-CldZrSRR.js → element-class-B_qAd8ET-DGj15cBY.js} +5124 -4448
- package/dist/element-class-B_qAd8ET-DGj15cBY.js.map +1 -0
- package/dist/elements.js +3 -3
- package/dist/index.js +2 -2
- package/dist/item-toolbar-element-BgqPFwsS.js +1990 -0
- package/dist/item-toolbar-element-BgqPFwsS.js.map +1 -0
- package/dist/{language-tags-DVlRltrl.js → language-tags-BwFWXo71.js} +3 -3
- package/dist/{language-tags-DVlRltrl.js.map → language-tags-BwFWXo71.js.map} +1 -1
- package/dist/{nl-NL-BeQBX6yq.js → nl-NL-BRA_1Wcl.js} +5 -3
- package/dist/nl-NL-BRA_1Wcl.js.map +1 -0
- package/dist/pie-DwmznDHb.js +363 -0
- package/dist/pie-DwmznDHb.js.map +1 -0
- package/dist/pie-assessment-toolkit-Cruxm385.js +5 -0
- package/dist/pie-assessment-toolkit-Cruxm385.js.map +1 -0
- package/dist/pie-assessment-toolkit-DJfg6laX.js +5 -0
- package/dist/pie-assessment-toolkit-DJfg6laX.js.map +1 -0
- package/dist/{pie-assessment-toolkit-element-CpiB3twr.js → pie-assessment-toolkit-element-CT5UuvVY.js} +1364 -1203
- package/dist/pie-assessment-toolkit-element-CT5UuvVY.js.map +1 -0
- package/dist/pie-tool-calculator-Crfk-IZe.js +378 -0
- package/dist/pie-tool-calculator-Crfk-IZe.js.map +1 -0
- package/dist/{provider-Y5PhmTAu.js → provider-gBXlGb0d.js} +3 -3
- package/dist/{provider-Y5PhmTAu.js.map → provider-gBXlGb0d.js.map} +1 -1
- package/dist/register-players.js +1 -1
- package/dist/register.js +10246 -9664
- package/dist/register.js.map +1 -1
- package/dist/{resolveItems-D8DJkv-4.js → resolveItems-CNMvD8LP.js} +2 -2
- package/dist/{resolveItems-D8DJkv-4.js.map → resolveItems-CNMvD8LP.js.map} +1 -1
- package/dist/{root-DSkIM1v3.js → root-dCY6j_Hh.js} +3 -3
- package/dist/{root-DSkIM1v3.js.map → root-dCY6j_Hh.js.map} +1 -1
- package/dist/tag-names-DZGvnAgd.js +2495 -0
- package/dist/tag-names-DZGvnAgd.js.map +1 -0
- package/dist/{tool-tts-inline-B71NTBbb.js → tool-tts-inline-k3hLJUfp.js} +1315 -1303
- package/dist/tool-tts-inline-k3hLJUfp.js.map +1 -0
- package/package.json +8 -8
- package/dist/define-D7_K0JFy.js.map +0 -1
- package/dist/dist-BRTWr852.js +0 -5809
- package/dist/dist-BRTWr852.js.map +0 -1
- package/dist/dist-BaQdJU08.js.map +0 -1
- package/dist/dist-DwvskOs6.js +0 -220
- package/dist/dist-DwvskOs6.js.map +0 -1
- package/dist/dist-ffJZTPTU.js.map +0 -1
- package/dist/element-class-DQy2cIPM-CldZrSRR.js.map +0 -1
- package/dist/item-toolbar-element-BW9Y_n5x.js +0 -1990
- package/dist/item-toolbar-element-BW9Y_n5x.js.map +0 -1
- package/dist/nl-NL-BeQBX6yq.js.map +0 -1
- package/dist/pie-assessment-toolkit-element-CpiB3twr.js.map +0 -1
- package/dist/pie-tool-calculator-BiWMTJe7.js +0 -2992
- package/dist/pie-tool-calculator-BiWMTJe7.js.map +0 -1
- package/dist/tool-tts-inline-B71NTBbb.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"define-D80uAEx4.js","names":["resolveCheckedPackagePath","hasUnsafeEncodedPathToken","safeDecodeURIComponent","serializeChildren","isElement","mergeDeliveryFields","extractAttribute","parseXml","findDescendants","parseHtml","record","findDescendants","escapeHtmlAttribute","parseXml","resolveCheckedPackagePath","shuffleArray","normalizeQtiViewTokens","isQtiViewVisibleForRole","isQtiViewVisibleForRole","isQtiViewVisibleForRole","normalizeQtiViewTokens","isQtiViewVisibleForRole","isQtiViewVisibleForRole","enUS","#state","#itemIdentifiers","#sessionController","#initializeItemSessions","#restoreItemSessionsFromState","#restoreItemResultsFromScores","#itemSessionStateSnapshot","#itemResults","#mountController","#controller","#hostBackend","#initSession","#dispatchLoadError","#syncFromQti","#loadSeq","#resourceLoadController","#allowMount","#assessmentTestXml","#referenceMode","#assessmentId","#syncInitSessionFromIds","#candidateId","#itemBaseUrl","#items","#config","#security","#pci","#initSessionSource","#backend","#syncSecureBackendMount","#itemFetchPolicy","#deactivateLocalBackend","#effectiveSecurity","#resourceItemsForParsedAssessment","#resolvedItemXmlMap","#composition","#security","#pci","#typeset"],"sources":["../../ims-cp-core/dist/package-path.js","../../ims-cp-core/dist/package-file-resolver.js","../../ims-cp-core/dist/qti3-shared-content.js","../../item-player/dist/core/parsingLimits.js","../../item-player/dist/core/sanitizer.js","../../item-player/dist/core/trustedTypes.js","../../item-player/dist/security/styleValues.js","../../item-player/dist/security/index.js","../../item-player/dist/core/ComponentRegistry.js","../../item-player/dist/extraction/types.js","../../item-player/dist/extraction/ExtractionRegistry.js","../../item-player/dist/extraction/deliveryTypes.js","../../item-player/dist/core/random.js","../../item-player/dist/core/shuffle.js","../../item-player/dist/interactions/associate/extractor.js","../../item-player/dist/interactions/choice/extractor.js","../../item-player/dist/interactions/custom/extractor.js","../../item-player/dist/interactions/drawing/extractor.js","../../item-player/dist/interactions/end-attempt/extractor.js","../../item-player/dist/interactions/extended-text/extractor.js","../../item-player/dist/interactions/gap-match/extractor.js","../../item-player/dist/interactions/graphic-associate/extractor.js","../../item-player/dist/interactions/graphic-gap-match/extractor.js","../../item-player/dist/interactions/graphic-order/extractor.js","../../item-player/dist/interactions/hotspot/extractor.js","../../item-player/dist/interactions/hottext/extractor.js","../../item-player/dist/interactions/inline-choice/extractor.js","../../item-player/dist/interactions/match/extractor.js","../../item-player/dist/interactions/media/extractor.js","../../item-player/dist/interactions/order/extractor.js","../../item-player/dist/interactions/position-object/extractor.js","../../item-player/dist/interactions/portable-custom/extractor.js","../../item-player/dist/interactions/select-point/extractor.js","../../item-player/dist/interactions/slider/extractor.js","../../item-player/dist/interactions/text-entry/extractor.js","../../item-player/dist/interactions/upload/extractor.js","../../item-player/dist/interactions/modules.js","../../item-player/dist/document/AssessmentItemDocument.js","../../item-player/dist/extraction/utils.js","../../item-player/dist/extraction/createContext.js","../../item-player/dist/extraction/interactionSecurity.js","../../item-player/dist/extraction/interactionExtractionPipeline.js","../../item-player/dist/pnp/applyPnp.js","../../item-player/dist/catalog/catalogExtractor.js","../../item-player/dist/catalog/catalogLookup.js","../../item-player/dist/pci/types.js","../../item-player/dist/pci/PciHost.js","../../item-player/dist/interactions/extended-text/response.js","../../item-player/dist/core/Player.js","../../item-player/dist/core/rolePolicy.js","../../item-player/dist/components/utils/feedbackUtils.js","../../item-player/dist/components/utils/stylesheetRender.js","../../item-player/dist/components/utils/stimulusRender.js","../../item-player/dist/interactions/inline/render-plan.js","../../item-player/dist/presentation/itemPresentationPlan.js","../../item-player/dist/core/ItemSession.js","../../item-player/dist/core/AssessmentItemDefinition.js","../../assessment-player/dist/integration/assessment-item-scorer.js","../../assessment-player/dist/integration/ReferenceBackendAdapter.js","../../assessment-toolkit/dist/role-view.js","../../assessment-toolkit/dist/tool-normalization.js","../../assessment-toolkit/dist/shared-context-normalization.js","../../section-player/dist/visibility/role-view.js","../../section-player/dist/composition/resolveQtiSectionComposition.js","../../i18n/dist/locales/en-US.js","../../i18n/dist/core/I18n.js","../../section-player/src/visibility/role-view.ts","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-context.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-assessment-toolkit/dist/tools/tool-tag-map.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-providers/DesmosToolProvider.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-providers/TTSToolProvider.js","../../../node_modules/.bun/@pie-players+pie-default-tool-loaders@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-default-tool-loaders/dist/registrations/calculator.js","../../../node_modules/.bun/@pie-players+pie-default-tool-loaders@0.3.73+4df9da1290a48f6a/node_modules/@pie-players/pie-default-tool-loaders/dist/registrations/tts.js","../../section-player/src/tools/section-tool-config.ts","../../section-player/src/components/QtiToolButtonBar.svelte","../../default-components/dist/shared/actions/typesetAction.js","../../section-player/src/security/sanitizeSharedHtml.ts","../../section-player/src/components/SanitizedHtml.svelte","../../section-player/src/components/RubricDisplay.svelte","../../section-player/src/runtime/notifyRuntimeHost.ts","../../section-player/src/tts/readable-interaction-projection.ts","../../section-player/src/components/ItemRenderer.svelte","../../section-player/src/components/SplitPaneResizer.svelte","../../section-player/src/components/SectionPlayerSplitPane.svelte","../../section-player/src/components/SectionPlayerVertical.svelte","../../section-player/src/components/TestFeedback.svelte","../../assessment-player/src/core/ItemSessionController.ts","../../assessment-player/src/core/AssessmentSessionCoordinator.ts","../../assessment-player/src/core/NavigationManager.ts","../../assessment-player/src/core/TimeManager.ts","../../assessment-player/src/core/AssessmentPlayer.ts","../../assessment-player/src/integration/toSectionComposition.ts","../../assessment-player/src/components/AccessibilityAnnouncer.svelte","../../assessment-player/src/components/SectionMenu.svelte","../../assessment-player/src/components/AssessmentHeader.svelte","../../assessment-player/src/components/NavigationBar.svelte","../../assessment-player/src/components/AssessmentShell.svelte","../src/utils/json.ts","../src/elements/BaseSvelteMountElement.ts","../src/elements/QtiAssessmentPlayerElement.ts","../src/elements/QtiSectionPlayerSplitPaneElement.ts","../src/elements/QtiSectionPlayerVerticalElement.ts","../src/define.ts"],"sourcesContent":["export function joinPackagePath(...parts) {\n return parts.filter(Boolean).join('/');\n}\nexport function dirnamePackagePath(path) {\n const normalized = path.replaceAll('\\\\', '/');\n const index = normalized.lastIndexOf('/');\n return index === -1 ? '' : normalized.slice(0, index);\n}\nexport function resolvePackagePath(basePath, href) {\n return resolvePackagePathInternal(basePath, href).path;\n}\nexport function resolvePackagePathFromFile(baseHref, href) {\n return resolvePackagePath(dirnamePackagePath(baseHref), href);\n}\nexport function resolveCheckedPackagePath(basePath, href) {\n if (!isPackageRelativeHref(href))\n return null;\n if (hasUnsafeEncodedPathToken(href))\n return null;\n if (!isSafePackageBasePath(basePath))\n return null;\n const result = resolvePackagePathInternal(basePath, href, { rejectRootEscape: true });\n return result.escapedRoot ? null : result.path;\n}\nexport function resolveCheckedPackagePathFromFile(baseHref, href) {\n return resolveCheckedPackagePath(dirnamePackagePath(baseHref), href);\n}\nexport function isPackageRelativeHref(href) {\n const value = href.trim();\n return Boolean(value) && !value.startsWith('/') && !value.startsWith('//') && !/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.test(value);\n}\nexport function isExternalPackageHref(href) {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i.test(href);\n}\nfunction isSafePackageBasePath(basePath) {\n if (!basePath)\n return true;\n if (!isPackageRelativeHref(basePath))\n return false;\n if (hasUnsafeEncodedPathToken(basePath))\n return false;\n return !resolvePackagePathInternal(undefined, basePath, { rejectRootEscape: true }).escapedRoot;\n}\nfunction resolvePackagePathInternal(basePath, href, options = {}) {\n const raw = href.replaceAll('\\\\', '/');\n const combined = raw.startsWith('/') ? raw.slice(1) : joinPackagePath(basePath, raw);\n const normalized = [];\n let escapedRoot = false;\n for (const part of combined.split('/')) {\n if (!part || part === '.')\n continue;\n if (part === '..') {\n if (normalized.length === 0) {\n escapedRoot = true;\n if (options.rejectRootEscape)\n continue;\n }\n else {\n normalized.pop();\n }\n continue;\n }\n normalized.push(part);\n }\n return { path: normalized.join('/'), escapedRoot };\n}\nfunction hasUnsafeEncodedPathToken(href) {\n let current = href;\n for (let i = 0; i < 3; i += 1) {\n if (/%(?:2e|2f|5c)/i.test(current)) {\n return true;\n }\n const decoded = safeDecodeURIComponent(current);\n if (decoded === current) {\n return false;\n }\n current = decoded;\n }\n return /%(?:2e|2f|5c)/i.test(current);\n}\nfunction safeDecodeURIComponent(value) {\n try {\n return decodeURIComponent(value);\n }\n catch {\n return value;\n }\n}\n//# sourceMappingURL=package-path.js.map","import { DEFAULT_HEURISTICS_CONFIG, normalizeHeuristicsConfig, } from './qti-heuristics.js';\nexport function buildPackageFileIndex(paths) {\n const exactPaths = new Set();\n const pathsBySuffix = new Map();\n const pathsByBasename = new Map();\n const diagnostics = [];\n for (const rawPath of paths) {\n const normalized = normalizePackagePath('', rawPath);\n if (hasUnsafeEncodedPathToken(rawPath) || normalized.unsafe || !normalized.path) {\n diagnostics.push({\n severity: 'warning',\n code: 'IMS_CP_FILE_INDEX_UNSAFE_PATH',\n message: `Package file index skipped unsafe path: ${rawPath}.`,\n reference: rawPath,\n });\n continue;\n }\n if (exactPaths.has(normalized.path)) {\n diagnostics.push({\n severity: 'warning',\n code: 'IMS_CP_FILE_INDEX_COLLISION',\n message: `Package file index saw duplicate canonical path: ${normalized.path}.`,\n reference: rawPath,\n candidatePaths: [normalized.path],\n });\n continue;\n }\n exactPaths.add(normalized.path);\n addSuffixes(pathsBySuffix, normalized.path);\n const basename = basenameOf(normalized.path);\n if (basename) {\n mapArrayFor(pathsByBasename, lookupKey(basename)).push(normalized.path);\n }\n }\n return { exactPaths, pathsBySuffix, pathsByBasename, diagnostics };\n}\nexport function resolvePackageReference(input) {\n const rawHref = input.rawHref;\n const trimmed = String(rawHref ?? '').trim();\n const split = splitLookupHref(trimmed);\n const lookupHref = split.lookupHref.replaceAll('\\\\', '/').trim();\n const diagnostics = [];\n if (!lookupHref || lookupHref.startsWith('#') || isExternalHref(lookupHref)) {\n return {\n status: 'skipped',\n rawHref,\n lookupHref,\n queryAndFragment: split.queryAndFragment,\n diagnostics,\n };\n }\n if (lookupHref.startsWith('/') || hasUnsafeEncodedPathToken(lookupHref)) {\n return unsafeResolution(rawHref, lookupHref, split.queryAndFragment, input.sourcePath);\n }\n const sourceBase = input.sourcePath ? dirname(input.sourcePath) : '';\n const sourceCandidate = normalizePackagePath(sourceBase, lookupHref);\n if (sourceCandidate.unsafe) {\n return unsafeResolution(rawHref, lookupHref, split.queryAndFragment, input.sourcePath);\n }\n const sourceMatch = exactMatch(input.fileIndex, sourceCandidate.path);\n if (sourceMatch) {\n return resolved(rawHref, lookupHref, split.queryAndFragment, sourceMatch, 'source-relative', false, diagnostics);\n }\n const rootCandidate = normalizePackagePath('', lookupHref);\n if (!rootCandidate.unsafe) {\n const rootMatch = exactMatch(input.fileIndex, rootCandidate.path);\n if (rootMatch) {\n return resolved(rawHref, lookupHref, split.queryAndFragment, rootMatch, 'package-root', false, diagnostics);\n }\n }\n const heuristics = normalizeHeuristicsConfig(input.heuristicsConfig ?? DEFAULT_HEURISTICS_CONFIG);\n if (!heuristics.enabled || !heuristics.lenientPackageResourcePaths) {\n return missing(rawHref, lookupHref, split.queryAndFragment, input.sourcePath, [\n {\n severity: 'info',\n code: 'IMS_CP_REFERENCE_HEURISTIC_DISABLED',\n message: `Heuristic package path resolution is disabled for ${lookupHref}.`,\n sourcePath: input.sourcePath,\n reference: rawHref,\n },\n ]);\n }\n const suffixKeys = suffixLookupKeys(sourceCandidate.path, rootCandidate.path, lookupHref);\n let ambiguousSuffixMatches = [];\n let suffixKey = suffixKeys[0] ?? '';\n let eligibleSuffixMatches = [];\n for (const key of suffixKeys) {\n if (!canUseSingleSegmentSuffix(input.referenceKind) && !key.includes('/')) {\n continue;\n }\n const suffixMatches = uniqueSorted(input.fileIndex.pathsBySuffix.get(lookupKey(key)) ?? []);\n const eligibleMatches = filterManifestEvidence(suffixMatches, input);\n if (eligibleMatches.length === 1) {\n suffixKey = key;\n eligibleSuffixMatches = eligibleMatches;\n break;\n }\n if (eligibleMatches.length > 1 && ambiguousSuffixMatches.length === 0) {\n suffixKey = key;\n ambiguousSuffixMatches = eligibleMatches;\n }\n }\n if (eligibleSuffixMatches.length === 1) {\n return resolved(rawHref, lookupHref, split.queryAndFragment, eligibleSuffixMatches[0], 'unique-suffix', true, diagnostics);\n }\n if (ambiguousSuffixMatches.length > 1) {\n return ambiguous(rawHref, lookupHref, split.queryAndFragment, input.sourcePath, ambiguousSuffixMatches);\n }\n if (!canUseBasenameHeuristic(input.referenceKind, heuristics)) {\n return missing(rawHref, lookupHref, split.queryAndFragment, input.sourcePath, diagnostics);\n }\n const basename = basenameOf(suffixKey);\n const basenameMatches = uniqueSorted(input.fileIndex.pathsByBasename.get(lookupKey(basename)) ?? []);\n if (basenameMatches.length === 1) {\n return resolved(rawHref, lookupHref, split.queryAndFragment, basenameMatches[0], 'unique-basename', true, diagnostics);\n }\n if (basenameMatches.length > 1) {\n return ambiguous(rawHref, lookupHref, split.queryAndFragment, input.sourcePath, basenameMatches);\n }\n return missing(rawHref, lookupHref, split.queryAndFragment, input.sourcePath, diagnostics);\n}\nfunction exactMatch(fileIndex, path) {\n return path && fileIndex.exactPaths.has(path) ? path : null;\n}\nfunction resolved(rawHref, lookupHref, queryAndFragment, resolvedPath, strategy, heuristic, diagnostics) {\n return {\n status: 'resolved',\n rawHref,\n lookupHref,\n renderHref: `${resolvedPath}${queryAndFragment}`,\n resolvedPath,\n strategy,\n heuristic,\n queryAndFragment,\n diagnostics,\n };\n}\nfunction missing(rawHref, lookupHref, queryAndFragment, sourcePath, diagnostics) {\n return {\n status: 'missing',\n rawHref,\n lookupHref,\n queryAndFragment,\n diagnostics: diagnostics.length > 0\n ? diagnostics\n : [\n {\n severity: 'warning',\n code: 'IMS_CP_REFERENCE_MISSING',\n message: `Package reference could not be resolved: ${lookupHref}.`,\n sourcePath,\n reference: rawHref,\n },\n ],\n };\n}\nfunction ambiguous(rawHref, lookupHref, queryAndFragment, sourcePath, candidatePaths) {\n return {\n status: 'ambiguous',\n rawHref,\n lookupHref,\n queryAndFragment,\n candidatePaths,\n diagnostics: [\n {\n severity: 'warning',\n code: 'IMS_CP_REFERENCE_AMBIGUOUS',\n message: `Package reference is ambiguous: ${lookupHref} matched ${candidatePaths.length} files.`,\n sourcePath,\n reference: rawHref,\n candidatePaths: [...candidatePaths],\n },\n ],\n };\n}\nfunction unsafeResolution(rawHref, lookupHref, queryAndFragment, sourcePath) {\n return {\n status: 'unsafe',\n rawHref,\n lookupHref,\n queryAndFragment,\n diagnostics: [\n {\n severity: 'error',\n code: 'IMS_CP_REFERENCE_UNSAFE',\n message: `Package reference escapes the package root or uses an absolute package path: ${lookupHref}.`,\n sourcePath,\n reference: rawHref,\n },\n ],\n };\n}\nfunction splitLookupHref(rawHref) {\n const queryIndex = rawHref.indexOf('?');\n const fragmentIndex = rawHref.indexOf('#');\n const indexes = [queryIndex, fragmentIndex].filter((index) => index >= 0);\n if (indexes.length === 0) {\n return { lookupHref: rawHref, queryAndFragment: '' };\n }\n const splitIndex = Math.min(...indexes);\n return {\n lookupHref: rawHref.slice(0, splitIndex),\n queryAndFragment: rawHref.slice(splitIndex),\n };\n}\nfunction isExternalHref(href) {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(href);\n}\nfunction hasUnsafeEncodedPathToken(href) {\n let current = href;\n for (let i = 0; i < 3; i += 1) {\n if (/%(?:2e|2f|5c)/i.test(current)) {\n return true;\n }\n const decoded = safeDecodeURIComponent(current);\n if (decoded === current) {\n return false;\n }\n current = decoded;\n }\n return /%(?:2e|2f|5c)/i.test(current);\n}\nfunction safeDecodeURIComponent(value) {\n try {\n return decodeURIComponent(value);\n }\n catch {\n return value;\n }\n}\nfunction normalizePackagePath(basePath, href) {\n const raw = href.replaceAll('\\\\', '/').trim();\n if (!raw || raw.startsWith('/')) {\n return { path: '', unsafe: raw.startsWith('/') };\n }\n const parts = [...(basePath ? basePath.replaceAll('\\\\', '/').split('/') : []), ...raw.split('/')];\n const normalized = [];\n for (const part of parts) {\n if (!part || part === '.')\n continue;\n if (part === '..') {\n if (normalized.length === 0) {\n return { path: '', unsafe: true };\n }\n normalized.pop();\n continue;\n }\n normalized.push(part);\n }\n return { path: normalized.join('/'), unsafe: false };\n}\nfunction suffixLookupKeys(sourceCandidate, rootCandidate, lookupHref) {\n return uniqueStrings([\n rootCandidate,\n normalizePackagePath('', lookupHref).path,\n sourceCandidate,\n lookupHref.replaceAll('\\\\', '/').replace(/^\\/+/, ''),\n ].filter(Boolean));\n}\nfunction canUseBasenameHeuristic(referenceKind, heuristics) {\n if (!heuristics.lenientAssetBasenames)\n return false;\n return referenceKind === 'media-asset';\n}\nfunction canUseSingleSegmentSuffix(referenceKind) {\n return referenceKind === 'media-asset';\n}\nfunction filterManifestEvidence(matches, input) {\n if (input.referenceKind !== 'source-xml' && input.referenceKind !== 'assessment-item-ref') {\n return matches;\n }\n const evidence = input.manifestEvidencePaths;\n if (!evidence)\n return [];\n return matches.filter((match) => evidence.has(match));\n}\nfunction addSuffixes(index, path) {\n const parts = path.split('/');\n for (let partIndex = 0; partIndex < parts.length; partIndex += 1) {\n const suffix = parts.slice(partIndex).join('/');\n if (suffix) {\n mapArrayFor(index, lookupKey(suffix)).push(path);\n }\n }\n}\nfunction lookupKey(value) {\n return value.toLowerCase();\n}\nfunction mapArrayFor(map, key) {\n const existing = map.get(key);\n if (existing)\n return existing;\n const next = [];\n map.set(key, next);\n return next;\n}\nfunction basenameOf(path) {\n const index = path.lastIndexOf('/');\n return index === -1 ? path : path.slice(index + 1);\n}\nfunction dirname(path) {\n const normalized = path.replaceAll('\\\\', '/');\n const index = normalized.lastIndexOf('/');\n return index === -1 ? '' : normalized.slice(0, index);\n}\nfunction uniqueSorted(values) {\n return [...new Set(values)].sort((left, right) => left.localeCompare(right));\n}\nfunction uniqueStrings(values) {\n return [...new Set(values)];\n}\n//# sourceMappingURL=package-file-resolver.js.map","import { parse } from 'node-html-parser';\nimport { resolvePackageReference, } from './package-file-resolver.js';\nimport { isPackageRelativeHref, resolveCheckedPackagePathFromFile, resolvePackagePathFromFile, } from './package-path.js';\nimport { isBlockedStylesheetCss, parseSrcsetCandidates } from './security-parsing.js';\nconst STIMULUS_REF_TAGS = new Set(['assessmentstimulusref']);\nconst ASSESSMENT_STIMULUS_TAGS = new Set(['assessmentstimulus']);\nconst STIMULUS_BODY_TAGS = new Set(['stimulusbody']);\nconst STYLESHEET_TAGS = new Set(['stylesheet']);\nconst CATALOG_INFO_TAGS = new Set(['cataloginfo']);\nexport function extractAssessmentStimulusRefs(itemXml) {\n const refs = [];\n for (const el of findElements(parseXml(itemXml), STIMULUS_REF_TAGS)) {\n const identifier = readAttr(el, 'identifier');\n const href = readAttr(el, 'href');\n if (!identifier || !href)\n continue;\n refs.push({\n identifier,\n href,\n title: readAttr(el, 'title') ?? undefined,\n });\n }\n return refs;\n}\nexport function parseAssessmentStimulusXml(stimulusXml) {\n const root = parseXml(stimulusXml);\n const stimulus = findElements(root, ASSESSMENT_STIMULUS_TAGS)[0];\n const validationMessages = [];\n if (!stimulus) {\n validationMessages.push('Expected one qti-assessment-stimulus root element.');\n return { bodyHtml: '', stylesheets: [], validationMessages };\n }\n const bodyElements = directChildElements(stimulus).filter((child) => STIMULUS_BODY_TAGS.has(normalizeTag(child.tagName)));\n const catalogElements = directChildElements(stimulus).filter((child) => CATALOG_INFO_TAGS.has(normalizeTag(child.tagName)));\n const stylesheets = directChildElements(stimulus)\n .filter((child) => STYLESHEET_TAGS.has(normalizeTag(child.tagName)))\n .map(toStylesheetRef)\n .filter((style) => Boolean(style));\n if (bodyElements.length !== 1) {\n validationMessages.push('Expected exactly one qti-stimulus-body child element.');\n }\n if (catalogElements.length > 1) {\n validationMessages.push('Expected at most one qti-catalog-info child element.');\n }\n validateStimulusChildOrder(stimulus, validationMessages);\n return {\n identifier: readAttr(stimulus, 'identifier') ?? undefined,\n title: readAttr(stimulus, 'title') ?? undefined,\n lang: readAttr(stimulus, 'xml:lang') ?? readAttr(stimulus, 'lang') ?? undefined,\n bodyHtml: bodyElements[0] ? serializeChildren(bodyElements[0]).trim() : '',\n stylesheets,\n catalogInfoXml: catalogElements[0]?.toString(),\n validationMessages,\n };\n}\nexport function extractStimulusBodyHtml(stimulusXml) {\n return parseAssessmentStimulusXml(stimulusXml).bodyHtml;\n}\nexport function createResolvedItemDeliveryContext(options) {\n const itemHref = options.itemHref ?? '';\n const resolverContext = {\n fileIndex: options.fileIndex,\n manifestEvidencePaths: options.manifestEvidencePaths,\n heuristicsConfig: options.heuristicsConfig,\n };\n const validationMessages = [];\n const stimuli = {};\n const catalogSources = [];\n const stylesheets = resolveStylesheetRefs(extractQtiStylesheets(options.itemXml), itemHref, 'item', validationMessages, options.readText, undefined, resolverContext);\n for (const itemCatalogXml of extractCatalogInfoXml(options.itemXml)) {\n catalogSources.push({\n scope: 'item',\n xml: resolveCatalogFileHrefs(itemCatalogXml, itemHref, validationMessages, resolverContext),\n baseHref: itemHref,\n });\n }\n for (const ref of extractAssessmentStimulusRefs(options.itemXml)) {\n const resolvedHref = resolvePackageHref(itemHref, ref.href, validationMessages, `Stimulus ${ref.identifier}`, 'source-xml', resolverContext);\n if (!resolvedHref)\n continue;\n const stimulusXml = options.readText(resolvedHref);\n if (!stimulusXml) {\n validationMessages.push(`Stimulus file not found: ${resolvedHref}.`);\n continue;\n }\n const parsed = parseAssessmentStimulusXml(stimulusXml);\n const stimulusMessages = parsed.validationMessages.map((message) => `${ref.identifier}: ${message}`);\n validationMessages.push(...stimulusMessages);\n const bodyHtml = options.resolveAssetUrl\n ? rewriteHtmlAssetRefs(parsed.bodyHtml, resolvedHref, options.resolveAssetUrl, validationMessages, resolverContext)\n : parsed.bodyHtml;\n const stimulusStylesheets = resolveStylesheetRefs(parsed.stylesheets, resolvedHref, 'stimulus', validationMessages, options.readText, ref.identifier, resolverContext);\n const catalogSource = parsed.catalogInfoXml\n ? {\n scope: 'stimulus',\n xml: resolveCatalogFileHrefs(parsed.catalogInfoXml, resolvedHref, validationMessages, resolverContext),\n baseHref: resolvedHref,\n stimulusIdentifier: ref.identifier,\n }\n : undefined;\n if (catalogSource) {\n catalogSources.push(catalogSource);\n }\n stylesheets.push(...stimulusStylesheets);\n stimuli[ref.identifier] = {\n identifier: ref.identifier,\n href: ref.href,\n resolvedHref,\n title: ref.title ?? parsed.title,\n lang: parsed.lang,\n bodyHtml,\n stylesheets: stimulusStylesheets,\n catalogSource,\n validationMessages: stimulusMessages,\n };\n }\n return {\n itemHref: options.itemHref,\n stimuli,\n stylesheets,\n catalogSources,\n validationMessages,\n };\n}\nexport function extractQtiStylesheets(xml) {\n return findElements(parseXml(xml), STYLESHEET_TAGS)\n .map(toStylesheetRef)\n .filter((style) => Boolean(style));\n}\nexport function extractCatalogInfoXml(xml) {\n return findElements(parseXml(xml), CATALOG_INFO_TAGS).map((el) => el.toString());\n}\nexport function resolveRelativePath(baseHref, relativePath) {\n return resolvePackagePathFromFile(baseHref, relativePath);\n}\nfunction resolveCheckedPackagePath(baseHref, href) {\n if (!isPackageRelativeHref(href))\n return null;\n return resolveCheckedPackagePathFromFile(baseHref, href);\n}\nfunction resolvePackageHref(baseHref, href, validationMessages, label, referenceKind = 'source-xml', resolverContext) {\n if (resolverContext?.fileIndex) {\n const resolution = resolvePackageReference({\n fileIndex: resolverContext.fileIndex,\n sourcePath: baseHref,\n rawHref: href,\n referenceKind,\n manifestEvidencePaths: resolverContext.manifestEvidencePaths,\n heuristicsConfig: resolverContext.heuristicsConfig,\n });\n if (resolution.status === 'resolved') {\n return resolution.resolvedPath;\n }\n if (resolution.status === 'unsafe') {\n validationMessages.push(`${label} href escapes the package root: ${href}.`);\n return null;\n }\n if (resolution.status === 'ambiguous') {\n validationMessages.push(`${label} href is ambiguous: ${href}.`);\n return null;\n }\n if (resolution.status === 'missing') {\n validationMessages.push(`${label} file not found: ${href}.`);\n return null;\n }\n if ((referenceKind === 'media-asset' || referenceKind === 'catalog-file') && isPolicyHandledExternalHref(href)) {\n return href;\n }\n validationMessages.push(`${label} href is not a package-relative path: ${href}.`);\n return null;\n }\n if (!isPackageRelativeHref(href)) {\n if ((referenceKind === 'media-asset' || referenceKind === 'catalog-file') && isPolicyHandledExternalHref(href)) {\n return href;\n }\n validationMessages.push(`${label} href is not a package-relative path: ${href}.`);\n return null;\n }\n const resolved = resolveCheckedPackagePath(baseHref, href);\n if (!resolved) {\n validationMessages.push(`${label} href escapes the package root: ${href}.`);\n return null;\n }\n return resolved;\n}\nfunction isPolicyHandledExternalHref(href) {\n return /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i.test(href.trim());\n}\nfunction resolveStylesheetRefs(stylesheets, baseHref, source, validationMessages, readText, stimulusIdentifier, resolverContext) {\n const resolved = [];\n for (const style of stylesheets) {\n const resolvedHref = resolvePackageHref(baseHref, style.href, validationMessages, `${source === 'item' ? 'Item' : `Stimulus ${stimulusIdentifier ?? ''}`} stylesheet`, 'stylesheet', resolverContext);\n if (!resolvedHref)\n continue;\n const cssText = readText ? readText(resolvedHref) : undefined;\n const safeCssText = cssText === undefined || cssText === null\n ? undefined\n : sanitizeStylesheetCss(cssText, validationMessages, resolvedHref);\n resolved.push({\n ...style,\n resolvedHref,\n source,\n stimulusIdentifier,\n ...(safeCssText ? { cssText: safeCssText } : {}),\n });\n }\n return resolved;\n}\nfunction sanitizeStylesheetCss(css, validationMessages, resolvedHref) {\n if (!css.trim())\n return '';\n if (isBlockedStylesheetCss(css)) {\n validationMessages.push(`Stylesheet blocked by policy: ${resolvedHref}.`);\n return null;\n }\n return css;\n}\nfunction rewriteHtmlAssetRefs(html, baseHref, resolveAssetUrl, validationMessages, resolverContext) {\n if (!html.trim())\n return html;\n const root = parse(`<root>${html}</root>`, {\n comment: false,\n lowerCaseTagName: false,\n });\n const wrapper = root.querySelector('root') ?? root;\n for (const el of findElements(wrapper, new Set(['img', 'audio', 'video', 'source', 'track', 'object', 'embed', 'a']))) {\n for (const attr of ['src', 'href', 'data', 'poster']) {\n const raw = readAttr(el, attr);\n if (!raw || raw.trim().startsWith('#'))\n continue;\n if (isPolicyHandledExternalHref(raw))\n continue;\n const resolvedPath = resolvePackageHref(baseHref, raw, validationMessages, `Stimulus asset ${attr}`, 'media-asset', resolverContext);\n if (!resolvedPath) {\n el.removeAttribute(attr);\n continue;\n }\n const resolvedUrl = resolveAssetUrl(resolvedPath);\n if (resolvedUrl) {\n el.setAttribute(attr, resolvedUrl);\n }\n else {\n el.removeAttribute(attr);\n }\n }\n const srcset = readAttr(el, 'srcset');\n if (srcset) {\n const rewritten = rewriteSrcset(srcset, baseHref, resolveAssetUrl, validationMessages, resolverContext);\n if (rewritten)\n el.setAttribute('srcset', rewritten);\n else\n el.removeAttribute('srcset');\n }\n }\n return serializeChildren(wrapper);\n}\nfunction rewriteSrcset(value, baseHref, resolveAssetUrl, validationMessages, resolverContext) {\n const rewritten = [];\n for (const candidate of parseSrcsetCandidates(value)) {\n if (isPolicyHandledExternalHref(candidate.url)) {\n rewritten.push(candidate.raw);\n continue;\n }\n const resolvedPath = resolvePackageHref(baseHref, candidate.url, validationMessages, 'Stimulus asset srcset', 'media-asset', resolverContext);\n if (!resolvedPath)\n return null;\n const resolvedUrl = resolveAssetUrl(resolvedPath);\n if (!resolvedUrl)\n return null;\n rewritten.push([resolvedUrl, candidate.descriptors].filter(Boolean).join(' '));\n }\n return rewritten.length > 0 ? rewritten.join(', ') : null;\n}\nfunction resolveCatalogFileHrefs(xml, baseHref, validationMessages, resolverContext) {\n if (!xml.trim())\n return xml;\n const root = parse(`<root>${xml}</root>`, {\n comment: false,\n lowerCaseTagName: false,\n });\n const wrapper = root.querySelector('root') ?? root;\n for (const fileHref of findElements(wrapper, new Set(['filehref']))) {\n const raw = readAttr(fileHref, 'src') ?? fileHref.text?.trim() ?? '';\n const resolvedPath = resolvePackageHref(baseHref, raw, validationMessages, 'Catalog file', 'catalog-file', resolverContext);\n if (resolvedPath) {\n fileHref.setAttribute('src', resolvedPath);\n }\n else {\n fileHref.removeAttribute('src');\n }\n clearElementContent(fileHref);\n }\n return serializeChildren(wrapper);\n}\nfunction clearElementContent(el) {\n const mutable = el;\n if (typeof mutable.set_content === 'function') {\n mutable.set_content('');\n return;\n }\n mutable.innerHTML = '';\n mutable.textContent = '';\n}\nfunction parseXml(xml) {\n return parse(xml, {\n comment: false,\n lowerCaseTagName: false,\n });\n}\nfunction findElements(root, normalizedTags) {\n const matches = [];\n visit(root, (node) => {\n if (normalizedTags.has(normalizeTag(node.tagName))) {\n matches.push(node);\n }\n });\n return matches;\n}\nfunction visit(node, callback) {\n if (isElement(node)) {\n callback(node);\n }\n for (const child of node.childNodes ?? []) {\n visit(child, callback);\n }\n}\nfunction directChildElements(el) {\n return (el.childNodes ?? []).filter(isElement);\n}\nfunction isElement(node) {\n return typeof node.tagName === 'string';\n}\nfunction normalizeTag(tagName) {\n return tagName.toLowerCase().replace(/^qti-/, '').replace(/-([a-z])/g, (_match, char) => char);\n}\nfunction readAttr(el, name) {\n const direct = el.getAttribute(name);\n if (direct !== undefined)\n return direct;\n const kebabName = name.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n const kebab = el.getAttribute(kebabName);\n return kebab === undefined ? null : kebab;\n}\nfunction serializeChildren(el) {\n return (el.childNodes ?? []).map((child) => child.toString()).join('');\n}\nfunction toStylesheetRef(el) {\n const href = readAttr(el, 'href');\n if (!href)\n return null;\n return {\n href,\n type: readAttr(el, 'type') ?? undefined,\n media: readAttr(el, 'media') ?? undefined,\n xml: el.toString(),\n };\n}\nfunction validateStimulusChildOrder(stimulus, validationMessages) {\n let seenBody = false;\n let seenCatalog = false;\n for (const child of directChildElements(stimulus)) {\n const tag = normalizeTag(child.tagName);\n if (STYLESHEET_TAGS.has(tag)) {\n if (seenBody || seenCatalog) {\n validationMessages.push('qti-stylesheet must precede qti-stimulus-body and qti-catalog-info.');\n }\n continue;\n }\n if (STIMULUS_BODY_TAGS.has(tag)) {\n if (seenCatalog) {\n validationMessages.push('qti-stimulus-body must precede qti-catalog-info.');\n }\n seenBody = true;\n continue;\n }\n if (CATALOG_INFO_TAGS.has(tag)) {\n seenCatalog = true;\n continue;\n }\n validationMessages.push(`Unexpected qti-assessment-stimulus child element: ${child.tagName}.`);\n }\n}\n//# sourceMappingURL=qti3-shared-content.js.map","const DEFAULTS = {\n rejectDoctype: true,\n maxItemXmlBytes: 10000000,\n maxHtmlBytes: 5000000,\n maxHtmlNodes: 200000,\n maxHtmlDepth: 200,\n};\nfunction getByteLengthUtf8(s) {\n // TextEncoder is available in modern runtimes (browser + Bun/node 20+).\n // Fall back to a conservative approximation if unavailable.\n const TE = globalThis.TextEncoder;\n if (!TE)\n return s.length * 2;\n return new TE().encode(s).byteLength;\n}\nexport function normalizeParsingLimits(security) {\n const cfg = security?.parsingLimits;\n const enabled = cfg?.enabled === true;\n if (!enabled) {\n return { enabled: false, ...DEFAULTS };\n }\n return {\n enabled: true,\n rejectDoctype: cfg?.rejectDoctype ?? DEFAULTS.rejectDoctype,\n maxItemXmlBytes: cfg?.maxItemXmlBytes ?? DEFAULTS.maxItemXmlBytes,\n maxHtmlBytes: cfg?.maxHtmlBytes ?? DEFAULTS.maxHtmlBytes,\n maxHtmlNodes: cfg?.maxHtmlNodes ?? DEFAULTS.maxHtmlNodes,\n maxHtmlDepth: cfg?.maxHtmlDepth ?? DEFAULTS.maxHtmlDepth,\n };\n}\nexport function enforceItemXmlLimits(itemXml, security) {\n const limits = normalizeParsingLimits(security);\n if (!limits.enabled)\n return;\n const bytes = getByteLengthUtf8(String(itemXml ?? ''));\n if (bytes > limits.maxItemXmlBytes) {\n throw new Error(`itemXml exceeds maxItemXmlBytes (${bytes} > ${limits.maxItemXmlBytes})`);\n }\n if (limits.rejectDoctype) {\n // Case-insensitive and tolerant of whitespace: \"<!DOCTYPE\"\n if (/<!\\s*doctype/i.test(itemXml)) {\n throw new Error('itemXml contains <!DOCTYPE>, which is rejected by parsingLimits');\n }\n }\n}\n//# sourceMappingURL=parsingLimits.js.map","/**\n * HTML Sanitizer for QTI Content\n *\n * Removes dangerous HTML/scripts while preserving safe educational content.\n * Protects against XSS attacks via:\n * - Script tags\n * - Event handlers (onclick, onerror, onload, etc.)\n * - Dangerous protocols (javascript:, data:text/html)\n * - Unsafe iframe/object sources\n */\nimport { parse } from 'node-html-parser';\nimport { isBlockedStylesheetCss, normalizeCssForPolicy, parseSrcsetCandidates, } from '@pie-qti/ims-cp-core';\nimport { Qti3ElementNameMapper } from '@pie-qti/qti-common';\nimport { normalizeParsingLimits } from './parsingLimits.js';\nimport { sanitizeResourceUrl } from './urlPolicy.js';\nclass HtmlLimitExceeded extends Error {\n constructor(message) {\n super(message);\n }\n}\nfunction policyFromOptions(options) {\n return options?.security?.urlPolicy;\n}\nfunction allowObjectEmbeds(options) {\n return options?.security?.allowObjectEmbeds === true;\n}\nfunction allowIframes(options) {\n return options?.security?.allowIframes === true;\n}\nfunction escapeAttr(value) {\n return value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\nfunction getOptionalAttr(element, attrName) {\n const value = element.getAttribute(attrName);\n return value ? ` ${attrName}=\"${escapeAttr(value)}\"` : '';\n}\nfunction sanitizeUrlForHtml(value, options, kind) {\n const policy = policyFromOptions(options);\n const sanitized = sanitizeResourceUrl(value, policy, kind);\n if (!sanitized)\n return null;\n if (!options?.sanitizeUrl)\n return sanitized;\n const hostSanitized = options.sanitizeUrl(sanitized, kind);\n if (!hostSanitized)\n return null;\n return sanitizeResourceUrl(hostSanitized, policy, kind);\n}\nfunction sanitizeUrlAttr(value, options, kind) {\n return sanitizeUrlForHtml(value, options, kind) ?? '#';\n}\nfunction sanitizeSrcset(value, options) {\n const out = [];\n for (const candidate of parseSrcsetCandidates(value)) {\n const sanitized = sanitizeUrlForHtml(candidate.url, options, 'img');\n if (!sanitized)\n continue;\n out.push([sanitized, candidate.descriptors].filter(Boolean).join(' '));\n }\n return out.join(', ');\n}\nfunction isBlockedInlineStyle(css) {\n if (isBlockedStylesheetCss(css))\n return true;\n const normalized = normalizeCssForPolicy(css);\n for (const match of normalized.matchAll(/(?:^|;)position:([^;]*)/gi)) {\n const value = (match[1] ?? '').replace(/!important$/i, '');\n // Keep the small set of literal values needed by authored QTI layouts.\n // CSS variables, vendor values, and CSS-wide inheritance keywords can all\n // resolve to fixed/sticky positioning after this static policy pass.\n if (!/^(?:static|relative|absolute)$/i.test(value))\n return true;\n }\n return false;\n}\nconst qti3ElementNameMapper = new Qti3ElementNameMapper();\nfunction isKnownQti3Element(tagName) {\n if (!tagName.startsWith('qti-'))\n return false;\n const canonical = qti3ElementNameMapper.toCanonical(tagName);\n return qti3ElementNameMapper.toNative(canonical) === tagName;\n}\nconst SVG_RESOURCE_ATTRIBUTES = new Set([\n 'clip-path',\n 'color-profile',\n 'cursor',\n 'fill',\n 'filter',\n 'marker',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'mask',\n 'stroke',\n]);\n// SVG SMIL elements can mutate href and other URL-bearing attributes after the\n// static attribute pass has completed. Removing the active animation vocabulary\n// is the only robust same-DOM policy across browser-specific SMIL recovery rules.\nconst ACTIVE_SVG_ELEMENTS = new Set([\n 'animate',\n 'animatecolor',\n 'animatemotion',\n 'animatetransform',\n 'discard',\n 'set',\n]);\nfunction hasBlockedSvgResourceUrl(value) {\n const normalized = normalizeCssForPolicy(value);\n if (!/url\\(/i.test(normalized))\n return false;\n let foundUrl = false;\n let blocked = false;\n const remainder = normalized.replace(/url\\(([^)]*)\\)/gi, (_match, rawUrl) => {\n foundUrl = true;\n const unquoted = rawUrl.replace(/^(['\"])(.*)\\1$/, '$2');\n if (!/^#[^'\"()\\s]+$/.test(unquoted))\n blocked = true;\n return '';\n });\n // Malformed/nested url() syntax is safer to drop than to let the browser\n // recover it differently from this policy parser.\n return blocked || !foundUrl || /url\\(/i.test(remainder);\n}\n/** Whether an element sits inside an `<svg>` subtree, where SMIL animation applies. */\nfunction isInsideSvg(element) {\n let ancestor = element.parentNode;\n while (ancestor) {\n if (ancestor.rawTagName?.toLowerCase() === 'svg') {\n return true;\n }\n ancestor = ancestor.parentNode;\n }\n return false;\n}\n/** Drop an element from the tree while keeping its sanitized child content. */\nfunction unwrapElement(element, options, limitsState, depth) {\n const children = [...element.childNodes];\n for (const child of children) {\n if (child.rawTagName) {\n sanitizeElement(child, options, limitsState, depth + 1);\n }\n }\n // Re-read childNodes because sanitization may have removed or replaced\n // entries from the original snapshot.\n element.replaceWith(...element.childNodes);\n}\n/**\n * Recursively sanitize an HTML element and its children\n */\nfunction sanitizeElement(element, options, limitsState, depth) {\n if (limitsState.enabled) {\n if (depth > limitsState.maxDepth) {\n throw new HtmlLimitExceeded(`HTML depth exceeds maxHtmlDepth (${depth} > ${limitsState.maxDepth})`);\n }\n limitsState.nodes++;\n if (limitsState.nodes > limitsState.maxNodes) {\n throw new HtmlLimitExceeded(`HTML node count exceeds maxHtmlNodes (${limitsState.nodes} > ${limitsState.maxNodes})`);\n }\n }\n const tagName = element.rawTagName?.toLowerCase();\n // Remove script tags entirely\n if (tagName === 'script') {\n element.remove();\n return;\n }\n // The SMIL vocabulary only animates inside an `<svg>` subtree, so that is where\n // the removal policy applies. The same tag names in item HTML are inert unknown\n // elements — `<set>` reaches real content as a wrapper in ExamView-style QTI 2.1\n // exports — and removing them there destroys readable stem text for no gain.\n if (tagName && ACTIVE_SVG_ELEMENTS.has(tagName)) {\n if (isInsideSvg(element)) {\n element.remove();\n return;\n }\n unwrapElement(element, options, limitsState, depth);\n return;\n }\n // Remove high-risk elements by default (same-DOM embedding).\n if (tagName === 'iframe' && !allowIframes(options)) {\n element.remove();\n return;\n }\n if ((tagName === 'object' || tagName === 'embed') && !allowObjectEmbeds(options)) {\n const replacementHtml = getSafeObjectReplacementHtml(element, options);\n if (replacementHtml) {\n element.replaceWith(replacementHtml);\n return;\n }\n element.remove();\n return;\n }\n if (tagName === 'base' || tagName === 'meta' || tagName === 'link' || tagName === 'style' || tagName === 'foreignobject') {\n element.remove();\n return;\n }\n // Only the closed QTI 3 vocabulary may retain a custom-element-shaped name.\n // A prefix check alone would let assessment content invoke any host-registered\n // `qti-*` lifecycle hook. Other hyphenated elements are unwrapped while their\n // already-sanitized readable child content is preserved.\n if (tagName?.includes('-') && !isKnownQti3Element(tagName)) {\n unwrapElement(element, options, limitsState, depth);\n return;\n }\n // Remove dangerous event handler attributes (case-insensitive).\n const attrs = element.attributes || {};\n for (const attrName of Object.keys(attrs)) {\n if (attrName.toLowerCase().startsWith('on')) {\n element.removeAttribute(attrName);\n }\n }\n // Sanitize URL attributes\n for (const attrName of Object.keys(attrs)) {\n const lower = attrName.toLowerCase();\n const value = element.getAttribute(attrName);\n if (!value)\n continue;\n // Block srcdoc everywhere (HTML document string).\n if (lower === 'srcdoc') {\n element.removeAttribute(attrName);\n continue;\n }\n // The ping attribute is a space-separated tracking endpoint list. It is\n // not needed for QTI content and should never cause assessment-authored\n // background requests when a candidate follows a link.\n if (lower === 'ping') {\n element.removeAttribute(attrName);\n continue;\n }\n // Customized built-in elements (`<button is=\"x-widget\">`) can execute the\n // same host-registered lifecycle code as autonomous custom elements.\n if (lower === 'is') {\n element.removeAttribute(attrName);\n continue;\n }\n // Inline CSS is allowed for QTI presentation, but CSS resource functions\n // must not bypass the URL policy or trigger external tracking requests.\n if (lower === 'style' && isBlockedInlineStyle(value)) {\n element.removeAttribute(attrName);\n continue;\n }\n if (lower === 'srcset') {\n const sanitized = sanitizeSrcset(value, options);\n if (!sanitized)\n element.removeAttribute(attrName);\n else if (sanitized !== value)\n element.setAttribute(attrName, sanitized);\n continue;\n }\n // SVG presentation attributes can load external paint servers, filters,\n // masks, markers, and cursors via CSS url(). Preserve document-local\n // fragment references while removing network-capable forms.\n if (SVG_RESOURCE_ATTRIBUTES.has(lower) && hasBlockedSvgResourceUrl(value)) {\n element.removeAttribute(attrName);\n continue;\n }\n // Deprecated HTML background attributes are still fetched by browsers.\n if (lower === 'background') {\n const sanitized = sanitizeUrlForHtml(value, options, 'img');\n if (!sanitized)\n element.removeAttribute(attrName);\n else if (sanitized !== value)\n element.setAttribute(attrName, sanitized);\n continue;\n }\n // URL-bearing attributes (include SVG xlink:href).\n if (lower === 'href' ||\n lower === 'xlink:href' ||\n lower === 'src' ||\n lower === 'data' ||\n lower === 'action' ||\n lower === 'formaction' ||\n lower === 'poster') {\n const kind = tagName === 'img' ? 'img' :\n tagName === 'audio' || tagName === 'video' || tagName === 'source' ? 'media' :\n tagName === 'object' || tagName === 'embed' ? 'object' :\n tagName === 'a' ? 'link' :\n 'any';\n const sanitized = sanitizeUrlAttr(value, options, kind);\n if (sanitized !== value)\n element.setAttribute(attrName, sanitized);\n }\n }\n // Recursively sanitize children\n const children = element.childNodes.filter((n) => n.rawTagName);\n for (const child of children) {\n sanitizeElement(child, options, limitsState, depth + 1);\n }\n}\n/**\n * Sanitize HTML string by removing XSS vectors\n *\n * @param html - HTML string to sanitize\n * @returns Sanitized HTML string safe for rendering\n */\nexport function sanitizeHtml(html, options) {\n if (!html || typeof html !== 'string') {\n return '';\n }\n try {\n const limits = normalizeParsingLimits(options?.security);\n if (limits.enabled) {\n const TE = globalThis.TextEncoder;\n const bytes = TE ? new TE().encode(html).byteLength : html.length * 2;\n if (bytes > limits.maxHtmlBytes) {\n return '';\n }\n }\n // Parse HTML\n const root = parse(html, {\n comment: false, // Remove comments (potential XSS vector)\n });\n // Sanitize all elements\n const elements = root.childNodes.filter((n) => n.rawTagName);\n const limitsState = {\n enabled: limits.enabled,\n nodes: 0,\n maxNodes: limits.maxHtmlNodes,\n maxDepth: limits.maxHtmlDepth,\n };\n for (const element of elements) {\n sanitizeElement(element, options, limitsState, 1);\n }\n // Return sanitized HTML\n return root.toString();\n }\n catch (error) {\n if (error instanceof HtmlLimitExceeded) {\n return '';\n }\n // If parsing fails, return empty string (safer than returning potentially malicious content)\n console.error('HTML sanitization failed:', error);\n return '';\n }\n}\n/**\n * Sanitize text content in choice labels, prompts, etc.\n * This is for content that gets serialized to JSON and displayed in UI.\n *\n * @param text - Text content that may contain HTML\n * @returns Sanitized text\n */\nexport function sanitizeTextContent(text, options) {\n if (!text || typeof text !== 'string') {\n return '';\n }\n // If it looks like HTML (contains tags), sanitize it\n if (/<[^>]+>/.test(text)) {\n return sanitizeHtml(text, options);\n }\n // Plain text - return as-is\n return text;\n}\nfunction getSafeObjectReplacementHtml(element, options) {\n if (element.rawTagName?.toLowerCase() !== 'object') {\n return null;\n }\n const rawType = element.getAttribute('type')?.trim().toLowerCase() ?? '';\n const rawData = element.getAttribute('data')?.trim() ?? '';\n if (!rawType || !rawData) {\n return null;\n }\n const dimensions = `${getOptionalAttr(element, 'width')}${getOptionalAttr(element, 'height')}`;\n const classes = getOptionalAttr(element, 'class');\n const id = getOptionalAttr(element, 'id');\n if (rawType.startsWith('image/')) {\n const src = sanitizeUrlForHtml(rawData, options, 'img');\n if (!src) {\n return null;\n }\n const alt = element.getAttribute('aria-label') ??\n element.getAttribute('title') ??\n element.textContent?.trim() ??\n '';\n return `<img src=\"${escapeAttr(src)}\" alt=\"${escapeAttr(alt)}\"${dimensions}${classes}${id}>`;\n }\n if (rawType.startsWith('audio/')) {\n const src = sanitizeUrlForHtml(rawData, options, 'media');\n if (!src) {\n return null;\n }\n return `<audio controls${classes}${id}><source src=\"${escapeAttr(src)}\" type=\"${escapeAttr(rawType)}\"></audio>`;\n }\n if (rawType.startsWith('video/')) {\n const src = sanitizeUrlForHtml(rawData, options, 'media');\n if (!src) {\n return null;\n }\n const rawPoster = element.getAttribute('poster')?.trim() ?? '';\n const poster = rawPoster\n ? sanitizeUrlForHtml(rawPoster, options, 'img')\n : null;\n const posterAttr = poster ? ` poster=\"${escapeAttr(poster)}\"` : '';\n return `<video controls${dimensions}${classes}${id}${posterAttr}><source src=\"${escapeAttr(src)}\" type=\"${escapeAttr(rawType)}\"></video>`;\n }\n return null;\n}\n//# sourceMappingURL=sanitizer.js.map","function getTrustedTypesGlobal() {\n return globalThis.trustedTypes;\n}\nconst policyCache = new Map();\nfunction getOrCreatePolicy(policyName) {\n const existing = policyCache.get(policyName);\n if (existing)\n return existing;\n const tt = getTrustedTypesGlobal();\n if (!tt?.createPolicy)\n return null;\n try {\n const policy = tt.createPolicy(policyName, {\n createHTML: (s) => s,\n });\n // Policy may be blocked/throw depending on CSP allowlist.\n if (!policy?.createHTML)\n return null;\n policyCache.set(policyName, policy);\n return policy;\n }\n catch {\n return null;\n }\n}\n/**\n * Convert a sanitized HTML string into a Trusted Types HTML value when:\n * - the host configured a policy name, and\n * - the browser supports Trusted Types, and\n * - CSP allows creating/using that policy.\n *\n * Otherwise returns the original string.\n */\nexport function toTrustedHtml(html, policyName) {\n if (!policyName)\n return html;\n if (!html)\n return '';\n const policy = getOrCreatePolicy(policyName);\n if (!policy)\n return html;\n try {\n return policy.createHTML(html);\n }\n catch {\n return html;\n }\n}\n/**\n * Normalize HtmlContent back to a string.\n * Useful when you need to perform string operations (replace/substr/etc) before re-wrapping.\n */\nexport function htmlToString(html) {\n return typeof html === 'string' ? html : String(html);\n}\n//# sourceMappingURL=trustedTypes.js.map","const UNSIGNED_DECIMAL = /^(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\nconst MAX_AUTHORED_PIXEL_LENGTH = 100000;\nfunction parseUnsignedDecimal(value, allowPixelSuffix) {\n if (typeof value === 'number') {\n return Number.isFinite(value) && value >= 0 ? value : null;\n }\n if (typeof value !== 'string')\n return null;\n let token = value.trim();\n if (allowPixelSuffix && token.toLowerCase().endsWith('px')) {\n token = token.slice(0, -2).trim();\n }\n if (!UNSIGNED_DECIMAL.test(token))\n return null;\n const parsed = Number(token);\n return Number.isFinite(parsed) && parsed >= 0 && parsed <= MAX_AUTHORED_PIXEL_LENGTH\n ? parsed\n : null;\n}\n/**\n * Normalize an authored palette width to one complete CSS value.\n *\n * Palette widths are a player extension expressed in pixels. Restricting the\n * grammar to a non-negative decimal with an optional `px` suffix prevents an\n * authored value from terminating the width declaration and introducing a\n * second declaration such as `background-image: url(...)`.\n */\nexport function normalizeCssPixelLength(value) {\n const parsed = parseUnsignedDecimal(value, true);\n return parsed === null ? null : `${parsed}px`;\n}\n/**\n * Normalize QTI image/object width and height attributes to a positive pixel\n * count without a unit. Callers can safely append `px` in a style value.\n *\n * QTI dimensions use the integer-like HTML width/height attribute shape, so\n * unit-bearing values are rejected. Decimal values remain accepted for\n * compatibility and are emitted in canonical numeric form.\n */\nexport function normalizePixelDimension(value, fallback) {\n const parsed = parseUnsignedDecimal(value, false);\n if (parsed !== null && parsed > 0)\n return String(parsed);\n if (fallback === undefined)\n return undefined;\n const parsedFallback = parseUnsignedDecimal(fallback, false);\n return parsedFallback !== null && parsedFallback > 0 ? String(parsedFallback) : undefined;\n}\n//# sourceMappingURL=styleValues.js.map","import { sanitizeHtml, sanitizeTextContent } from '../core/sanitizer.js';\nimport { sanitizeResourceUrl } from '../core/urlPolicy.js';\nimport { toTrustedHtml, htmlToString } from '../core/trustedTypes.js';\nexport { sanitizeHtml, sanitizeTextContent };\nexport { sanitizeResourceUrl };\nexport { enforceItemXmlLimits, normalizeParsingLimits, } from '../core/parsingLimits.js';\nexport { toTrustedHtml, htmlToString };\nexport { normalizeCssPixelLength, normalizePixelDimension, } from './styleValues.js';\nexport function sanitizeSharedHtml(html, security, options) {\n const sanitized = sanitizeHtml(html, { security, sanitizeUrl: options?.sanitizeUrl });\n return toTrustedHtml(sanitized, security?.trustedTypesPolicyName);\n}\n//# sourceMappingURL=index.js.map","/**\n * Component Registry for Web Component-based Interaction Rendering\n *\n * Provides a pluggable system for registering web components to render\n * different QTI interaction types. Uses priority-based dispatch similar to the\n * ExtractionRegistry, but for framework-agnostic web components.\n */\nconst DEFAULT_COMPONENT_TAGS_BY_TYPE = {\n choiceInteraction: { name: 'default-choice', tagName: 'pie-qti-choice' },\n sliderInteraction: { name: 'default-slider', tagName: 'pie-qti-slider' },\n orderInteraction: { name: 'default-order', tagName: 'pie-qti-order' },\n matchInteraction: { name: 'default-match', tagName: 'pie-qti-match' },\n associateInteraction: { name: 'default-associate', tagName: 'pie-qti-associate' },\n gapMatchInteraction: { name: 'default-gap-match', tagName: 'pie-qti-gap-match' },\n hotspotInteraction: { name: 'default-hotspot', tagName: 'pie-qti-hotspot' },\n hottextInteraction: { name: 'default-hottext', tagName: 'pie-qti-hottext' },\n mediaInteraction: { name: 'default-media', tagName: 'pie-qti-media' },\n customInteraction: { name: 'default-custom', tagName: 'pie-qti-custom' },\n portableCustomInteraction: { name: 'default-portable-custom', tagName: 'pie-qti-portable-custom' },\n endAttemptInteraction: { name: 'default-end-attempt', tagName: 'pie-qti-end-attempt' },\n positionObjectInteraction: { name: 'default-position-object', tagName: 'pie-qti-position-object' },\n graphicGapMatchInteraction: { name: 'default-graphic-gap-match', tagName: 'pie-qti-graphic-gap-match' },\n graphicOrderInteraction: { name: 'default-graphic-order', tagName: 'pie-qti-graphic-order' },\n graphicAssociateInteraction: { name: 'default-graphic-associate', tagName: 'pie-qti-graphic-associate' },\n selectPointInteraction: { name: 'default-select-point', tagName: 'pie-qti-select-point' },\n extendedTextInteraction: { name: 'default-extended-text', tagName: 'pie-qti-extended-text' },\n uploadInteraction: { name: 'default-upload', tagName: 'pie-qti-upload' },\n drawingInteraction: { name: 'default-drawing', tagName: 'pie-qti-drawing' },\n catalogPopup: { name: 'default-catalog-popup', tagName: 'pie-qti-catalog-popup' },\n};\n/**\n * Registry for web components that render QTI interactions\n */\nexport class ComponentRegistry {\n constructor() {\n this.components = new Map();\n this.definedElements = new Set();\n this.sealed = false;\n }\n /**\n * Register a web component for an interaction type with priority-based dispatch\n *\n * @param type - QTI interaction type (e.g., 'choiceInteraction', 'textEntryInteraction')\n * @param config - Component configuration with priority and canHandle predicate\n *\n * @example\n * // Custom rating choice component with high priority\n * registry.register('choiceInteraction', {\n * name: 'rating-choice',\n * priority: 100,\n * description: 'Star rating interactions',\n * canHandle: (data) => data.interactionClasses?.includes('rating-interaction'),\n * tagName: 'custom-rating-choice',\n * componentClass: RatingChoiceInteraction,\n * autoRegister: true\n * });\n *\n * // Default choice component\n * registry.register('choiceInteraction', {\n * name: 'standard-choice',\n * tagName: 'qti-choice-interaction'\n * });\n */\n register(type, config) {\n this.assertMutable();\n // Validate tag name\n if (!config.tagName.includes('-')) {\n throw new Error(`Invalid tag name '${config.tagName}'. ` +\n `Web component tag names must contain a hyphen.`);\n }\n const registered = this.createRegisteredComponent(config);\n // Define eagerly in a browser. In a headless compiler there is no custom\n // element registry, so registration is deferred until the renderer is used.\n this.ensureCustomElementDefined(registered.config);\n // Get or create component array for this type\n let components = this.components.get(type);\n if (!components) {\n components = [];\n this.components.set(type, components);\n }\n // Add normalized component and sort by priority (highest first)\n components.push(registered);\n components.sort((a, b) => b.config.priority - a.config.priority);\n }\n createRegisteredComponent(config) {\n return Object.freeze({\n config: Object.freeze({\n ...config,\n priority: config.priority ?? 0,\n canHandle: config.canHandle?.bind(config) ?? (() => true),\n }),\n });\n }\n ensureCustomElementDefined(config) {\n if (!config.componentClass ||\n config.autoRegister === false ||\n this.definedElements.has(config.tagName)) {\n return;\n }\n const registry = globalThis.customElements;\n if (!registry)\n return;\n if (!registry.get(config.tagName)) {\n registry.define(config.tagName, config.componentClass);\n }\n this.definedElements.add(config.tagName);\n }\n /**\n * Get a web component tag name for an interaction type\n * Evaluates canHandle predicates in priority order\n *\n * @param data - Interaction data\n * @returns Web component tag name (e.g., 'qti-choice-interaction')\n * @throws Error if no component matches\n */\n getTagName(data) {\n const components = this.components.get(data.type);\n if (!components || components.length === 0) {\n throw new Error(`No component registered for '${data.type}' interaction. ` +\n `Available types: ${Array.from(this.components.keys()).join(', ')}`);\n }\n // Evaluate canHandle in priority order\n for (const { config } of components) {\n try {\n if (config.canHandle(data)) {\n this.ensureCustomElementDefined(config);\n return config.tagName;\n }\n }\n catch (error) {\n // Log but continue to next component\n console.warn(`canHandle() failed for '${config.name}' component:`, error);\n }\n }\n // No component matched\n const componentList = components\n .map((c) => {\n const desc = c.config.description ? ` (${c.config.description})` : '';\n return `${c.config.name}${desc}`;\n })\n .join(', ');\n throw new Error(`No component available for '${data.type}' interaction.\\n` +\n `Registered components: ${componentList}.\\n` +\n `None of these components matched the current interaction.`);\n }\n /**\n * Get all registered interaction types\n * @returns Array of registered interaction type names\n */\n getRegisteredTypes() {\n return Array.from(this.components.keys());\n }\n /**\n * Check if a component is registered for a type\n */\n hasComponent(type) {\n return this.components.has(type) && this.components.get(type).length > 0;\n }\n /**\n * Get the tag name for a registered type by name (no canHandle evaluation).\n * Useful for non-interaction components like catalogPopup where the type string\n * is known and there is no delivered interaction object to pass.\n *\n * Returns the highest-priority registered tag name for the type, or null if\n * the type is not registered.\n */\n getTagNameForType(type) {\n const components = this.components.get(type);\n if (!components || components.length === 0)\n return null;\n const config = components[0].config;\n this.ensureCustomElementDefined(config);\n return config.tagName;\n }\n /** Freeze renderer selection for a compiled AssessmentItem definition. */\n seal() {\n this.sealed = true;\n return this;\n }\n isSealed() {\n return this.sealed;\n }\n assertMutable() {\n if (this.sealed) {\n throw new Error('ComponentRegistry is sealed for this AssessmentItem; create a new definition to change renderers');\n }\n }\n}\n/**\n * Create a new component registry\n */\nexport function createComponentRegistry() {\n const registry = new ComponentRegistry();\n registerDefaultComponentTags(registry);\n return registry;\n}\n/**\n * Register the default QTI interaction tag names without importing their implementations.\n *\n * Hosts still choose the implementation bundle, typically by importing\n * `@pie-qti/default-components/plugins` in the browser. Keeping only tag metadata here lets\n * the item-player custom element remain the public rendering boundary without depending on\n * Svelte-authored default components.\n */\nexport function registerDefaultComponentTags(registry) {\n for (const [type, component] of Object.entries(DEFAULT_COMPONENT_TAGS_BY_TYPE)) {\n registry.register(type, {\n ...component,\n description: `Default web component tag for ${type}`,\n priority: -100,\n });\n }\n}\n//# sourceMappingURL=ComponentRegistry.js.map","/**\n * Core types for the plugin-based element extraction system\n *\n * Provides interfaces for extracting data from QTI XML elements with\n * priority-based dispatch, validation, and type safety.\n */\n/**\n * Error thrown during extraction\n */\nexport class ExtractionError extends Error {\n constructor(message, extractorId, elementType, cause) {\n super(message);\n this.extractorId = extractorId;\n this.elementType = elementType;\n this.cause = cause;\n this.name = 'ExtractionError';\n }\n}\n/**\n * Type guard for successful extraction result\n */\nexport function isSuccessResult(result) {\n return result.success === true;\n}\n/**\n * Type guard for failed extraction result\n */\nexport function isErrorResult(result) {\n return result.success === false;\n}\n//# sourceMappingURL=types.js.map","/**\n * ExtractionRegistry for priority-based element extraction\n *\n * Manages a collection of ElementExtractor instances with:\n * - Priority-based dispatch (highest priority checked first)\n * - Type-based indexing for O(M) lookup instead of O(N) scanning\n * - Context-correct priority lookup\n * - Validation and error handling\n */\nimport { Qti2xElementNameMapper } from '@pie-qti/qti-common';\nimport { ExtractionError } from './types.js';\nconst REGISTER_FRAMEWORK_DELIVERY_FIELDS = Symbol('registerFrameworkDeliveryFields');\n/**\n * Registry for element extractors with priority-based dispatch\n */\nexport class ExtractionRegistry {\n constructor(elementNameMapper) {\n /** All registered extractors by ID */\n this.extractorsById = new Map();\n /** Extractors indexed by element type for fast lookup */\n this.extractorsByType = new Map();\n /** Plugin-owned additions to the delivery schema. */\n this.deliveryFieldsByType = new Map();\n /** Framework-owned authored sink policy, kept authoritative over plugin additions. */\n this.frameworkDeliveryFieldsByType = new Map();\n this.sealed = false;\n /** QTI 2.x mapper for converting canonical names to extractor registry keys */\n this.qti2xMapper = new Qti2xElementNameMapper();\n this.elementNameMapper = elementNameMapper;\n }\n /**\n * Register an extractor with the registry\n *\n * @param extractor - The extractor to register\n * @throws Error if extractor ID is already registered\n *\n * @example\n * registry.register({\n * id: 'qti:choice',\n * name: 'QTI Standard Choice',\n * priority: 10,\n * elementTypes: ['choiceInteraction'],\n * canHandle: (element) => utils.hasChildWithTag(element, 'simpleChoice'),\n * extract: (element, context) => ({ choices: [...] })\n * });\n */\n register(extractor) {\n this.assertMutable();\n // Check for duplicate ID\n if (this.extractorsById.has(extractor.id)) {\n throw new Error(`Extractor with ID '${extractor.id}' is already registered. ` +\n `Each extractor must have a unique ID.`);\n }\n // Validate extractor configuration\n if (!extractor.id || typeof extractor.id !== 'string') {\n throw new Error(`Extractor must have a valid string ID`);\n }\n if (!extractor.elementTypes || extractor.elementTypes.length === 0) {\n throw new Error(`Extractor '${extractor.id}' must specify at least one element type`);\n }\n if (typeof extractor.priority !== 'number') {\n throw new Error(`Extractor '${extractor.id}' must have a numeric priority`);\n }\n if (extractor.outputType !== undefined &&\n (typeof extractor.outputType !== 'string' || !extractor.outputType)) {\n throw new Error(`Extractor '${extractor.id}' must have a non-empty outputType`);\n }\n const registered = snapshotExtractor(extractor);\n // Register by ID\n this.extractorsById.set(registered.id, registered);\n // Register by type for fast lookup\n // Normalize element types to canonical (lowercase) form for version-agnostic lookup\n for (const type of registered.elementTypes) {\n // Convert to canonical form - extractors specify QTI 2.x names (e.g., 'choiceInteraction')\n // but we store them in canonical form (e.g., 'choiceinteraction') for QTI version independence\n const canonicalType = this.qti2xMapper.toCanonical(type);\n let extractors = this.extractorsByType.get(canonicalType);\n if (!extractors) {\n extractors = [];\n this.extractorsByType.set(canonicalType, extractors);\n }\n extractors.push(registered);\n // Keep sorted by priority (highest first)\n extractors.sort((a, b) => b.priority - a.priority);\n }\n }\n /**\n * Unregister an extractor by ID\n *\n * @param id - The extractor ID to unregister\n * @returns true if extractor was found and removed, false otherwise\n */\n unregister(id) {\n this.assertMutable();\n const extractor = this.extractorsById.get(id);\n if (!extractor)\n return false;\n // Remove from ID map\n this.extractorsById.delete(id);\n // Remove from type maps (using canonical form)\n for (const type of extractor.elementTypes) {\n const canonicalType = this.qti2xMapper.toCanonical(type);\n const extractors = this.extractorsByType.get(canonicalType);\n if (extractors) {\n const index = extractors.findIndex((e) => e.id === id);\n if (index !== -1) {\n extractors.splice(index, 1);\n }\n // Clean up empty arrays\n if (extractors.length === 0) {\n this.extractorsByType.delete(canonicalType);\n }\n }\n }\n return true;\n }\n /**\n * Find an extractor that can handle the given element\n * Uses type-based indexing and evaluates the caller's extraction context.\n *\n * @param element - The element to find an extractor for\n * @param context - Extraction context\n * @returns The matching extractor, or null if none found\n */\n findExtractor(element, context) {\n // Get element type - normalize using mapper for QTI version handling\n // Extractors are registered in canonical (lowercase) form for version independence.\n // Convert any QTI version element name to canonical form for lookup.\n //\n // Example for QTI 3.0:\n // 'qti-choice-interaction' → 'choiceinteraction' (canonical)\n // Example for QTI 2.x:\n // 'choiceInteraction' → 'choiceinteraction' (canonical)\n let lookupKey = element.rawTagName || '';\n if (lookupKey && this.elementNameMapper) {\n // Convert element's raw tag to canonical form using the document's mapper\n lookupKey = this.elementNameMapper.toCanonical(lookupKey);\n }\n // Get extractors for this element type (O(1) map lookup)\n const extractors = this.extractorsByType.get(lookupKey);\n if (!extractors || extractors.length === 0) {\n return null;\n }\n // Evaluate canHandle in priority order (O(M) where M = extractors for this type)\n for (const extractor of extractors) {\n try {\n const canHandle = extractor.canHandle(element, context);\n if (canHandle) {\n return extractor;\n }\n }\n catch (error) {\n // Log but continue to next extractor\n console.warn(`canHandle() failed for extractor '${extractor.id}' (${extractor.name}):`, error);\n }\n }\n return null;\n }\n /**\n * Extract data from an element using the appropriate extractor\n *\n * @param element - The element to extract data from\n * @param context - Extraction context\n * @returns Extraction result with data or error\n *\n * @example\n * const result = registry.extract<ChoiceData>(element, context);\n * if (result.success) {\n * console.log('Extracted:', result.data);\n * if (result.warnings) console.warn('Warnings:', result.warnings);\n * } else {\n * console.error('Extraction failed:', result.error.message);\n * }\n */\n extract(element, context) {\n // Find appropriate extractor\n const extractor = this.findExtractor(element, context);\n if (!extractor) {\n const elementType = element.rawTagName || 'unknown';\n const error = new ExtractionError(`No extractor available for element '${elementType}'. ` +\n `Registered types: ${Array.from(this.extractorsByType.keys()).join(', ')}`, 'none', elementType);\n return { success: false, error };\n }\n try {\n // Extract data\n const data = extractor.extract(element, context);\n // Validate if validator provided\n if (extractor.validate) {\n const validation = extractor.validate(data);\n if (!validation.valid) {\n const error = new ExtractionError(`Validation failed for extractor '${extractor.id}': ${validation.errors?.join(', ')}`, extractor.id, element.rawTagName || 'unknown');\n return { success: false, error };\n }\n // Return with warnings if present\n if (validation.warnings && validation.warnings.length > 0) {\n return {\n success: true,\n data,\n extractor,\n warnings: validation.warnings,\n };\n }\n }\n return { success: true, data, extractor };\n }\n catch (error) {\n const elementType = element.rawTagName || 'unknown';\n const extractionError = error instanceof ExtractionError\n ? error\n : new ExtractionError(`Extraction failed for '${elementType}': ${error instanceof Error ? error.message : String(error)}`, extractor.id, elementType, error instanceof Error ? error : undefined);\n return { success: false, error: extractionError };\n }\n }\n /**\n * Get all registered extractors\n * @returns Read-only array of extractors sorted by priority (highest first)\n */\n getExtractors() {\n const all = Array.from(this.extractorsById.values());\n all.sort((a, b) => b.priority - a.priority);\n return all;\n }\n /**\n * Get extractors for a specific element type\n * @param elementType - The element type (e.g., 'choiceInteraction')\n * @returns Read-only array of extractors for this type, sorted by priority\n */\n getExtractorsForType(elementType) {\n // Convert to canonical form for lookup\n const canonicalType = this.qti2xMapper.toCanonical(elementType);\n return Object.freeze([...(this.extractorsByType.get(canonicalType) ?? [])]);\n }\n /**\n * Register additional plugin-owned sink policy for an interaction kind.\n *\n * The framework's authored schema is stored separately and remains authoritative\n * when both schemas classify the same output path.\n */\n registerDeliveryFields(elementType, fields) {\n this.assertMutable();\n const canonicalType = this.qti2xMapper.toCanonical(elementType);\n const existing = this.deliveryFieldsByType.get(canonicalType) ?? [];\n this.deliveryFieldsByType.set(canonicalType, snapshotDeliveryFields([...existing, ...fields]));\n }\n [REGISTER_FRAMEWORK_DELIVERY_FIELDS](elementType, fields) {\n this.assertMutable();\n const canonicalType = this.qti2xMapper.toCanonical(elementType);\n const existing = this.frameworkDeliveryFieldsByType.get(canonicalType) ?? [];\n this.frameworkDeliveryFieldsByType.set(canonicalType, snapshotDeliveryFields([...existing, ...fields]));\n }\n /** Return the immutable sink policy compiled for an authored interaction kind. */\n getDeliveryFieldsForType(elementType) {\n const canonicalType = this.qti2xMapper.toCanonical(elementType);\n return mergeDeliveryFields(this.deliveryFieldsByType.get(canonicalType) ?? EMPTY_DELIVERY_FIELDS, this.frameworkDeliveryFieldsByType.get(canonicalType) ?? EMPTY_DELIVERY_FIELDS);\n }\n /**\n * Check if an extractor is registered by ID\n * @param id - The extractor ID\n * @returns true if extractor exists\n */\n hasExtractor(id) {\n return this.extractorsById.has(id);\n }\n /**\n * Clear all registered extractors\n * Useful for testing or resetting the registry\n */\n clear() {\n this.assertMutable();\n this.extractorsById.clear();\n this.extractorsByType.clear();\n this.deliveryFieldsByType.clear();\n this.frameworkDeliveryFieldsByType.clear();\n }\n /**\n * Clone this registry with all extractors\n * @returns New registry with same extractors\n */\n clone() {\n const cloned = new ExtractionRegistry(this.elementNameMapper);\n for (const extractor of this.extractorsById.values()) {\n cloned.register(extractor);\n }\n for (const [elementType, fields] of this.deliveryFieldsByType) {\n cloned.deliveryFieldsByType.set(elementType, snapshotDeliveryFields(fields));\n }\n for (const [elementType, fields] of this.frameworkDeliveryFieldsByType) {\n cloned.frameworkDeliveryFieldsByType.set(elementType, snapshotDeliveryFields(fields));\n }\n return cloned;\n }\n /**\n * Freeze the definition set used by a compiled AssessmentItem. Lookups and\n * extraction remain available; registration changes require a new definition.\n */\n seal() {\n this.sealed = true;\n return this;\n }\n isSealed() {\n return this.sealed;\n }\n assertMutable() {\n if (this.sealed) {\n throw new Error('ExtractionRegistry is sealed for this AssessmentItem; create a new definition to change InteractionModules');\n }\n }\n}\nconst EMPTY_DELIVERY_FIELDS = Object.freeze([]);\n/**\n * Create a new extraction registry\n * @param elementNameMapper - Optional element name mapper for QTI version handling\n * @returns Empty registry ready for extractor registration\n */\nexport function createExtractionRegistry(elementNameMapper) {\n return new ExtractionRegistry(elementNameMapper);\n}\n/**\n * Register immutable framework-owned policy without exposing that capability at\n * the public plugin seam.\n *\n * @internal\n */\nexport function registerFrameworkDeliveryFields(registry, elementType, fields) {\n registry[REGISTER_FRAMEWORK_DELIVERY_FIELDS](elementType, fields);\n}\nfunction snapshotExtractor(extractor) {\n const delivery = extractor.delivery\n ? Object.freeze({\n fields: snapshotDeliveryFields(extractor.delivery.fields),\n })\n : undefined;\n return Object.freeze({\n id: extractor.id,\n name: extractor.name,\n priority: extractor.priority,\n elementTypes: Object.freeze([...extractor.elementTypes]),\n ...(extractor.description ? { description: extractor.description } : {}),\n ...(extractor.outputType ? { outputType: extractor.outputType } : {}),\n ...(delivery ? { delivery } : {}),\n canHandle: extractor.canHandle.bind(extractor),\n extract: extractor.extract.bind(extractor),\n ...(extractor.validate\n ? {\n validate: extractor.validate.bind(extractor),\n }\n : {}),\n });\n}\nfunction snapshotDeliveryFields(fields) {\n return Object.freeze(fields.map((field) => Object.freeze({ ...field, path: Object.freeze([...field.path]) })));\n}\nfunction mergeDeliveryFields(extensions, framework) {\n if (extensions.length === 0 && framework.length === 0)\n return EMPTY_DELIVERY_FIELDS;\n const fieldsByPath = new Map();\n for (const field of [...extensions, ...framework]) {\n // One output path has one sink meaning. Framework-authored meaning is applied\n // last so a plugin can add new paths but cannot relabel a standard one.\n fieldsByPath.set(JSON.stringify(field.path), field);\n }\n return snapshotDeliveryFields([...fieldsByPath.values()]);\n}\n//# sourceMappingURL=ExtractionRegistry.js.map","export function htmlField(...path) {\n return { kind: 'html', path };\n}\nexport function urlField(use, ...path) {\n return { kind: 'url', path, use };\n}\n//# sourceMappingURL=deliveryTypes.js.map","/**\n * Deterministic pseudo-random number generator helpers.\n *\n * We keep this tiny and dependency-free so tests (and optionally consumers)\n * can run template processing deterministically.\n */\n/**\n * Mulberry32 PRNG.\n * Returns a function that yields a float in [0, 1).\n */\nexport function createSeededRng(seed) {\n // Ensure 32-bit unsigned int\n let a = seed >>> 0;\n return () => {\n a = (a + 0x6d2b79f5) >>> 0;\n let t = a;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n//# sourceMappingURL=random.js.map","/**\n * Seeded shuffling for QTI interactions that support the `shuffle` attribute.\n *\n * QTI expects the presentation order to be randomized per candidate attempt, and to\n * stay stable *within* that attempt — a candidate must not see choices jump around\n * between re-renders or after reloading a saved session. Both properties come from\n * seeding a real PRNG with the item session GUID: `Player` persists that GUID in its\n * saved state and restores it, so the same attempt reproduces the same order while a\n * different candidate (or a new attempt) gets a different one.\n */\nimport { createSeededRng } from './random.js';\n/**\n * FNV-1a (32-bit) string hash.\n *\n * Deliberately not a sum of character codes: a sum is order-insensitive, so it\n * collides on anagrams (`\"AB\"`/`\"BA\"`, `\"item1\"`/`\"1item\"`) and clusters tightly for\n * ids sharing a prefix, which in turn makes a weak PRNG return the same permutation\n * for every item.\n */\nexport function hashStringToSeed(value) {\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n/**\n * Build the RNG used to shuffle one interaction's choices.\n *\n * Keyed on both the session GUID and the response identifier so that two interactions\n * in the same item do not receive identical permutations.\n */\nexport function createShuffleRng(sessionGuid, responseId) {\n return createSeededRng(hashStringToSeed(`${sessionGuid}:${responseId}`));\n}\n/**\n * Fisher-Yates shuffle that honours QTI's `fixed` attribute: entries reported as fixed\n * keep their authored index, and only the remaining entries are permuted among the\n * leftover slots.\n *\n * Returns a new array; the input is not mutated.\n */\nexport function shuffleWithFixed(items, isFixed, rng) {\n const fixedAt = new Map();\n const movable = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (isFixed(item)) {\n fixedAt.set(i, item);\n }\n else {\n movable.push(item);\n }\n }\n for (let i = movable.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1));\n [movable[i], movable[j]] = [movable[j], movable[i]];\n }\n const out = new Array(items.length);\n let next = 0;\n for (let i = 0; i < items.length; i++) {\n const pinned = fixedAt.get(i);\n out[i] = pinned !== undefined ? pinned : movable[next++];\n }\n return out;\n}\n/**\n * Convenience wrapper for the common extractor case.\n *\n * `rng` is optional so that an externally constructed `ExtractionContext` without one\n * simply keeps the authored order rather than throwing — failing back to the order the\n * content author wrote is always safe.\n */\nexport function maybeShuffle(items, shuffle, rng) {\n if (!shuffle || !rng || items.length < 2)\n return [...items];\n // `T` is intentionally unconstrained: constraining it to `{ fixed?: boolean }` makes\n // inference collapse `T` to the constraint for choice types that do not declare\n // `fixed` (e.g. `associateInteraction`), erasing their real fields from the result.\n return shuffleWithFixed(items, (item) => item.fixed === true, rng);\n}\n//# sourceMappingURL=shuffle.js.map","/**\n * Standard QTI associateInteraction extractor\n *\n * Extracts data from associateInteraction elements (associating items)\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\n/**\n * Standard QTI associate interaction extractor\n * Handles associateInteraction elements (creating associations between items)\n */\nexport const standardAssociateExtractor = {\n id: 'qti:associate-interaction',\n name: 'QTI Standard Associate Interaction',\n priority: 10,\n elementTypes: ['associateInteraction'],\n description: 'Extracts standard QTI associateInteraction (associating items)',\n canHandle(element, context) {\n // All associateInteraction elements with simpleAssociableChoice are standard\n return (context.utils.matchesTag(element, 'associateInteraction') &&\n context.utils.hasChildWithTag(element, 'simpleAssociableChoice'));\n },\n extract(element, context) {\n const { utils } = context;\n // Extract simpleAssociableChoice children\n const choiceElements = utils.getChildrenByTag(element, 'simpleAssociableChoice');\n const choices = choiceElements.map((choice) => {\n const classes = utils.getClasses(choice);\n const matchMax = utils.getNumberAttribute(choice, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(choice, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(choice, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract attributes with proper defaults\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 0);\n const minAssociations = utils.getNumberAttribute(element, 'minAssociations', 0);\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n choices: maybeShuffle(choices, shuffle, context.shuffleRng),\n shuffle,\n maxAssociations,\n ...(minAssociations > 0 ? { minAssociations } : {}),\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n // Validate choices exist\n if (!data.choices || data.choices.length < 2) {\n errors.push('associateInteraction must have at least 2 choices');\n }\n // Validate choice identifiers\n if (data.choices) {\n const identifiers = new Set();\n for (const choice of data.choices) {\n if (!choice.identifier) {\n errors.push('All choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate choice identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n // Validate matchMax\n if (choice.matchMax < 0) {\n errors.push(`matchMax must be non-negative for choice ${choice.identifier}`);\n }\n // Validate matchMin\n if (choice.matchMin !== undefined && choice.matchMin < 0) {\n errors.push(`matchMin must be non-negative for choice ${choice.identifier}`);\n }\n }\n }\n // Validate maxAssociations\n if (data.maxAssociations < 0) {\n errors.push('maxAssociations must be non-negative');\n }\n // Validate minAssociations\n if (data.minAssociations !== undefined && data.minAssociations < 0) {\n errors.push('minAssociations must be non-negative');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI choiceInteraction extractor\n *\n * Extracts data from choiceInteraction elements with simpleChoice children\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\n/**\n * Standard QTI choice interaction extractor\n * Handles choiceInteraction elements with simpleChoice children\n */\nexport const standardChoiceExtractor = {\n id: 'qti:choice-interaction',\n name: 'QTI Standard Choice Interaction',\n priority: 10,\n elementTypes: ['choiceInteraction'],\n description: 'Extracts standard QTI choiceInteraction with simpleChoice elements',\n canHandle(element, context) {\n // Standard QTI choice interactions have simpleChoice children\n return context.utils.hasChildWithTag(element, 'simpleChoice');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract choices\n const simpleChoices = utils.getChildrenByTag(element, 'simpleChoice');\n const choices = simpleChoices.map((choice) => {\n const classes = utils.getClasses(choice);\n const fixed = utils.getBooleanAttribute(choice, 'fixed');\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n ...(fixed ? { fixed } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract prompt\n const promptElement = utils.querySelector(element, 'prompt');\n const prompt = promptElement ? utils.getHtmlContent(promptElement) : null;\n // Extract attributes\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n const interactionClasses = utils.getClasses(element);\n const maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n return {\n choices: maybeShuffle(choices, shuffle, context.shuffleRng),\n shuffle,\n maxChoices,\n minChoices,\n prompt,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate choices exist\n if (!data.choices || data.choices.length === 0) {\n errors.push('choiceInteraction must have at least one choice');\n }\n // Validate choice identifiers\n if (data.choices) {\n const identifiers = new Set();\n for (const choice of data.choices) {\n if (!choice.identifier) {\n errors.push('All choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate choice identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n }\n }\n // Validate maxChoices\n if (data.maxChoices < 0) {\n errors.push('maxChoices must be non-negative');\n }\n if (data.maxChoices === 0) {\n warnings.push('maxChoices=0 means unlimited selections');\n }\n if (data.maxChoices > data.choices.length) {\n warnings.push(`maxChoices (${data.maxChoices}) is greater than the number of choices (${data.choices.length})`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI customInteraction extractor\n *\n * Extracts data from customInteraction elements (custom/portable interactions)\n */\n/**\n * Standard QTI custom interaction extractor\n * Handles customInteraction elements (vendor-specific or portable custom interactions)\n */\nexport const standardCustomExtractor = {\n id: 'qti:custom-interaction',\n name: 'QTI Standard Custom Interaction',\n priority: 10,\n elementTypes: ['customInteraction'],\n description: 'Extracts standard QTI customInteraction (custom/portable interactions)',\n canHandle(element, _context) {\n const tag = element.rawTagName?.toLowerCase() ?? '';\n if (tag !== 'custominteraction' && tag !== 'qti-custom-interaction')\n return false;\n // A QTI 2.x customInteraction containing a namespaced PCI payload is handled\n // by portableCustomExtractor. All other custom interactions keep this fallback.\n return !containsPortableCustomInteraction(element);\n },\n extract(element, context) {\n const { utils } = context;\n // Capture the raw XML for the custom interaction\n const xml = element.outerHTML || element.toString();\n // Extract all attributes\n const rawAttributes = {};\n if (element.attributes) {\n for (const [key, value] of Object.entries(element.attributes)) {\n rawAttributes[key] = String(value);\n }\n }\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n xml,\n rawAttributes,\n prompt,\n };\n },\n validate(_data) {\n const warnings = [];\n // Warn if no XML content\n if (!_data.xml || _data.xml.trim() === '') {\n warnings.push('customInteraction has no XML content');\n }\n return {\n valid: true,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\nfunction containsPortableCustomInteraction(element) {\n const visit = (parent) => {\n for (const child of parent.childNodes ?? []) {\n const candidate = child;\n const rawTag = candidate.rawTagName?.toLowerCase() ?? '';\n const localTag = rawTag.includes(':') ? rawTag.slice(rawTag.lastIndexOf(':') + 1) : rawTag;\n if (localTag === 'portablecustominteraction' || localTag === 'qti-portable-custom-interaction') {\n return true;\n }\n if (candidate.rawTagName && visit(candidate))\n return true;\n }\n return false;\n };\n return visit(element);\n}\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI drawingInteraction extractor\n *\n * Extracts data from drawingInteraction elements (drawing on canvas)\n */\nimport { normalizePixelDimension } from '../../security/styleValues.js';\n/**\n * Standard QTI drawing interaction extractor\n * Handles drawingInteraction elements (drawing on a canvas)\n */\nexport const standardDrawingExtractor = {\n id: 'qti:drawing-interaction',\n name: 'QTI Standard Drawing Interaction',\n priority: 10,\n elementTypes: ['drawingInteraction'],\n description: 'Extracts standard QTI drawingInteraction (drawing on canvas)',\n canHandle(element, context) {\n // All drawingInteraction elements are standard\n return context.utils.matchesTag(element, 'drawingInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract background image data from object element (optional)\n const objectElements = utils.getChildrenByTag(element, 'object');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''));\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''));\n if (type.startsWith('image/svg')) {\n // Extract inline SVG content\n const content = utils.getHtmlContent(objectElement);\n imageData = {\n type: 'svg',\n content,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n else if (data) {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n }\n // Extract all attributes\n const rawAttributes = {};\n if (element.attributes) {\n for (const [key, value] of Object.entries(element.attributes)) {\n rawAttributes[key] = String(value);\n }\n }\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n imageData,\n rawAttributes,\n prompt,\n };\n },\n validate(data) {\n const warnings = [];\n // Warn if no background image\n if (!data.imageData) {\n warnings.push('drawingInteraction has no background image - students will draw on a blank canvas');\n }\n return {\n valid: true,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI endAttemptInteraction extractor\n *\n * Extracts data from endAttemptInteraction elements (end attempt button)\n */\n/**\n * Standard QTI end attempt interaction extractor\n * Handles endAttemptInteraction elements (button to end the attempt)\n */\nexport const standardEndAttemptExtractor = {\n id: 'qti:end-attempt-interaction',\n name: 'QTI Standard End Attempt Interaction',\n priority: 10,\n elementTypes: ['endAttemptInteraction'],\n description: 'Extracts standard QTI endAttemptInteraction (end attempt button)',\n canHandle(element, context) {\n // All endAttemptInteraction elements are standard\n return context.utils.matchesTag(element, 'endAttemptInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract attributes with defaults\n const title = utils.getAttribute(element, 'title', 'End Attempt');\n const countAttempt = element.hasAttribute('countAttempt')\n ? utils.getBooleanAttribute(element, 'countAttempt')\n : true;\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n title,\n countAttempt,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate title is not empty\n if (!data.title || data.title.trim() === '') {\n errors.push('endAttemptInteraction must have a title');\n }\n // Warn if countAttempt is false (uncommon usage)\n if (data.countAttempt === false) {\n warnings.push('endAttemptInteraction has countAttempt=false - make sure this is intentional');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI extendedTextInteraction extractor\n *\n * Extracts data from extendedTextInteraction elements (multi-line text input)\n */\n/**\n * Standard QTI extended text interaction extractor\n * Handles extendedTextInteraction elements (multi-line text input)\n */\nexport const standardExtendedTextExtractor = {\n id: 'qti:extended-text-interaction',\n name: 'QTI Standard Extended Text Interaction',\n priority: 10,\n elementTypes: ['extendedTextInteraction'],\n description: 'Extracts standard QTI extendedTextInteraction (multi-line text input)',\n canHandle(element, _context) {\n // All extendedTextInteraction elements are standard (both QTI 2.x and 3.0)\n return (element.rawTagName === 'extendedTextInteraction' ||\n element.rawTagName === 'qti-extended-text-interaction');\n },\n extract(element, context) {\n const { utils } = context;\n const declaration = context.declarations.get(context.responseId);\n // Extract attributes\n const cardinality = declaration?.cardinality ?? 'single';\n const base = utils.getNumberAttribute(element, 'base', 10);\n const stringIdentifier = utils.getAttribute(element, 'stringIdentifier', '') || undefined;\n const minStrings = utils.getNumberAttribute(element, 'minStrings', 0);\n const maxStrings = utils.getNumberAttribute(element, 'maxStrings', cardinality === 'single' || cardinality === 'record' ? 1 : 0);\n const expectedLines = utils.getNumberAttribute(element, 'expectedLines', 3);\n const expectedLength = utils.getNumberAttribute(element, 'expectedLength', 200);\n const placeholderText = utils.getAttribute(element, 'placeholderText', '');\n const format = utils.getAttribute(element, 'format', 'plain');\n const patternMask = utils.getAttribute(element, 'patternMask', '') || null;\n const patternMaskMessage = utils.getAttribute(element, 'patternMaskMessage', '') || null;\n const interactionClasses = utils.getClasses(element);\n const prompt = utils.getPrompt(element);\n return {\n cardinality,\n baseType: declaration?.baseType,\n base,\n ...(stringIdentifier ? { stringIdentifier } : {}),\n minStrings,\n maxStrings,\n expectedLines,\n expectedLength,\n prompt,\n placeholderText,\n format,\n ...(patternMask ? { patternMask } : {}),\n ...(patternMaskMessage ? { patternMaskMessage } : {}),\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n if (data.cardinality === 'record') {\n if (data.baseType)\n errors.push('record cardinality must not declare a baseType');\n if (data.minStrings > 1 || data.maxStrings > 1) {\n errors.push('record cardinality captures exactly one numeric string');\n }\n }\n else if (!['string', 'integer', 'float'].includes(data.baseType ?? '')) {\n errors.push('extendedTextInteraction baseType must be string, integer, or float');\n }\n if (!Number.isInteger(data.base) || data.base < 2 || data.base > 36) {\n errors.push('base must be an integer from 2 through 36');\n }\n if (!Number.isInteger(data.minStrings) || data.minStrings < 0) {\n errors.push('minStrings must be a non-negative integer');\n }\n if (!Number.isInteger(data.maxStrings) || data.maxStrings < 0) {\n errors.push('maxStrings must be a non-negative integer');\n }\n if (data.maxStrings > 0 && data.minStrings > data.maxStrings) {\n errors.push('minStrings must not exceed maxStrings');\n }\n // Validate expectedLines\n if (!Number.isInteger(data.expectedLines) || data.expectedLines < 0) {\n errors.push('expectedLines must be a non-negative integer');\n }\n // Validate expectedLength\n if (!Number.isInteger(data.expectedLength) || data.expectedLength < 0) {\n errors.push('expectedLength must be a non-negative integer');\n }\n // Validate format\n const validFormats = ['plain', 'preFormatted', 'preformatted', 'xhtml'];\n if (!validFormats.includes(data.format)) {\n warnings.push(`Unrecognized format \"${data.format}\" - expected plain, preformatted, preFormatted, or xhtml`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI gapMatchInteraction extractor\n *\n * Extracts data from gapMatchInteraction elements (drag words into gaps)\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\nimport { normalizeCssPixelLength } from '../../security/styleValues.js';\nconst GAP_ELEMENT_PATTERN = /<(?:qti-gap|gap)(?=[\\s/>])([^>]*)\\/?>/gi;\nconst GAP_CLOSE_PATTERN = /<\\/(?:qti-gap|gap)>/gi;\nconst GAP_TEXT_PATTERN = /<(?:qti-gap-text|gapText)\\b[\\s\\S]*?<\\/(?:qti-gap-text|gapText)>/gi;\nconst GAP_MATCH_OPEN_PATTERN = /<(?:qti-gap-match-interaction|gapMatchInteraction)\\b[^>]*>/i;\nconst GAP_MATCH_CLOSE_PATTERN = /<\\/(?:qti-gap-match-interaction|gapMatchInteraction)>/i;\nconst PROMPT_PATTERN = /<(?:qti-prompt|prompt)\\b[\\s\\S]*?<\\/(?:qti-prompt|prompt)>/gi;\nfunction extractAttribute(attrs, name) {\n const match = new RegExp(`\\\\b${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)')`, 'i').exec(attrs);\n return (match?.[1] ?? match?.[2] ?? '').trim();\n}\nfunction promptTextFromInteractionBody(interactionHtml) {\n return interactionHtml\n .replace(GAP_MATCH_OPEN_PATTERN, '')\n .replace(GAP_MATCH_CLOSE_PATTERN, '')\n .replace(PROMPT_PATTERN, '')\n .replace(GAP_TEXT_PATTERN, '')\n .replace(GAP_ELEMENT_PATTERN, (_match, attrs) => {\n const id = extractAttribute(attrs, 'identifier');\n return id ? `[GAP:${id}]` : '';\n })\n .replace(GAP_CLOSE_PATTERN, '')\n .trim();\n}\n/**\n * Standard QTI gap match interaction extractor\n * Handles gapMatchInteraction elements (drag words into gaps in text)\n */\nexport const standardGapMatchExtractor = {\n id: 'qti:gap-match-interaction',\n name: 'QTI Standard Gap Match Interaction',\n priority: 10,\n elementTypes: ['gapMatchInteraction'],\n description: 'Extracts standard QTI gapMatchInteraction (drag words into gaps)',\n canHandle(element, context) {\n // All gapMatchInteraction elements are standard\n return context.utils.matchesTag(element, 'gapMatchInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract gapText children (draggable items)\n const gapTextElements = utils.getChildrenByTag(element, 'gapText');\n const gapTexts = gapTextElements.map((gapText) => {\n const classes = utils.getClasses(gapText);\n const matchMax = utils.getNumberAttribute(gapText, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(gapText, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(gapText, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n return {\n identifier: utils.getAttribute(gapText, 'identifier', ''),\n text: utils.getTextContent(gapText),\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract prompt (optional) and process gap placeholders.\n // NOTE: Many QTI items place `<gap>` elements in the interaction content (e.g. a `<p>`/`<blockquote>`)\n // rather than inside a `<prompt>` element. Support both patterns.\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n let prompt = null;\n let promptText = '';\n const gaps = [];\n if (promptElements.length > 0) {\n const promptElement = promptElements[0];\n prompt = utils.getHtmlContent(promptElement);\n // Extract gap elements from prompt children\n const gapElements = utils.getChildrenByTag(promptElement, 'gap');\n for (const gap of gapElements) {\n gaps.push(utils.getAttribute(gap, 'identifier', ''));\n }\n // Replace gap elements with placeholders in the text\n // Derive renderable content only from the already-sanitized prompt. Using\n // outerHTML here would reintroduce event handlers and unsafe URLs that\n // getHtmlContent deliberately removed.\n promptText = prompt\n .replace(GAP_ELEMENT_PATTERN, (_match, attrs) => {\n const id = extractAttribute(attrs, 'identifier');\n return id ? `[GAP:${id}]` : '';\n })\n .replace(GAP_CLOSE_PATTERN, '')\n .trim();\n }\n // If gaps were not found inside a <prompt>, search the full interaction body.\n // This handles items where <gap> elements appear in <p>/<blockquote> siblings of <prompt>.\n if (gaps.length === 0) {\n // Keep the fallback on the same sanitization boundary as prompt content.\n const interactionHtml = utils.getHtmlContent(element);\n const gapIdMatches = Array.from(interactionHtml.matchAll(GAP_ELEMENT_PATTERN));\n for (const m of gapIdMatches) {\n const id = extractAttribute(m[1] ?? '', 'identifier');\n if (id)\n gaps.push(id);\n }\n if (gaps.length > 0 && (!promptText || !promptText.includes('[GAP:'))) {\n // Build promptText from the interaction body when gaps are authored outside the prompt.\n promptText = promptTextFromInteractionBody(interactionHtml);\n }\n }\n // Extract attributes\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const interactionClasses = utils.getClasses(element);\n const choicesContainerWidth = normalizeCssPixelLength(utils.getAttribute(element, 'data-choices-container-width', ''));\n const maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n return {\n gapTexts: maybeShuffle(gapTexts, shuffle, context.shuffleRng),\n gaps,\n shuffle,\n prompt,\n promptText,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(choicesContainerWidth ? { choicesContainerWidth } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n // Validate gapTexts exist\n if (!data.gapTexts || data.gapTexts.length === 0) {\n errors.push('gapMatchInteraction must have at least one gapText');\n }\n // Validate gaps exist\n if (!data.gaps || data.gaps.length === 0) {\n errors.push('gapMatchInteraction must have at least one gap in the prompt');\n }\n // Validate gapText identifiers\n if (data.gapTexts) {\n const identifiers = new Set();\n for (const gapText of data.gapTexts) {\n if (!gapText.identifier) {\n errors.push('All gapTexts must have an identifier');\n }\n else if (identifiers.has(gapText.identifier)) {\n errors.push(`Duplicate gapText identifier: ${gapText.identifier}`);\n }\n else {\n identifiers.add(gapText.identifier);\n }\n // Validate matchMax\n if (gapText.matchMax < 0) {\n errors.push(`matchMax must be non-negative for gapText ${gapText.identifier}`);\n }\n }\n }\n // Validate gap identifiers\n if (data.gaps) {\n const identifiers = new Set();\n for (const gap of data.gaps) {\n if (!gap) {\n errors.push('All gaps must have an identifier');\n }\n else if (identifiers.has(gap)) {\n errors.push(`Duplicate gap identifier: ${gap}`);\n }\n else {\n identifiers.add(gap);\n }\n }\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI graphicAssociateInteraction extractor\n *\n * Extracts data from graphicAssociateInteraction elements (associate items on image)\n */\nimport { normalizePixelDimension } from '../../security/styleValues.js';\n/**\n * Standard QTI graphic associate interaction extractor\n * Handles graphicAssociateInteraction elements (creating associations between hotspots)\n */\nexport const standardGraphicAssociateExtractor = {\n id: 'qti:graphic-associate-interaction',\n name: 'QTI Standard Graphic Associate Interaction',\n priority: 10,\n elementTypes: ['graphicAssociateInteraction'],\n description: 'Extracts standard QTI graphicAssociateInteraction (associate items on image)',\n canHandle(element, context) {\n // All graphicAssociateInteraction elements are standard\n return context.utils.matchesTag(element, 'graphicAssociateInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract image data from object element\n const objectElements = utils.getChildrenByTag(element, 'object');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''), '500');\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''), '300');\n if (type.startsWith('image/svg')) {\n // Extract inline SVG content - get full content including <svg> tag\n const content = utils.getHtmlContent(objectElement);\n imageData = {\n type: 'svg',\n content,\n width,\n height,\n };\n }\n else {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n width,\n height,\n };\n }\n }\n // Extract associableHotspot children\n const hotspotElements = utils.getChildrenByTag(element, 'associableHotspot');\n const associableHotspots = hotspotElements.map((hotspot) => {\n const classes = utils.getClasses(hotspot);\n const identifier = utils.getAttribute(hotspot, 'identifier', '');\n const shape = utils.getAttribute(hotspot, 'shape', 'rect');\n const coords = utils.getAttribute(hotspot, 'coords', '0,0,50,50');\n const matchMax = utils.getNumberAttribute(hotspot, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(hotspot, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(hotspot, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n // Get text content as label, use identifier as fallback\n const textContent = utils.getTextContent(hotspot).trim();\n const label = textContent || identifier;\n return {\n identifier,\n label,\n shape,\n coords,\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract attributes with proper defaults\n const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 1);\n const minAssociations = utils.getNumberAttribute(element, 'minAssociations', 0);\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n imageData,\n associableHotspots,\n maxAssociations,\n minAssociations,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate image data\n if (!data.imageData) {\n warnings.push('graphicAssociateInteraction has no image data');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('graphicAssociateInteraction must have an image URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('graphicAssociateInteraction must have SVG content');\n }\n // Validate hotspots exist\n if (!data.associableHotspots || data.associableHotspots.length < 2) {\n errors.push('graphicAssociateInteraction must have at least 2 hotspots');\n }\n // Validate hotspot identifiers and coords\n if (data.associableHotspots && data.associableHotspots.length > 0) {\n const identifiers = new Set();\n for (const hotspot of data.associableHotspots) {\n if (!hotspot.identifier) {\n errors.push('All hotspots must have an identifier');\n }\n else if (identifiers.has(hotspot.identifier)) {\n errors.push(`Duplicate hotspot identifier: ${hotspot.identifier}`);\n }\n else {\n identifiers.add(hotspot.identifier);\n }\n if (!hotspot.coords) {\n errors.push(`Hotspot ${hotspot.identifier} must have coords`);\n }\n // Validate matchMax\n if (hotspot.matchMax < 0) {\n errors.push(`matchMax must be non-negative for hotspot ${hotspot.identifier}`);\n }\n }\n }\n // Validate maxAssociations\n if (data.maxAssociations < 0) {\n errors.push('maxAssociations must be non-negative');\n }\n // Validate minAssociations\n if (data.minAssociations < 0) {\n errors.push('minAssociations must be non-negative');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI graphicGapMatchInteraction extractor\n *\n * Extracts data from graphicGapMatchInteraction elements (drag text/images into gaps on image)\n */\nimport { normalizeCssPixelLength, normalizePixelDimension, } from '../../security/styleValues.js';\n/**\n * Standard QTI graphic gap match interaction extractor\n * Handles graphicGapMatchInteraction elements (drag text/images into gaps on an image)\n */\nexport const standardGraphicGapMatchExtractor = {\n id: 'qti:graphic-gap-match-interaction',\n name: 'QTI Standard Graphic Gap Match Interaction',\n priority: 10,\n elementTypes: ['graphicGapMatchInteraction'],\n description: 'Extracts standard QTI graphicGapMatchInteraction (drag text/images into gaps)',\n canHandle(element, context) {\n // All graphicGapMatchInteraction elements are standard\n return context.utils.matchesTag(element, 'graphicGapMatchInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract image data from object element\n const objectElements = utils.getChildrenByTag(element, 'object');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const normalizedWidth = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''));\n const normalizedHeight = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''));\n const width = normalizedWidth ? Number(normalizedWidth) : undefined;\n const height = normalizedHeight ? Number(normalizedHeight) : undefined;\n if (type.startsWith('image/svg')) {\n // Inline SVG: <object type=\"image/svg+xml\"><svg>...</svg></object>\n // External SVG: <object type=\"image/svg+xml\" data=\"path/to/file.svg\"/>\n // The <object> may contain alt text (not SVG markup) — only treat as inline if content has <svg.\n const content = utils.getHtmlContent(objectElement);\n const hasSvgMarkup = /<svg[\\s>]/i.test(content);\n if (hasSvgMarkup) {\n imageData = {\n type: 'svg',\n content,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n else {\n // External SVG file reference — render via <img src>\n imageData = {\n type: 'image',\n src: data,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n }\n else {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n }\n // Extract interaction-level attributes\n const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 0);\n // Extract gapText children (draggable text labels)\n const gapTextElements = utils.getChildrenByTag(element, 'gapText');\n const gapTexts = gapTextElements.map((gapText) => {\n const classes = utils.getClasses(gapText);\n const matchMax = utils.getNumberAttribute(gapText, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(gapText, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(gapText, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n const text = utils.getHtmlContent(gapText);\n return {\n identifier: utils.getAttribute(gapText, 'identifier', ''),\n text,\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract gapImg children (draggable image labels)\n const gapImgElements = utils.getChildrenByTag(element, 'gapImg');\n const gapImages = gapImgElements.map((gapImg) => {\n const matchMax = utils.getNumberAttribute(gapImg, 'matchMax', 1);\n const matchGroupRaw = utils.getAttribute(gapImg, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n const objectChildren = utils.getChildrenByTag(gapImg, 'object');\n let src = '';\n let alt = '';\n let width;\n let height;\n if (objectChildren.length > 0) {\n const obj = objectChildren[0];\n src = utils.getAttribute(obj, 'data', '');\n alt = utils.getTextContent(obj);\n const w = normalizePixelDimension(utils.getAttribute(obj, 'width', ''));\n const h = normalizePixelDimension(utils.getAttribute(obj, 'height', ''));\n if (w)\n width = Number(w);\n if (h)\n height = Number(h);\n }\n return {\n identifier: utils.getAttribute(gapImg, 'identifier', ''),\n src,\n alt,\n matchMax,\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(width !== undefined ? { width } : {}),\n ...(height !== undefined ? { height } : {}),\n };\n });\n // Extract associableHotspot elements (gap targets)\n const hotspotElements = utils.getChildrenByTag(element, 'associableHotspot');\n const hotspots = hotspotElements.map((hotspot) => ({\n identifier: utils.getAttribute(hotspot, 'identifier', ''),\n shape: utils.getAttribute(hotspot, 'shape', 'rect'),\n coords: utils.getAttribute(hotspot, 'coords', ''),\n matchMax: utils.getNumberAttribute(hotspot, 'matchMax', 1),\n }));\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n const interactionClasses = utils.getClasses(element);\n const choicesContainerWidth = normalizeCssPixelLength(utils.getAttribute(element, 'data-choices-container-width', ''));\n const maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n return {\n imageData,\n maxAssociations,\n gapTexts,\n gapImages,\n hotspots,\n prompt,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(choicesContainerWidth ? { choicesContainerWidth } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate image data (optional but recommended)\n if (!data.imageData) {\n warnings.push('graphicGapMatchInteraction has no background image');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('graphicGapMatchInteraction must have an image URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('graphicGapMatchInteraction must have SVG content');\n }\n // Validate that at least one draggable choice type is present\n if ((!data.gapTexts || data.gapTexts.length === 0) && (!data.gapImages || data.gapImages.length === 0)) {\n errors.push('graphicGapMatchInteraction must have at least one gapText or gapImg');\n }\n // Validate hotspots exist\n if (!data.hotspots || data.hotspots.length === 0) {\n errors.push('graphicGapMatchInteraction must have at least one hotspot');\n }\n // Validate gapText identifiers\n if (data.gapTexts) {\n const identifiers = new Set();\n for (const gapText of data.gapTexts) {\n if (!gapText.identifier) {\n errors.push('All gapTexts must have an identifier');\n }\n else if (identifiers.has(gapText.identifier)) {\n errors.push(`Duplicate gapText identifier: ${gapText.identifier}`);\n }\n else {\n identifiers.add(gapText.identifier);\n }\n }\n }\n // Validate hotspot identifiers\n if (data.hotspots) {\n const identifiers = new Set();\n for (const hotspot of data.hotspots) {\n if (!hotspot.identifier) {\n errors.push('All hotspots must have an identifier');\n }\n else if (identifiers.has(hotspot.identifier)) {\n errors.push(`Duplicate hotspot identifier: ${hotspot.identifier}`);\n }\n else {\n identifiers.add(hotspot.identifier);\n }\n if (!hotspot.coords) {\n errors.push(`Hotspot ${hotspot.identifier} must have coords`);\n }\n }\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI graphicOrderInteraction extractor\n *\n * Extracts data from graphicOrderInteraction elements (order items on image)\n */\nimport { normalizePixelDimension } from '../../security/styleValues.js';\n/**\n * Standard QTI graphic order interaction extractor\n * Handles graphicOrderInteraction elements (ordering hotspots on an image)\n */\nexport const standardGraphicOrderExtractor = {\n id: 'qti:graphic-order-interaction',\n name: 'QTI Standard Graphic Order Interaction',\n priority: 10,\n elementTypes: ['graphicOrderInteraction'],\n description: 'Extracts standard QTI graphicOrderInteraction (order items on image)',\n canHandle(element, context) {\n // All graphicOrderInteraction elements are standard\n return context.utils.matchesTag(element, 'graphicOrderInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract image data from object element\n const objectElements = utils.getChildrenByTag(element, 'object');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''), '500');\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''), '300');\n if (type.startsWith('image/svg')) {\n // Extract inline SVG content - get full content including <svg> tag\n const content = utils.getHtmlContent(objectElement);\n imageData = {\n type: 'svg',\n content,\n width,\n height,\n };\n }\n else {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n width,\n height,\n };\n }\n }\n // Extract hotspotChoice children\n const hotspotElements = utils.getChildrenByTag(element, 'hotspotChoice');\n const hotspotChoices = hotspotElements.map((hotspot) => {\n const classes = utils.getClasses(hotspot);\n const identifier = utils.getAttribute(hotspot, 'identifier', '');\n const shape = utils.getAttribute(hotspot, 'shape', 'rect');\n const coords = utils.getAttribute(hotspot, 'coords', '0,0,50,50');\n const fixed = utils.getBooleanAttribute(hotspot, 'fixed');\n // Get text content as label, use identifier as fallback\n const textContent = utils.getTextContent(hotspot).trim();\n const label = textContent || identifier;\n return {\n identifier,\n label,\n shape,\n coords,\n ...(fixed ? { fixed } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n imageData,\n hotspotChoices,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate image data\n if (!data.imageData) {\n warnings.push('graphicOrderInteraction has no image data');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('graphicOrderInteraction must have an image URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('graphicOrderInteraction must have SVG content');\n }\n // Validate hotspot choices exist\n if (!data.hotspotChoices || data.hotspotChoices.length < 2) {\n errors.push('graphicOrderInteraction must have at least 2 hotspots');\n }\n // Validate hotspot choice identifiers and coords\n if (data.hotspotChoices) {\n const identifiers = new Set();\n for (const hotspot of data.hotspotChoices) {\n if (!hotspot.identifier) {\n errors.push('All hotspot choices must have an identifier');\n }\n else if (identifiers.has(hotspot.identifier)) {\n errors.push(`Duplicate hotspot identifier: ${hotspot.identifier}`);\n }\n else {\n identifiers.add(hotspot.identifier);\n }\n if (!hotspot.coords) {\n errors.push(`Hotspot ${hotspot.identifier} must have coords`);\n }\n }\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI hotspotInteraction extractor\n *\n * Extracts data from hotspotInteraction elements (clickable areas on image)\n */\nimport { normalizePixelDimension } from '../../security/styleValues.js';\n/**\n * Standard QTI hotspot interaction extractor\n * Handles hotspotInteraction elements (clickable areas on an image)\n */\nexport const standardHotspotExtractor = {\n id: 'qti:hotspot-interaction',\n name: 'QTI Standard Hotspot Interaction',\n priority: 10,\n elementTypes: ['hotspotInteraction'],\n description: 'Extracts standard QTI hotspotInteraction (clickable areas on image)',\n canHandle(element, context) {\n // All hotspotInteraction elements are standard\n return context.utils.matchesTag(element, 'hotspotInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract image data from object element\n const objectElements = utils.getChildrenByTag(element, 'object');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''));\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''));\n if (type.startsWith('image/svg')) {\n // Inline SVG: <object type=\"image/svg+xml\"><svg>...</svg></object>\n // External SVG: <object type=\"image/svg+xml\" data=\"path/to/file.svg\"/>\n // The <object> may contain alt text (not SVG markup) — only treat as inline if content has <svg.\n const content = utils.getHtmlContent(objectElement);\n const hasSvgMarkup = /<svg[\\s>]/i.test(content);\n if (hasSvgMarkup) {\n imageData = {\n type: 'svg',\n content,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n else {\n // External SVG file reference — render via <img src> (SVG renders in img tags)\n imageData = {\n type: 'image',\n src: data,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n }\n else {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n ...(width ? { width } : {}),\n ...(height ? { height } : {}),\n };\n }\n }\n // Extract hotspotChoice children\n const hotspotElements = utils.getChildrenByTag(element, 'hotspotChoice');\n const hotspotChoices = hotspotElements.map((hotspot) => {\n const classes = utils.getClasses(hotspot);\n const shape = utils.getAttribute(hotspot, 'shape', 'rect');\n const coords = utils.getAttribute(hotspot, 'coords', '');\n const hotspotLabel = utils.getAttribute(hotspot, 'hotspotLabel', '');\n return {\n identifier: utils.getAttribute(hotspot, 'identifier', ''),\n shape: shape,\n coords,\n ...(hotspotLabel ? { hotspotLabel } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract attributes\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n const interactionClasses = utils.getClasses(element);\n const maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n imageData,\n hotspotChoices,\n maxChoices,\n ...(minChoices > 0 ? { minChoices } : {}),\n prompt,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate image data\n if (!data.imageData) {\n warnings.push('hotspotInteraction has no image data');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('hotspotInteraction must have an image URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('hotspotInteraction must have SVG content');\n }\n // Validate hotspots exist\n if (!data.hotspotChoices || data.hotspotChoices.length === 0) {\n errors.push('hotspotInteraction must have at least one hotspot');\n }\n // Validate hotspot identifiers and coords\n if (data.hotspotChoices && data.hotspotChoices.length > 0) {\n const identifiers = new Set();\n for (const hotspot of data.hotspotChoices) {\n if (!hotspot.identifier) {\n errors.push('All hotspots must have an identifier');\n }\n else if (identifiers.has(hotspot.identifier)) {\n errors.push(`Duplicate hotspot identifier: ${hotspot.identifier}`);\n }\n else {\n identifiers.add(hotspot.identifier);\n }\n if (!hotspot.coords) {\n errors.push(`Hotspot ${hotspot.identifier} must have coords`);\n }\n }\n // Warn if maxChoices exceeds hotspot count\n if (data.maxChoices > data.hotspotChoices.length) {\n warnings.push(`maxChoices (${data.maxChoices}) exceeds the number of hotspots (${data.hotspotChoices.length})`);\n }\n }\n // Validate maxChoices\n if (data.maxChoices < 0) {\n errors.push('maxChoices must be non-negative');\n }\n // Validate minChoices\n if (data.minChoices !== undefined && data.minChoices < 0) {\n errors.push('minChoices must be non-negative');\n }\n // Validate minChoices <= maxChoices\n if (data.minChoices !== undefined &&\n data.maxChoices > 0 &&\n data.minChoices > data.maxChoices) {\n errors.push('minChoices cannot exceed maxChoices');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI hottextInteraction extractor\n *\n * Extracts data from hottextInteraction elements (select text spans)\n */\nimport { sanitizeHtml } from '../../core/sanitizer.js';\n/**\n * Standard QTI hottext interaction extractor\n * Handles hottextInteraction elements (selectable text spans)\n */\nexport const standardHottextExtractor = {\n id: 'qti:hottext-interaction',\n name: 'QTI Standard Hottext Interaction',\n priority: 10,\n elementTypes: ['hottextInteraction'],\n description: 'Extracts standard QTI hottextInteraction (select text spans)',\n canHandle(element, _context) {\n // All hottextInteraction elements are standard\n return element.rawTagName === 'hottextInteraction' || element.rawTagName === 'qti-hottext-interaction';\n },\n extract(element, context) {\n const { utils } = context;\n // Extract hottext children (selectable text spans) - recursively search entire tree\n const findHottextElements = (el) => {\n const results = [];\n if (el.rawTagName === 'hottext' || el.rawTagName === 'qti-hottext') {\n results.push(el);\n }\n if (el.childNodes) {\n for (const child of el.childNodes) {\n if (typeof child !== 'string') {\n results.push(...findHottextElements(child));\n }\n }\n }\n return results;\n };\n const hottextElements = findHottextElements(element);\n const hottextChoices = hottextElements.map((hottext) => {\n const classes = utils.getClasses(hottext);\n return {\n identifier: utils.getAttribute(hottext, 'identifier', ''),\n text: utils.getTextContent(hottext),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract attributes\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n const interactionClasses = utils.getClasses(element);\n const maxSelectionsMessage = utils.getAttribute(element, 'data-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-min-selections-message', '') || null;\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n // Extract content HTML (all content except prompt)\n let contentHtml = '';\n for (const child of element.childNodes) {\n // Skip prompt elements\n if (typeof child !== 'string' &&\n child.rawTagName !== 'prompt' &&\n child.rawTagName !== 'qti-prompt') {\n contentHtml += child.outerHTML || child.toString();\n }\n else if (typeof child === 'string') {\n contentHtml += child;\n }\n }\n // Sanitize extracted HTML before rendering via {@html} in the component.\n contentHtml = sanitizeHtml(contentHtml, { security: context.config.security });\n return {\n hottextChoices,\n contentHtml,\n maxChoices,\n minChoices,\n prompt,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate hottextChoices exist\n if (!data.hottextChoices || data.hottextChoices.length === 0) {\n errors.push('hottextInteraction must have at least one hottext');\n }\n // Validate hottext identifiers\n if (data.hottextChoices) {\n const identifiers = new Set();\n for (const hottext of data.hottextChoices) {\n if (!hottext.identifier) {\n errors.push('All hottext elements must have an identifier');\n }\n else if (identifiers.has(hottext.identifier)) {\n errors.push(`Duplicate hottext identifier: ${hottext.identifier}`);\n }\n else {\n identifiers.add(hottext.identifier);\n }\n }\n }\n // Validate maxChoices\n if (data.maxChoices < 0) {\n errors.push('maxChoices must be non-negative');\n }\n // Warn if maxChoices exceeds hottext count\n if (data.hottextChoices && data.maxChoices > data.hottextChoices.length) {\n warnings.push(`maxChoices (${data.maxChoices}) exceeds the number of hottext choices (${data.hottextChoices.length})`);\n }\n // Validate minChoices\n if (data.minChoices !== undefined && data.minChoices < 0) {\n errors.push('minChoices must be non-negative');\n }\n // Validate minChoices <= maxChoices\n if (data.minChoices !== undefined &&\n data.maxChoices > 0 &&\n data.minChoices > data.maxChoices) {\n warnings.push(`minChoices (${data.minChoices}) exceeds maxChoices (${data.maxChoices}); rendering interaction with authoring constraint warning`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI inlineChoiceInteraction extractor\n *\n * Extracts data from inlineChoiceInteraction elements (dropdown in text)\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\n/**\n * Standard QTI inline choice interaction extractor\n * Handles inlineChoiceInteraction elements (dropdown selections within text)\n */\nexport const standardInlineChoiceExtractor = {\n id: 'qti:inline-choice-interaction',\n name: 'QTI Standard Inline Choice Interaction',\n priority: 10,\n elementTypes: ['inlineChoiceInteraction'],\n description: 'Extracts standard QTI inlineChoiceInteraction (dropdown in text)',\n canHandle(element, _context) {\n // All inlineChoiceInteraction elements are standard\n return element.rawTagName === 'inlineChoiceInteraction' || element.rawTagName === 'qti-inline-choice-interaction';\n },\n extract(element, context) {\n const { utils } = context;\n // Extract choices (inlineChoice children)\n const inlineChoices = utils.getChildrenByTag(element, 'inlineChoice');\n const choices = inlineChoices.map((choice) => {\n const fixed = utils.getBooleanAttribute(choice, 'fixed');\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getTextContent(choice),\n ...(fixed ? { fixed } : {}),\n };\n });\n // Extract <label> child — used as placeholder text in the dropdown\n const labelElements = utils.getChildrenByTag(element, 'label');\n const label = labelElements.length > 0 ? utils.getTextContent(labelElements[0]) : null;\n // data-prompt: alternative placeholder for the dropdown default option\n const dataPrompt = utils.getAttribute(element, 'data-prompt', '') || null;\n // Extract attributes\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const interactionClasses = utils.getClasses(element);\n return {\n choices: maybeShuffle(choices, shuffle, context.shuffleRng),\n shuffle,\n label,\n ...(dataPrompt ? { dataPrompt } : {}),\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate choices exist\n if (!data.choices || data.choices.length === 0) {\n errors.push('inlineChoiceInteraction must have at least one choice');\n }\n // Validate choice identifiers\n if (data.choices) {\n const identifiers = new Set();\n for (const choice of data.choices) {\n if (!choice.identifier) {\n errors.push('All choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate choice identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n }\n // Warn if too many choices\n if (data.choices.length >= 10) {\n warnings.push(`inlineChoiceInteraction has ${data.choices.length} choices - consider limiting for better usability`);\n }\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI matchInteraction extractor\n *\n * Extracts data from matchInteraction elements (matching pairs)\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\n/**\n * Standard QTI match interaction extractor\n * Handles matchInteraction elements (matching pairs between two sets)\n */\nexport const standardMatchExtractor = {\n id: 'qti:match-interaction',\n name: 'QTI Standard Match Interaction',\n priority: 10,\n elementTypes: ['matchInteraction'],\n description: 'Extracts standard QTI matchInteraction (matching pairs)',\n canHandle(element, _context) {\n // All matchInteraction elements are standard (both QTI 2.x and 3.0)\n return element.rawTagName === 'matchInteraction' || element.rawTagName === 'qti-match-interaction';\n },\n extract(element, context) {\n const { utils } = context;\n // Extract all simpleAssociableChoice children\n const allChoices = utils.getChildrenByTag(element, 'simpleAssociableChoice');\n // Determine which are source vs target based on matchSet structure\n // In QTI, matchInteraction can have two simpleMatchSet elements\n const matchSets = utils.getChildrenByTag(element, 'simpleMatchSet');\n let sourceSet = [];\n let targetSet = [];\n if (matchSets.length >= 2) {\n // Extract choices from first matchSet (source)\n const sourceMatchSet = matchSets[0];\n const sourceElements = utils.getChildrenByTag(sourceMatchSet, 'simpleAssociableChoice');\n sourceSet = sourceElements.map((choice) => {\n const classes = utils.getClasses(choice);\n const matchMax = utils.getNumberAttribute(choice, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(choice, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(choice, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract choices from second matchSet (target)\n const targetMatchSet = matchSets[1];\n const targetElements = utils.getChildrenByTag(targetMatchSet, 'simpleAssociableChoice');\n targetSet = targetElements.map((choice) => {\n const classes = utils.getClasses(choice);\n const matchMax = utils.getNumberAttribute(choice, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(choice, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(choice, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n }\n else {\n // Fallback: treat all choices as both source and target\n const extractedChoices = allChoices.map((choice) => {\n const classes = utils.getClasses(choice);\n const matchMax = utils.getNumberAttribute(choice, 'matchMax', 1);\n const matchMin = utils.getNumberAttribute(choice, 'matchMin', 0);\n const matchGroupRaw = utils.getAttribute(choice, 'matchGroup', '');\n const matchGroup = matchGroupRaw.split(/\\s+/).filter(Boolean);\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n matchMax,\n ...(matchMin > 0 ? { matchMin } : {}),\n ...(matchGroup.length > 0 ? { matchGroup } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n sourceSet = extractedChoices;\n targetSet = extractedChoices;\n }\n // Extract attributes\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const maxAssociations = utils.getNumberAttribute(element, 'maxAssociations', 1);\n const minAssociationsRaw = utils.getNumberAttribute(element, 'minAssociations', 0);\n const minAssociations = minAssociationsRaw > 0 ? minAssociationsRaw : undefined;\n const interactionClasses = utils.getClasses(element);\n const maxSelectionsMessage = utils.getAttribute(element, 'data-qti-max-selections-message', '') || null;\n const minSelectionsMessage = utils.getAttribute(element, 'data-qti-min-selections-message', '') || null;\n const firstColumnHeader = utils.getAttribute(element, 'data-qti-first-column-header', '') || null;\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n sourceSet: maybeShuffle(sourceSet, shuffle, context.shuffleRng),\n targetSet: maybeShuffle(targetSet, shuffle, context.shuffleRng),\n shuffle,\n maxAssociations,\n ...(minAssociations !== undefined ? { minAssociations } : {}),\n prompt,\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(maxSelectionsMessage ? { maxSelectionsMessage } : {}),\n ...(minSelectionsMessage ? { minSelectionsMessage } : {}),\n ...(firstColumnHeader ? { firstColumnHeader } : {}),\n };\n },\n validate(data) {\n const errors = [];\n // Validate source choices exist\n if (!data.sourceSet || data.sourceSet.length === 0) {\n errors.push('matchInteraction must have at least one source choice');\n }\n // Validate target choices exist\n if (!data.targetSet || data.targetSet.length === 0) {\n errors.push('matchInteraction must have at least one target choice');\n }\n // Validate choice identifiers\n if (data.sourceSet) {\n const identifiers = new Set();\n for (const choice of data.sourceSet) {\n if (!choice.identifier) {\n errors.push('All source choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate source identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n }\n }\n if (data.targetSet) {\n const identifiers = new Set();\n for (const choice of data.targetSet) {\n if (!choice.identifier) {\n errors.push('All target choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate target identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n }\n }\n // Validate maxAssociations\n if (data.maxAssociations < 0) {\n errors.push('maxAssociations must be non-negative');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI mediaInteraction extractor\n *\n * Extracts data from mediaInteraction elements (video/audio playback)\n */\n/**\n * Standard QTI media interaction extractor\n * Handles mediaInteraction elements (video/audio playback with interaction)\n */\nexport const standardMediaExtractor = {\n id: 'qti:media-interaction',\n name: 'QTI Standard Media Interaction',\n priority: 10,\n elementTypes: ['mediaInteraction'],\n description: 'Extracts standard QTI mediaInteraction (video/audio playback)',\n canHandle(element, context) {\n // All mediaInteraction elements are standard\n return context.utils.matchesTag(element, 'mediaInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract attributes\n const autostart = utils.getBooleanAttribute(element, 'autostart', false);\n const minPlays = utils.getNumberAttribute(element, 'minPlays', 0);\n const maxPlays = utils.getNumberAttribute(element, 'maxPlays', 0);\n const loop = utils.getBooleanAttribute(element, 'loop', false);\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n // Extract media element (audio, video, or object)\n let mediaElement = null;\n // Check for audio element\n const audioElements = utils.getChildrenByTag(element, 'audio');\n if (audioElements.length > 0) {\n const audioElement = audioElements[0];\n const sourceElements = utils.getChildrenByTag(audioElement, 'source');\n if (sourceElements.length === 0) {\n throw new Error('audio element must contain at least one source element');\n }\n const firstSource = sourceElements[0];\n mediaElement = {\n type: 'audio',\n src: utils.getAttribute(firstSource, 'src', ''),\n mimeType: utils.getAttribute(firstSource, 'type', ''),\n };\n }\n // Check for video element\n const videoElements = utils.getChildrenByTag(element, 'video');\n if (videoElements.length > 0) {\n const videoElement = videoElements[0];\n const sourceElements = utils.getChildrenByTag(videoElement, 'source');\n if (sourceElements.length === 0) {\n throw new Error('video element must contain at least one source element');\n }\n const firstSource = sourceElements[0];\n const width = utils.getNumberAttribute(videoElement, 'width', 640);\n const height = utils.getNumberAttribute(videoElement, 'height', 480);\n mediaElement = {\n type: 'video',\n src: utils.getAttribute(firstSource, 'src', ''),\n mimeType: utils.getAttribute(firstSource, 'type', ''),\n width,\n height,\n };\n }\n // Check for object element\n const objectElements = utils.getChildrenByTag(element, 'object');\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const data = utils.getAttribute(objectElement, 'data', '');\n if (!data) {\n throw new Error('object element must have data attribute');\n }\n const width = utils.getNumberAttribute(objectElement, 'width', 0);\n const height = utils.getNumberAttribute(objectElement, 'height', 0);\n mediaElement = {\n type: 'object',\n src: data,\n mimeType: utils.getAttribute(objectElement, 'type', ''),\n ...(width > 0 ? { width } : {}),\n ...(height > 0 ? { height } : {}),\n };\n }\n // Throw error if no media element found\n if (!mediaElement) {\n throw new Error('mediaInteraction must contain audio, video, or object element');\n }\n return {\n mediaElement,\n autostart,\n minPlays,\n maxPlays,\n loop,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate media element exists\n if (!data.mediaElement) {\n errors.push('mediaInteraction must have a mediaElement');\n }\n // Validate play constraints\n if (data.minPlays < 0) {\n errors.push('minPlays must be non-negative');\n }\n if (data.maxPlays < 0) {\n errors.push('maxPlays must be non-negative');\n }\n // Validate minPlays <= maxPlays (when maxPlays > 0, as 0 means unlimited)\n if (data.maxPlays > 0 && data.minPlays > data.maxPlays) {\n errors.push(`maxPlays (${data.maxPlays}) must be greater than or equal to minPlays (${data.minPlays})`);\n }\n // Warn if loop is true with maxPlays\n if (data.loop && data.maxPlays > 0) {\n warnings.push('mediaInteraction has loop=true with maxPlays - loop may be ignored');\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI orderInteraction extractor\n *\n * Extracts data from orderInteraction elements (ordering/ranking tasks)\n */\nimport { maybeShuffle } from '../../core/shuffle.js';\n/**\n * Standard QTI order interaction extractor\n * Handles orderInteraction elements with simpleChoice children\n */\nexport const standardOrderExtractor = {\n id: 'qti:order-interaction',\n name: 'QTI Standard Order Interaction',\n priority: 10,\n elementTypes: ['orderInteraction'],\n description: 'Extracts standard QTI orderInteraction (ordering/ranking tasks)',\n canHandle(element, context) {\n // Standard QTI order interactions have simpleChoice children\n return context.utils.hasChildWithTag(element, 'simpleChoice');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract choices\n const simpleChoices = utils.getChildrenByTag(element, 'simpleChoice');\n const choices = simpleChoices.map((choice) => {\n const classes = utils.getClasses(choice);\n const fixed = utils.getBooleanAttribute(choice, 'fixed');\n return {\n identifier: utils.getAttribute(choice, 'identifier', ''),\n text: utils.getHtmlContent(choice),\n ...(fixed ? { fixed } : {}),\n ...(classes.length > 0 ? { classes } : {}),\n };\n });\n // Extract prompt\n const promptElement = utils.querySelector(element, 'prompt');\n const prompt = promptElement ? utils.getHtmlContent(promptElement) : null;\n // Extract attributes\n const shuffle = utils.getBooleanAttribute(element, 'shuffle');\n const orientation = utils.getAttribute(element, 'orientation', 'vertical');\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 0);\n return {\n choices: maybeShuffle(choices, shuffle, context.shuffleRng),\n shuffle,\n orientation,\n minChoices,\n maxChoices,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate choices exist\n if (!data.choices || data.choices.length < 2) {\n errors.push('orderInteraction must have at least 2 choices');\n }\n // Warn if too many choices (difficult to order)\n if (data.choices && data.choices.length > 10) {\n warnings.push(`orderInteraction has ${data.choices.length} choices - this may be difficult for users to order`);\n }\n // Validate choice identifiers\n if (data.choices) {\n const identifiers = new Set();\n for (const choice of data.choices) {\n if (!choice.identifier) {\n errors.push('All choices must have an identifier');\n }\n else if (identifiers.has(choice.identifier)) {\n errors.push(`Duplicate choice identifier: ${choice.identifier}`);\n }\n else {\n identifiers.add(choice.identifier);\n }\n }\n }\n // Validate orientation (only if provided)\n if (data.orientation) {\n const validOrientations = ['vertical', 'horizontal'];\n if (!validOrientations.includes(data.orientation)) {\n warnings.push(`orientation '${data.orientation}' is not standard (expected: ${validOrientations.join(', ')})`);\n }\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","import { normalizePixelDimension } from '../../security/styleValues.js';\nfunction imageDataFromObject(objectElement, utils, defaultWidth, defaultHeight) {\n if (!objectElement)\n return null;\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''), defaultWidth);\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''), defaultHeight);\n const content = utils.getHtmlContent(objectElement);\n if (type.startsWith('image/svg') && /<svg[\\s>]/i.test(content)) {\n return { type: 'svg', content, width, height };\n }\n return { type: 'image', src: data, width, height };\n}\nexport const standardPositionObjectExtractor = {\n id: 'qti:position-object-interaction',\n name: 'QTI Standard Position Object Interaction',\n priority: 10,\n elementTypes: ['positionObjectInteraction'],\n description: 'Extracts a positionObjectInteraction from its parent positionObjectStage',\n canHandle(element) {\n const tagName = element.rawTagName?.toLowerCase();\n return tagName === 'positionobjectinteraction' || tagName === 'qti-position-object-interaction';\n },\n extract(element, context) {\n const { utils, responseId } = context;\n const parent = element.parentNode;\n const parentTagName = parent?.rawTagName?.toLowerCase();\n const isPositionObjectStage = parentTagName === 'positionobjectstage' || parentTagName === 'qti-position-object-stage';\n const stage = parent && isPositionObjectStage && utils.getChildrenByTag(parent, 'positionObjectInteraction').includes(element)\n ? parent\n : undefined;\n const backgroundObject = stage ? utils.getChildrenByTag(stage, 'object')[0] : undefined;\n const draggableObject = utils.getChildrenByTag(element, 'object')[0];\n const imageData = imageDataFromObject(backgroundObject, utils, '500', '300');\n const objectData = imageDataFromObject(draggableObject, utils, '50', '50');\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n const label = utils.getTextContent(draggableObject).trim() || responseId;\n const classes = utils.getClasses(element);\n const prompt = utils.getPrompt(element);\n return {\n imageData,\n positionObjectStages: [\n {\n identifier: responseId,\n label,\n matchMax: maxChoices,\n objectData,\n ...(classes.length > 0 ? { classes } : {}),\n },\n ],\n // The renderer currently represents the QTI default (the object's centre)\n // as a boolean. Explicit centre coordinates remain a follow-up API change.\n centerPoint: true,\n maxChoices,\n minChoices,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n if (!data.imageData) {\n errors.push('positionObjectInteraction must have a parent positionObjectStage with a background object');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('positionObjectStage background object must have a data URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('positionObjectStage background object must have SVG content');\n }\n const draggable = data.positionObjectStages[0];\n if (!draggable?.objectData) {\n errors.push('positionObjectInteraction must contain one draggable object');\n }\n else if (draggable.objectData.type === 'image' && !draggable.objectData.src) {\n errors.push('positionObjectInteraction draggable object must have a data URL');\n }\n if (data.maxChoices < 0)\n errors.push('maxChoices must be non-negative');\n if (data.minChoices < 0)\n errors.push('minChoices must be non-negative');\n if (data.maxChoices > 0 && data.minChoices > data.maxChoices) {\n errors.push('minChoices cannot exceed maxChoices');\n }\n if (data.imageData?.type === 'image') {\n warnings.push('Ensure the declared positionObjectStage width/height match the image dimensions. ' +\n `Declared: ${data.imageData.width || 'unspecified'}×${data.imageData.height || 'unspecified'}`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Extractor for <qti-portable-custom-interaction> (QTI 3.0) and the\n * namespaced <pci:portableCustomInteraction> payload inside a QTI 2.x\n * <customInteraction> wrapper.\n *\n * Extracts the module paths, markup, and config properties needed by PciHost\n * to load and initialize the PCI JavaScript module.\n *\n * Priority 20 > standardCustomExtractor priority 10, so this runs first when\n * both would match the same element.\n */\nexport const portableCustomExtractor = {\n id: 'qti:portable-custom-interaction',\n name: 'QTI Portable Custom Interaction',\n outputType: 'portableCustomInteraction',\n priority: 20,\n elementTypes: [\n 'customInteraction',\n 'portableCustomInteraction',\n 'qti-portable-custom-interaction',\n ],\n description: 'Extracts QTI 2.x/3.0 portable custom interaction module paths, markup, and config',\n canHandle(element, _context) {\n const tag = localTagName(element);\n return (tag === 'portablecustominteraction' ||\n tag === 'qti-portable-custom-interaction' ||\n (tag === 'custominteraction' && findDescendant(element, ['portablecustominteraction']) !== null));\n },\n extract(element, context) {\n const { utils } = context;\n const outerTag = localTagName(element);\n const pciElement = outerTag === 'custominteraction'\n ? findDescendant(element, ['portablecustominteraction'])\n : element;\n if (!pciElement) {\n throw new Error('customInteraction does not contain a portableCustomInteraction payload');\n }\n const responseIdentifier = utils.getAttribute(element, 'responseIdentifier') ||\n utils.getAttribute(element, 'response-identifier') ||\n context.responseId ||\n '';\n const customInteractionTypeIdentifier = utils.getAttribute(pciElement, 'customInteractionTypeIdentifier') ||\n utils.getAttribute(pciElement, 'custom-interaction-type-identifier') ||\n utils.getAttribute(pciElement, 'customInteractionIdentifierType') ||\n utils.getAttribute(pciElement, 'custom-interaction-identifier-type') ||\n '';\n // --- Module paths from <qti-interaction-modules>/<qti-interaction-module> ---\n // These element names ARE in the standard QTI 3.0 element mapper so utils.querySelector works.\n let primaryPath = '';\n let fallbackPath;\n const modulesEl = findDescendant(pciElement, ['interactionmodules', 'qti-interaction-modules']);\n if (modulesEl) {\n const moduleEl = findDescendant(modulesEl, ['interactionmodule', 'qti-interaction-module']);\n if (moduleEl) {\n primaryPath =\n utils.getAttribute(moduleEl, 'primaryPath') ||\n utils.getAttribute(moduleEl, 'primary-path') || '';\n const fb = utils.getAttribute(moduleEl, 'fallbackPath') ||\n utils.getAttribute(moduleEl, 'fallback-path') || '';\n if (fb)\n fallbackPath = fb;\n }\n }\n // QTI 2.x PCI v1.0 embeds one or more script hooks in <pci:instance>.\n // The first external script identifies the resource a host resolver must map.\n const instanceEl = findDescendant(pciElement, ['instance']);\n if (!primaryPath && instanceEl) {\n const externalScript = findDescendants(instanceEl, ['script']).find((script) => Boolean(utils.getAttribute(script, 'src')));\n primaryPath = externalScript ? utils.getAttribute(externalScript, 'src') : '';\n }\n // --- Markup from <qti-interaction-markup> ---\n const markupEl = findDescendant(pciElement, ['interactionmarkup', 'qti-interaction-markup']);\n // sanitizeHtml removes script hooks from the QTI 2.x instance while preserving\n // the authored DOM scaffold that the resolved module initializes.\n const markupSource = markupEl ?? instanceEl;\n const markup = markupSource ? utils.getHtmlContent(markupSource) : '';\n // --- Config from <qti-pci-properties>/<qti-pci-property> ---\n // qti-pci-properties is NOT in the standard QTI 3.0 element mapper, so we use the\n // native node-html-parser querySelector (available as element.querySelector on the raw element).\n const config = {};\n const propsEl = findDescendant(pciElement, ['pciproperties', 'qti-pci-properties']);\n if (propsEl) {\n const propEls = findDescendants(propsEl, ['pciproperty', 'qti-pci-property']);\n for (const propEl of propEls) {\n const key = utils.getAttribute(propEl, 'key') || utils.getAttribute(propEl, 'name') || '';\n const value = utils.getAttribute(propEl, 'value') || (propEl.textContent ?? '').trim() || '';\n if (key)\n config[key] = value;\n }\n }\n return {\n responseIdentifier,\n customInteractionTypeIdentifier,\n primaryPath,\n fallbackPath,\n markup,\n config,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n if (!data.responseIdentifier) {\n errors.push('portableCustomInteraction is missing responseIdentifier');\n }\n if (!data.customInteractionTypeIdentifier) {\n warnings.push('portableCustomInteraction is missing customInteractionTypeIdentifier');\n }\n if (!data.primaryPath) {\n errors.push('portableCustomInteraction has no primaryPath in qti-interaction-modules');\n }\n return { valid: errors.length === 0, errors: errors.length ? errors : undefined, warnings: warnings.length ? warnings : undefined };\n },\n};\nfunction localTagName(element) {\n const raw = element.rawTagName?.toLowerCase() ?? '';\n return raw.includes(':') ? raw.slice(raw.lastIndexOf(':') + 1) : raw;\n}\nfunction findDescendant(element, localNames) {\n return findDescendants(element, localNames)[0] ?? null;\n}\nfunction findDescendants(element, localNames) {\n const expected = new Set(localNames.map((name) => name.toLowerCase()));\n const matches = [];\n const visit = (parent) => {\n for (const child of parent.childNodes ?? []) {\n const candidate = child;\n if (!candidate.rawTagName)\n continue;\n if (expected.has(localTagName(candidate)))\n matches.push(candidate);\n visit(candidate);\n }\n };\n visit(element);\n return matches;\n}\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI selectPointInteraction extractor\n *\n * Extracts data from selectPointInteraction elements (click point on image)\n */\nimport { normalizePixelDimension } from '../../security/styleValues.js';\n/**\n * Standard QTI select point interaction extractor\n * Handles selectPointInteraction elements (clicking points on an image)\n */\nexport const standardSelectPointExtractor = {\n id: 'qti:select-point-interaction',\n name: 'QTI Standard Select Point Interaction',\n priority: 10,\n elementTypes: ['selectPointInteraction'],\n description: 'Extracts standard QTI selectPointInteraction (click point on image)',\n canHandle(element, context) {\n // All selectPointInteraction elements are standard\n return context.utils.matchesTag(element, 'selectPointInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract image data from object or img element\n const objectElements = utils.getChildrenByTag(element, 'object');\n const imgElements = utils.getChildrenByTag(element, 'img');\n let imageData = null;\n if (objectElements.length > 0) {\n const objectElement = objectElements[0];\n const type = utils.getAttribute(objectElement, 'type', '');\n const data = utils.getAttribute(objectElement, 'data', '');\n const width = normalizePixelDimension(utils.getAttribute(objectElement, 'width', ''), '500');\n const height = normalizePixelDimension(utils.getAttribute(objectElement, 'height', ''), '300');\n if (type.startsWith('image/svg')) {\n // Extract inline SVG content - get full content including <svg> tag\n const content = utils.getHtmlContent(objectElement);\n imageData = {\n type: 'svg',\n content,\n width,\n height,\n };\n }\n else {\n // External image reference\n imageData = {\n type: 'image',\n src: data,\n width,\n height,\n };\n }\n }\n else if (imgElements.length > 0) {\n // Handle img element as fallback\n const imgElement = imgElements[0];\n const src = utils.getAttribute(imgElement, 'src', '');\n const width = normalizePixelDimension(utils.getAttribute(imgElement, 'width', ''), '500');\n const height = normalizePixelDimension(utils.getAttribute(imgElement, 'height', ''), '300');\n imageData = {\n type: 'image',\n src,\n width,\n height,\n };\n }\n // Extract attributes\n const maxChoices = utils.getNumberAttribute(element, 'maxChoices', 1);\n const minChoices = utils.getNumberAttribute(element, 'minChoices', 0);\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n imageData,\n maxChoices,\n minChoices,\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate image data\n if (!data.imageData) {\n warnings.push('selectPointInteraction has no image data');\n }\n else if (data.imageData.type === 'image' && !data.imageData.src) {\n errors.push('selectPointInteraction must have an image URL');\n }\n else if (data.imageData.type === 'svg' && !data.imageData.content) {\n errors.push('selectPointInteraction must have SVG content');\n }\n // Validate maxChoices — 0 means unlimited per QTI spec\n if (data.maxChoices < 0) {\n errors.push('maxChoices must be non-negative');\n }\n // Validate minChoices\n if (data.minChoices < 0) {\n errors.push('minChoices must be non-negative');\n }\n // Validate minChoices <= maxChoices (skip when maxChoices=0, meaning unlimited)\n if (data.maxChoices > 0 && data.minChoices > data.maxChoices) {\n errors.push(`minChoices (${data.minChoices}) must be less than or equal to maxChoices (${data.maxChoices})`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI sliderInteraction extractor\n *\n * Extracts data from sliderInteraction elements (slider input)\n */\n/**\n * Standard QTI slider interaction extractor\n * Handles sliderInteraction elements (slider for numeric input)\n */\nexport const standardSliderExtractor = {\n id: 'qti:slider-interaction',\n name: 'QTI Standard Slider Interaction',\n priority: 10,\n elementTypes: ['sliderInteraction'],\n description: 'Extracts standard QTI sliderInteraction (slider input)',\n canHandle(element, context) {\n // All sliderInteraction elements are standard\n return context.utils.matchesTag(element, 'sliderInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract required attributes\n const lowerBound = utils.getNumberAttribute(element, 'lowerBound', 0);\n const upperBound = utils.getNumberAttribute(element, 'upperBound', 100);\n const step = utils.getNumberAttribute(element, 'step', 1);\n const orientation = utils.getAttribute(element, 'orientation', 'horizontal');\n const reverse = utils.getBooleanAttribute(element, 'reverse', false);\n // Extract optional attributes\n const stepLabel = utils.getBooleanAttribute(element, 'stepLabel');\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n lowerBound,\n upperBound,\n step,\n orientation,\n reverse,\n ...(stepLabel ? { stepLabel } : {}),\n prompt,\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate bounds\n if (data.lowerBound >= data.upperBound) {\n errors.push('lowerBound must be less than upperBound');\n }\n // Validate step\n if (data.step <= 0) {\n errors.push('step must be greater than 0');\n }\n // Validate orientation\n if (data.orientation && !['horizontal', 'vertical'].includes(data.orientation)) {\n errors.push('orientation must be \"horizontal\" or \"vertical\"');\n }\n // Warn if step is larger than range\n const range = data.upperBound - data.lowerBound;\n if (data.step > range) {\n warnings.push(`step (${data.step}) is larger than the range (${range})`);\n }\n else if (range % data.step !== 0) {\n // Warn if step doesn't evenly divide range\n warnings.push(`step ${data.step} does not evenly divide range ${range} (${data.lowerBound} to ${data.upperBound})`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI textEntryInteraction extractor\n *\n * Extracts data from textEntryInteraction elements (inline text input)\n */\n/**\n * Standard QTI text entry interaction extractor\n * Handles textEntryInteraction elements (inline text input)\n */\nexport const standardTextEntryExtractor = {\n id: 'qti:text-entry-interaction',\n name: 'QTI Standard Text Entry Interaction',\n priority: 10,\n elementTypes: ['textEntryInteraction'],\n description: 'Extracts standard QTI textEntryInteraction (inline text input)',\n canHandle(element, _context) {\n // All textEntryInteraction elements are standard (both QTI 2.x and 3.0)\n return (element.rawTagName === 'textEntryInteraction' || element.rawTagName === 'qti-text-entry-interaction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract attributes\n const expectedLength = utils.getNumberAttribute(element, 'expectedLength', 20);\n const patternMask = utils.getAttribute(element, 'patternMask', '');\n const placeholderText = utils.getAttribute(element, 'placeholderText', '');\n const format = utils.getAttribute(element, 'format', '');\n const interactionClasses = utils.getClasses(element);\n const patternMaskMessage = utils.getAttribute(element, 'data-patternmask-message', '') || null;\n return {\n expectedLength,\n patternMask: patternMask || null,\n placeholderText,\n ...(format ? { format } : {}),\n ...(interactionClasses.length > 0 ? { interactionClasses } : {}),\n ...(patternMaskMessage ? { patternMaskMessage } : {}),\n };\n },\n validate(data) {\n const errors = [];\n const warnings = [];\n // Validate expectedLength\n if (data.expectedLength < 1) {\n errors.push('expectedLength must be positive');\n }\n if (data.expectedLength > 1000) {\n warnings.push(`expectedLength (${data.expectedLength}) is very large - consider using extendedTextInteraction`);\n }\n return {\n valid: errors.length === 0,\n errors: errors.length > 0 ? errors : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","/**\n * Standard QTI uploadInteraction extractor\n *\n * Extracts data from uploadInteraction elements (file upload)\n */\n/**\n * Standard QTI upload interaction extractor\n * Handles uploadInteraction elements (file upload)\n */\nexport const standardUploadExtractor = {\n id: 'qti:upload-interaction',\n name: 'QTI Standard Upload Interaction',\n priority: 10,\n elementTypes: ['uploadInteraction'],\n description: 'Extracts standard QTI uploadInteraction (file upload)',\n canHandle(element, context) {\n // All uploadInteraction elements are standard\n return context.utils.matchesTag(element, 'uploadInteraction');\n },\n extract(element, context) {\n const { utils } = context;\n // Extract fileType child elements (vendor / QTI 3.0 style)\n const fileTypeElements = utils.getChildrenByTag(element, 'fileType');\n let fileTypes = fileTypeElements.map((el) => utils.getTextContent(el));\n // Fall back to QTI 2.x `type` attribute when no <fileType> children are present\n if (fileTypes.length === 0) {\n const typeAttr = utils.getAttribute(element, 'type', '');\n if (typeAttr) {\n fileTypes = typeAttr.split(/\\s+/).filter(Boolean);\n }\n }\n // Extract all attributes\n const rawAttributes = {};\n if (element.attributes) {\n for (const [key, value] of Object.entries(element.attributes)) {\n rawAttributes[key] = String(value);\n }\n }\n // Extract prompt (optional)\n const promptElements = utils.getChildrenByTag(element, 'prompt');\n const prompt = promptElements.length > 0 ? utils.getHtmlContent(promptElements[0]) : null;\n return {\n fileTypes,\n rawAttributes,\n prompt,\n };\n },\n validate(data) {\n const warnings = [];\n // Warn if no file type restrictions\n if (!data.fileTypes || data.fileTypes.length === 0) {\n warnings.push('uploadInteraction has no fileTypes - any file type will be accepted');\n }\n return {\n valid: true,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n },\n};\n//# sourceMappingURL=extractor.js.map","import { htmlField, urlField, } from '../extraction/deliveryTypes.js';\nimport { standardAssociateExtractor } from './associate/extractor.js';\nimport { standardChoiceExtractor } from './choice/extractor.js';\nimport { standardCustomExtractor } from './custom/extractor.js';\nimport { standardDrawingExtractor } from './drawing/extractor.js';\nimport { standardEndAttemptExtractor } from './end-attempt/extractor.js';\nimport { standardExtendedTextExtractor } from './extended-text/extractor.js';\nimport { standardGapMatchExtractor } from './gap-match/extractor.js';\nimport { standardGraphicAssociateExtractor } from './graphic-associate/extractor.js';\nimport { standardGraphicGapMatchExtractor } from './graphic-gap-match/extractor.js';\nimport { standardGraphicOrderExtractor } from './graphic-order/extractor.js';\nimport { standardHotspotExtractor } from './hotspot/extractor.js';\nimport { standardHottextExtractor } from './hottext/extractor.js';\nimport { standardInlineChoiceExtractor } from './inline-choice/extractor.js';\nimport { standardMatchExtractor } from './match/extractor.js';\nimport { standardMediaExtractor } from './media/extractor.js';\nimport { standardOrderExtractor } from './order/extractor.js';\nimport { standardPositionObjectExtractor } from './position-object/extractor.js';\nimport { portableCustomExtractor } from './portable-custom/extractor.js';\nimport { standardSelectPointExtractor } from './select-point/extractor.js';\nimport { standardSliderExtractor } from './slider/extractor.js';\nimport { standardTextEntryExtractor } from './text-entry/extractor.js';\nimport { standardUploadExtractor } from './upload/extractor.js';\nconst prompt = htmlField('prompt');\nconst image = [\n htmlField('imageData', 'content'),\n urlField('img', 'imageData', 'src'),\n];\nconst STANDARD_INTERACTION_MODULE_DEFINITIONS = [\n {\n type: 'choiceInteraction',\n extractor: standardChoiceExtractor,\n placement: 'block',\n delivery: [prompt, htmlField('choices', '*', 'text')],\n },\n {\n type: 'textEntryInteraction',\n extractor: standardTextEntryExtractor,\n placement: 'inline',\n delivery: [],\n },\n {\n type: 'extendedTextInteraction',\n extractor: standardExtendedTextExtractor,\n placement: 'block',\n delivery: [prompt],\n },\n {\n type: 'inlineChoiceInteraction',\n extractor: standardInlineChoiceExtractor,\n placement: 'inline',\n delivery: [],\n },\n {\n type: 'orderInteraction',\n extractor: standardOrderExtractor,\n placement: 'block',\n delivery: [prompt, htmlField('choices', '*', 'text')],\n },\n {\n type: 'matchInteraction',\n extractor: standardMatchExtractor,\n placement: 'block',\n delivery: [\n prompt,\n htmlField('sourceSet', '*', 'text'),\n htmlField('targetSet', '*', 'text'),\n ],\n },\n {\n type: 'associateInteraction',\n extractor: standardAssociateExtractor,\n placement: 'block',\n delivery: [prompt, htmlField('choices', '*', 'text')],\n },\n {\n type: 'gapMatchInteraction',\n extractor: standardGapMatchExtractor,\n placement: 'block',\n delivery: [prompt, htmlField('promptText')],\n },\n {\n type: 'sliderInteraction',\n extractor: standardSliderExtractor,\n placement: 'block',\n delivery: [prompt],\n },\n {\n type: 'hotspotInteraction',\n extractor: standardHotspotExtractor,\n placement: 'block',\n delivery: [prompt, ...image],\n },\n {\n type: 'graphicGapMatchInteraction',\n extractor: standardGraphicGapMatchExtractor,\n placement: 'block',\n delivery: [prompt, ...image, urlField('img', 'gapImages', '*', 'src')],\n },\n {\n type: 'uploadInteraction',\n extractor: standardUploadExtractor,\n placement: 'block',\n delivery: [prompt],\n },\n {\n type: 'drawingInteraction',\n extractor: standardDrawingExtractor,\n placement: 'block',\n delivery: [prompt, ...image],\n },\n {\n type: 'customInteraction',\n extractor: standardCustomExtractor,\n placement: 'block',\n delivery: [prompt],\n },\n {\n type: 'portableCustomInteraction',\n extractor: portableCustomExtractor,\n placement: 'block',\n delivery: [htmlField('markup')],\n },\n {\n type: 'mediaInteraction',\n extractor: standardMediaExtractor,\n placement: 'block',\n delivery: [prompt, urlField('media-or-object', 'mediaElement', 'src')],\n },\n {\n type: 'hottextInteraction',\n extractor: standardHottextExtractor,\n placement: 'block',\n delivery: [prompt, htmlField('contentHtml')],\n },\n {\n type: 'selectPointInteraction',\n extractor: standardSelectPointExtractor,\n placement: 'block',\n delivery: [prompt, ...image],\n },\n {\n type: 'graphicOrderInteraction',\n extractor: standardGraphicOrderExtractor,\n placement: 'block',\n delivery: [prompt, ...image],\n },\n {\n type: 'graphicAssociateInteraction',\n extractor: standardGraphicAssociateExtractor,\n placement: 'block',\n delivery: [prompt, ...image],\n },\n {\n type: 'positionObjectInteraction',\n extractor: standardPositionObjectExtractor,\n placement: 'block',\n delivery: [\n prompt,\n ...image,\n htmlField('positionObjectStages', '*', 'objectData', 'content'),\n urlField('img', 'positionObjectStages', '*', 'objectData', 'src'),\n ],\n },\n {\n type: 'endAttemptInteraction',\n extractor: standardEndAttemptExtractor,\n placement: 'block',\n delivery: [prompt],\n },\n];\n/**\n * Immutable process-wide inventory. Definitions still snapshot its delivery\n * fields into their own sealed registry, so session behavior does not depend on\n * later access to this exported catalog.\n */\nexport const STANDARD_INTERACTION_MODULES = freezeStandardInteractionModules(STANDARD_INTERACTION_MODULE_DEFINITIONS);\nexport function getStandardInteractionModules() {\n return STANDARD_INTERACTION_MODULES;\n}\nexport function getStandardBlockInteractionModules() {\n return STANDARD_INTERACTION_MODULES.filter((module) => module.placement === 'block');\n}\nexport function getStandardInlineInteractionModules() {\n return STANDARD_INTERACTION_MODULES.filter((module) => module.placement === 'inline');\n}\nexport function getStandardInteractionExtractors() {\n return STANDARD_INTERACTION_MODULES.map((module) => module.extractor);\n}\nexport function getStandardInteractionElementTypes() {\n const elementTypes = new Set();\n for (const module of STANDARD_INTERACTION_MODULES) {\n for (const elementType of module.extractor.elementTypes) {\n elementTypes.add(elementType);\n }\n }\n return [...elementTypes];\n}\nconst STANDARD_TYPE_BY_LOWERCASE = new Map(STANDARD_INTERACTION_MODULES.map((module) => [module.type.toLowerCase(), module.type]));\nexport function normalizeInteractionTypeFromTagName(tagName) {\n const lowerTagName = tagName.toLowerCase();\n if (lowerTagName.startsWith('qti-')) {\n return lowerTagName.slice(4).replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());\n }\n return STANDARD_TYPE_BY_LOWERCASE.get(lowerTagName) ?? tagName;\n}\nexport function getStandardInteractionModule(type) {\n const normalizedType = normalizeInteractionTypeFromTagName(type);\n return STANDARD_INTERACTION_MODULES.find((module) => module.type === normalizedType) ?? null;\n}\nexport function isStandardInlineInteractionType(type) {\n return getStandardInteractionModule(type)?.placement === 'inline';\n}\nexport function isStandardBlockInteractionType(type) {\n return getStandardInteractionModule(type)?.placement === 'block';\n}\nexport function isStandardInlineInteractionTagName(tagName) {\n return isStandardInlineInteractionType(normalizeInteractionTypeFromTagName(tagName));\n}\nfunction freezeStandardInteractionModules(modules) {\n return Object.freeze(modules.map((module) => Object.freeze({\n ...module,\n delivery: Object.freeze(module.delivery.map((field) => Object.freeze({\n ...field,\n path: Object.freeze([...field.path]),\n }))),\n })));\n}\n//# sourceMappingURL=modules.js.map","import { childElements, findAssessmentItem, findDescendants, findFirstDescendant, getAttr, parseXml, serializeXml, } from '@pie-qti/qti-processing';\nimport { parse } from 'node-html-parser';\nimport { enforceItemXmlLimits } from '../core/parsingLimits.js';\nimport { normalizeInteractionTypeFromTagName } from '../interactions/modules.js';\nexport class AssessmentItemDocument {\n constructor({ itemXml, elementNameMapper, attributeNameMapper, security, }) {\n this.itemXml = itemXml;\n this.security = security;\n this.mathMlPrefixes = findMathMlPrefixes(itemXml);\n this.elementNameMapper = elementNameMapper;\n this.attributeNameMapper = attributeNameMapper;\n enforceItemXmlLimits(this.itemXml, this.security);\n this.xmlDocument = parseXml(this.itemXml);\n this.assessmentItem = findAssessmentItem(this.xmlDocument);\n this.extractionSource = this.serializeItemBodyForExtraction();\n }\n detectVersion() {\n const namespace = this.assessmentItem.namespaceURI;\n if (namespace?.includes('v3p0') || namespace?.includes('imsqtiasi_v3p0'))\n return '3.0';\n if (namespace?.includes('v2p2') || namespace?.includes('imsqti_v2p2'))\n return '2.2';\n if (namespace?.includes('v2p1') || namespace?.includes('imsqti_v2p1'))\n return '2.1';\n if (namespace?.includes('v2p0') || namespace?.includes('imsqti_v2p0'))\n return '2.0';\n const localName = this.assessmentItem.localName || this.assessmentItem.tagName;\n if (localName === 'qti-assessment-item' || localName === 'qti-assessment-test')\n return '3.0';\n const version = this.assessmentItem.getAttribute('version');\n if (version?.startsWith('3.'))\n return '3.0';\n if (version === '2.2' || version === '2.1' || version === '2.0')\n return version;\n return 'unknown';\n }\n getProcessingElement(kind) {\n const tagName = kind === 'template'\n ? 'templateprocessing'\n : kind === 'response'\n ? 'responseprocessing'\n : 'outcomeprocessing';\n return findFirstDescendant(this.assessmentItem, this.elementNameMapper.toNative(tagName));\n }\n serializeItemBodyChildren() {\n const itemBody = this.getItemBodyElement();\n if (!itemBody)\n return '';\n return this.serializeChildren(itemBody);\n }\n describeResponseProcessing() {\n const element = this.getProcessingElement('response');\n if (!element)\n return Object.freeze({ present: false, hasStatements: false });\n const template = getAttr(element, 'template')?.trim() || undefined;\n return Object.freeze({\n present: true,\n hasStatements: childElements(element).length > 0,\n ...(template ? { template } : {}),\n });\n }\n readRubricBlocks() {\n return this.findRubricElements().map((element) => {\n const view = (getAttr(element, 'view') || '').trim().split(/[\\s,]+/).filter(Boolean);\n const use = (getAttr(element, 'use') || '').trim() || undefined;\n return Object.freeze({\n view: Object.freeze(view),\n ...(use ? { use } : {}),\n scope: this.rubricElementScope(element),\n content: this.serializeChildren(element) || element.textContent || '',\n });\n });\n }\n readModalFeedback() {\n return this.findModalFeedbackElements().map((element) => {\n const identifier = this.getMappedAttribute(element, 'identifier') || '';\n const outcomeIdentifier = this.getMappedAttribute(element, 'outcomeIdentifier') || '';\n const showHide = (this.getMappedAttribute(element, 'showHide') || 'show');\n const title = this.getMappedAttribute(element, 'title') || undefined;\n return Object.freeze({\n identifier,\n outcomeIdentifier,\n showHide,\n ...(title ? { title } : {}),\n content: this.serializeChildren(element) || element.textContent || '',\n });\n });\n }\n getExtendedTextBase(responseIdentifier) {\n const interaction = this.findExtractionElements(['extendedTextInteraction']).find((candidate) => candidate.responseIdentifier === responseIdentifier);\n if (!interaction)\n return undefined;\n const base = Number(interaction.element.getAttribute?.('base') ?? 10);\n return Number.isInteger(base) && base >= 2 && base <= 36 ? base : 10;\n }\n findRubricElements() {\n return findDescendants(this.assessmentItem, this.elementNameMapper.toNative('rubricblock'));\n }\n rubricElementScope(element) {\n const itemBodyTag = this.elementNameMapper.toNative('itembody').toLowerCase();\n let parent = element.parentNode;\n while (parent && parent !== this.assessmentItem) {\n const parentTag = parent.tagName?.toLowerCase();\n if (parentTag === itemBodyTag) {\n return 'itemBody';\n }\n parent = parent.parentNode;\n }\n return 'direct';\n }\n findModalFeedbackElements() {\n return findDescendants(this.assessmentItem, this.elementNameMapper.toNative('modalfeedback'));\n }\n findDeclarationElements(kind) {\n const tagName = kind === 'response'\n ? 'responsedeclaration'\n : kind === 'outcome'\n ? 'outcomedeclaration'\n : 'templatedeclaration';\n return findDescendants(this.assessmentItem, this.elementNameMapper.toNative(tagName));\n }\n getAssessmentItemAttribute(name) {\n return this.assessmentItem.getAttribute(this.attributeNameMapper.toNative(name));\n }\n getMappedAttribute(element, name) {\n return element.getAttribute(this.attributeNameMapper.toNative(name));\n }\n serializeChildren(element) {\n return normalizeMathMlPrefixes(unwrapCdataSections(this.serializeChildNodes(element)), this.mathMlPrefixes);\n }\n findExtractionElements(elementTypes) {\n const root = this.createExtractionRoot();\n if (!root)\n return [];\n const canonicalTypes = new Set([...elementTypes].map((elementType) => this.elementNameMapper.toCanonical(elementType)));\n const elements = [];\n this.walkExtractionChildren(root, (element) => {\n const rawTagName = element.rawTagName;\n if (!rawTagName)\n return;\n if (!canonicalTypes.has(this.elementNameMapper.toCanonical(rawTagName)))\n return;\n const responseIdentifier = this.getExtractionResponseIdentifier(element);\n if (!responseIdentifier)\n return;\n elements.push({\n element,\n contextRoot: root,\n responseIdentifier,\n normalizedType: normalizeInteractionTypeFromTagName(rawTagName),\n });\n });\n return elements;\n }\n createExtractionRoot() {\n // node-html-parser elements are intentionally mutable for plugin compatibility.\n // Parse one private view for each extraction pass so a plugin cannot mutate\n // the compiled document observed by a later item session.\n const docRoot = parse(this.extractionSource, {\n lowerCaseTagName: false,\n comment: false,\n });\n const itemBodyTag = this.elementNameMapper.toNative('itembody').toLowerCase();\n return docRoot.querySelector?.(itemBodyTag) ?? null;\n }\n getItemBodyElement() {\n return findFirstDescendant(this.assessmentItem, this.elementNameMapper.toNative('itembody'));\n }\n serializeItemBodyForExtraction() {\n const itemBodyTag = this.elementNameMapper.toNative('itembody');\n const itemBody = this.getItemBodyElement();\n const itemBodyChildren = itemBody ? this.serializeChildren(itemBody) : '';\n return `<assessmentItem><${itemBodyTag}>${itemBodyChildren}</${itemBodyTag}></assessmentItem>`;\n }\n serializeChildNodes(element) {\n const children = element.childNodes;\n if (!children)\n return '';\n const serialized = [];\n for (let index = 0; index < children.length; index++) {\n const child = children[index];\n if (child) {\n serialized.push(serializeXml(child));\n }\n }\n return serialized.join('');\n }\n walkExtractionChildren(root, visit) {\n for (const child of root.childNodes ?? []) {\n const element = child;\n if (!element.rawTagName)\n continue;\n if (isRubricBlockTagName(element.rawTagName))\n continue;\n visit(element);\n this.walkExtractionChildren(element, visit);\n }\n }\n getExtractionResponseIdentifier(element) {\n const nativeName = this.attributeNameMapper.toNative('responseIdentifier');\n return (element.getAttribute?.('responseIdentifier') ||\n element.getAttribute?.(nativeName) ||\n element.getAttribute?.('response-identifier') ||\n element.getAttribute?.('responseidentifier') ||\n '');\n }\n}\nfunction isRubricBlockTagName(tagName) {\n const lower = tagName.toLowerCase();\n return lower === 'rubricblock' || lower === 'qti-rubric-block';\n}\nexport function parseAssessmentItemDocument(input) {\n return new AssessmentItemDocument(input);\n}\nfunction unwrapCdataSections(xml) {\n return xml.replace(/<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>/g, (_match, content) => content);\n}\nfunction findMathMlPrefixes(xml) {\n const prefixes = new Set();\n for (const match of xml.matchAll(/\\sxmlns:([A-Za-z_][\\w.-]*)=([\"'])http:\\/\\/www\\.w3\\.org\\/1998\\/Math\\/MathML\\2/g)) {\n const prefix = match[1];\n if (prefix) {\n prefixes.add(prefix);\n }\n }\n return prefixes;\n}\nfunction normalizeMathMlPrefixes(xml, prefixes) {\n let normalized = xml;\n for (const prefix of prefixes) {\n const escapedPrefix = escapeRegExp(prefix);\n normalized = normalized\n .replace(new RegExp(`(<\\\\/?)${escapedPrefix}:([A-Za-z][\\\\w.-]*)(?=[\\\\s>/])`, 'g'), '$1$2')\n .replace(new RegExp(`\\\\sxmlns:${escapedPrefix}=([\"'])http:\\\\/\\\\/www\\\\.w3\\\\.org\\\\/1998\\\\/Math\\\\/MathML\\\\1`, 'g'), '');\n }\n return normalized;\n}\nfunction escapeRegExp(value) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n//# sourceMappingURL=AssessmentItemDocument.js.map","/**\n * Extraction utilities implementation\n *\n * Provides DOM manipulation and content extraction helpers for extractors\n */\nimport { Qti2xElementNameMapper, Qti2xAttributeNameMapper } from '@pie-qti/qti-common';\nimport { sanitizeTextContent } from '../core/sanitizer.js';\n/**\n * Extract text content from QTI elements\n */\nfunction getTextContent(element) {\n return element?.textContent?.trim() || '';\n}\n/**\n * Get children by tag name with QTI version awareness\n */\nfunction getChildrenByTagWithMapper(element, tagName, mapper) {\n if (!element?.childNodes)\n return [];\n return element.childNodes.filter((n) => matchesTagName(n.rawTagName, tagName, mapper));\n}\n/**\n * Extract a boolean attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getBooleanAttribute(element, name, defaultValue = false, attributeMapper) {\n let value = element.getAttribute(name);\n // If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n if ((value === null || value === undefined) && attributeMapper) {\n const nativeName = attributeMapper.toNative(name);\n value = element.getAttribute(nativeName);\n }\n if (value === null || value === undefined)\n return defaultValue;\n return value === 'true';\n}\n/**\n * Extract a number attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getNumberAttribute(element, name, defaultValue, attributeMapper) {\n let value = element.getAttribute(name);\n // If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n if ((value === null || value === undefined) && attributeMapper) {\n const nativeName = attributeMapper.toNative(name);\n value = element.getAttribute(nativeName);\n }\n return value ? Number(value) : defaultValue;\n}\n/**\n * Extract a string attribute from a QTI element\n * Supports both QTI 2.x (camelCase) and QTI 3.0 (kebab-case) attributes\n */\nfunction getStringAttribute(element, name, defaultValue = '', attributeMapper) {\n let value = element.getAttribute(name);\n // If not found and we have a mapper, try the native format (QTI 3.0 kebab-case)\n if ((value === null || value === undefined) && attributeMapper) {\n const nativeName = attributeMapper.toNative(name);\n value = element.getAttribute(nativeName);\n }\n return value || defaultValue;\n}\n/**\n * Extract CSS classes from an element\n */\nfunction getClasses(element) {\n const classAttr = element.getAttribute('class');\n return classAttr ? classAttr.split(/\\s+/).filter(Boolean) : [];\n}\n/**\n * Helper to check if an element's tag name matches a given QTI element name.\n * Handles both QTI 2.x and QTI 3.0 element naming conventions.\n *\n * @param rawTagName - The element's raw tag name from the HTML\n * @param expectedTagName - The tag name to check (in QTI 2.x format, e.g., 'simpleChoice')\n * @param mapper - Optional element name mapper for QTI version handling\n * @returns true if the tag name matches\n */\nfunction matchesTagName(rawTagName, expectedTagName, mapper) {\n if (!rawTagName)\n return false;\n // Convert expected tag name to canonical form (lowercase)\n const canonical = expectedTagName.toLowerCase();\n // Get the native form for this QTI version\n const native = mapper.toNative(canonical);\n // Check if raw tag name matches the native form (case-insensitive)\n return rawTagName.toLowerCase() === native.toLowerCase();\n}\n/**\n * Create extraction utilities instance\n * Provides standard helpers for extracting data from QTI elements.\n * Automatically handles both QTI 2.x and QTI 3.0 element and attribute naming conventions.\n */\nexport function createExtractionUtils(security, mapper, attributeMapper) {\n // Default to QTI 2.x mappers (primary supported QTI format)\n const elementMapper = mapper || new Qti2xElementNameMapper();\n const attrMapper = attributeMapper || new Qti2xAttributeNameMapper();\n return {\n matchesTag(element, tagName) {\n return matchesTagName(element.rawTagName, tagName, elementMapper);\n },\n getChildrenByTag(element, tagName) {\n return getChildrenByTagWithMapper(element, tagName, elementMapper);\n },\n querySelectorAll(element, selector) {\n // Parse simple selectors like \"choiceInteraction simpleChoice\"\n const parts = selector.split(/\\s+/);\n let results = [element];\n for (const part of parts) {\n const nextResults = [];\n for (const current of results) {\n if (matchesTagName(current.rawTagName, part, elementMapper)) {\n nextResults.push(current);\n }\n if (current.childNodes) {\n for (const child of current.childNodes) {\n if (typeof child !== 'string' && matchesTagName(child.rawTagName, part, elementMapper)) {\n nextResults.push(child);\n }\n }\n }\n }\n results = nextResults;\n }\n return results;\n },\n querySelector(element, selector) {\n const results = this.querySelectorAll(element, selector);\n return results.length > 0 ? results[0] : null;\n },\n hasChildWithTag(element, tagName) {\n // Fast boolean check without allocation\n if (!element.childNodes)\n return false;\n for (const child of element.childNodes) {\n if (typeof child !== 'string' && matchesTagName(child.rawTagName, tagName, elementMapper)) {\n return true;\n }\n }\n return false;\n },\n getHtmlContent(element) {\n const html = element?.innerHTML?.trim() || '';\n return sanitizeTextContent(html, { security });\n },\n getTextContent(element) {\n return getTextContent(element);\n },\n getAttribute(element, name, defaultValue = '') {\n return getStringAttribute(element, name, defaultValue, attrMapper);\n },\n getBooleanAttribute(element, name, defaultValue = false) {\n return getBooleanAttribute(element, name, defaultValue, attrMapper);\n },\n getNumberAttribute(element, name, defaultValue = 0) {\n return getNumberAttribute(element, name, defaultValue, attrMapper);\n },\n getPrompt(element) {\n const promptElement = getChildrenByTagWithMapper(element, 'prompt', elementMapper)[0];\n return promptElement ? this.getHtmlContent(promptElement) : null;\n },\n getClasses(element) {\n return getClasses(element);\n },\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Context factory for element extraction\n *\n * Creates ExtractionContext instances with utilities and metadata\n */\nimport { createExtractionUtils } from './utils.js';\nimport { createShuffleRng } from '../core/shuffle.js';\n/**\n * Create an extraction context for an element\n *\n * @param element - The element being extracted\n * @param responseId - Response identifier for this interaction\n * @param dom - Root DOM element for document-wide queries\n * @param declarations - Variable declarations from QTI\n * @param config - Extraction-time role, security, and QTI name mapping\n * @returns Complete extraction context with utilities\n *\n * @example\n * const context = createExtractionContext(\n * element,\n * 'RESPONSE',\n * rootElement,\n * declarations,\n * extractionConfig\n * );\n * const result = registry.extract<ChoiceData>(element, context);\n */\nexport function createExtractionContext(element, responseId, dom, declarations, config, sessionGuid) {\n // Pass both element and attribute name mappers for QTI version handling\n const elementMapper = config.elementNameMapper;\n const attributeMapper = config.attributeNameMapper;\n return {\n element,\n responseId,\n dom,\n declarations,\n utils: createExtractionUtils(config.security, elementMapper, attributeMapper),\n config,\n // Without a session GUID there is nothing stable to seed from, so leave the RNG\n // unset and let extractors keep the authored order.\n ...(sessionGuid ? { shuffleRng: createShuffleRng(sessionGuid, responseId) } : {}),\n };\n}\n//# sourceMappingURL=createContext.js.map","import { sanitizeHtml } from '../core/sanitizer.js';\nimport { toTrustedHtml } from '../core/trustedTypes.js';\nimport { sanitizeResourceUrl } from '../core/urlPolicy.js';\n/**\n * Finalize extracted data for its declared render sinks.\n *\n * InteractionModules own field classification. This module owns the common\n * enforcement implementation and is the only extraction egress that may mint\n * TrustedHTML. The returned graph is frozen so no post-egress string transform\n * can invalidate that guarantee.\n */\nexport function finalizeInteractionDelivery(interaction, fields, security, authoredType = interaction.type) {\n const output = cloneValue(interaction);\n for (const field of fields) {\n visitField(output, field.path, (value, parent, key) => {\n if (field.kind === 'html') {\n // A plugin overriding a standard extractor cannot bypass the common\n // policy by returning an object at a known HTML field. Coerce at this\n // boundary, sanitize, and mint the only render-capable value here.\n const raw = typeof value === 'string' ? value : '';\n const sanitized = sanitizeHtml(raw, { security });\n setChild(parent, key, toTrustedHtml(sanitized, security?.trustedTypesPolicyName));\n return;\n }\n // Unexpected URL shapes fail closed rather than reaching a browser sink\n // where implicit string coercion could reinterpret them.\n if (typeof value !== 'string') {\n setChild(parent, key, '');\n return;\n }\n const use = resolveUrlKind(field.use, output, authoredType);\n setChild(parent, key, sanitizeResourceUrl(value, security?.urlPolicy, use) ?? '');\n });\n }\n if (authoredType === 'mediaInteraction') {\n output.allowObjectEmbeds = security?.allowObjectEmbeds === true;\n }\n return deepFreeze(output);\n}\nfunction visitField(value, path, visit, parent, key) {\n if (path.length === 0) {\n if (parent !== undefined && key !== undefined)\n visit(value, parent, key);\n return;\n }\n if (value === null || typeof value !== 'object')\n return;\n const [segment, ...rest] = path;\n if (segment === '*') {\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n visitField(value[index], rest, visit, value, index);\n }\n return;\n }\n for (const [childKey, child] of Object.entries(value)) {\n visitField(child, rest, visit, value, childKey);\n }\n return;\n }\n const record = value;\n if (!(segment in record))\n return;\n visitField(record[segment], rest, visit, record, segment);\n}\nfunction resolveUrlKind(use, interaction, authoredType) {\n if (use !== 'media-or-object')\n return use;\n const mediaElement = authoredType === 'mediaInteraction' && 'mediaElement' in interaction\n ? interaction.mediaElement\n : null;\n return mediaElement &&\n typeof mediaElement === 'object' &&\n 'type' in mediaElement &&\n mediaElement.type === 'object'\n ? 'object'\n : 'media';\n}\nfunction setChild(parent, key, value) {\n if (Array.isArray(parent) && typeof key === 'number') {\n parent[key] = value;\n return;\n }\n parent[String(key)] = value;\n}\nfunction cloneValue(value) {\n if (Array.isArray(value))\n return value.map((entry) => cloneValue(entry));\n if (value && typeof value === 'object') {\n // TrustedHTML and other host values are terminal leaves. Standard extractor\n // output is plain data; retaining a non-plain value avoids destroying a host\n // object's identity when a plugin supplies one deliberately.\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null)\n return value;\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneValue(entry)]));\n }\n return value;\n}\nfunction deepFreeze(value) {\n if (!value || typeof value !== 'object' || Object.isFrozen(value))\n return value;\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n // TrustedHTML and other host objects are opaque terminal values. Freezing a\n // browser-owned object can throw and adds no protection to our data graph.\n return value;\n }\n Object.freeze(value);\n for (const child of Object.values(value))\n deepFreeze(child);\n return value;\n}\n//# sourceMappingURL=interactionSecurity.js.map","import { createExtractionContext } from './createContext.js';\nimport { finalizeInteractionDelivery } from './interactionSecurity.js';\nexport function extractInteractionData({ document, extractionRegistry, declarations, config, sessionGuid, }) {\n const declMap = projectDeclarationsForExtraction(declarations);\n const elements = document.findExtractionElements(getRegisteredElementTypes(extractionRegistry));\n const interactions = [];\n for (const discovered of elements) {\n const context = createExtractionContext(discovered.element, discovered.responseIdentifier, discovered.contextRoot, declMap, config, sessionGuid);\n const result = extractionRegistry.extract(discovered.element, context);\n if (!result.success)\n throw result.error;\n const extractor = result.extractor;\n const outputType = extractor?.outputType ?? discovered.normalizedType;\n const interaction = {\n ...result.data,\n // These are framework-owned routing fields. Applying them after the\n // extractor payload prevents a plugin from redirecting a response or\n // selecting an undeclared renderer through payload properties.\n type: outputType,\n responseId: discovered.responseIdentifier,\n };\n // Sink policy follows the authored interaction kind, while outputType only\n // selects a renderer. A plugin replacing a standard extractor must not be\n // able to shed the standard prompt/choice/URL policy by renaming its output.\n const standardFields = extractionRegistry.getDeliveryFieldsForType(discovered.normalizedType);\n const extractorFields = extractor.delivery?.fields ?? [];\n interactions.push(finalizeInteractionDelivery(interaction, mergeDeliveryFields(standardFields, extractorFields), config.security, discovered.normalizedType));\n }\n return Object.freeze(interactions);\n}\nfunction mergeDeliveryFields(standard, extension) {\n const fields = new Map();\n for (const field of [...extension, ...standard]) {\n // An output path has one sink meaning. Authored standard policy is\n // authoritative even when a plugin tries to change the field kind itself.\n fields.set(JSON.stringify(field.path), field);\n }\n return [...fields.values()];\n}\nfunction getRegisteredElementTypes(extractionRegistry) {\n const elementTypes = new Set();\n for (const extractor of extractionRegistry.getExtractors()) {\n for (const elementType of extractor.elementTypes) {\n elementTypes.add(elementType);\n }\n }\n return [...elementTypes];\n}\nfunction projectDeclarationsForExtraction(declarations) {\n const declMap = new Map();\n for (const declaration of Object.values(declarations)) {\n declMap.set(declaration.identifier, {\n identifier: declaration.identifier,\n cardinality: declaration.cardinality,\n baseType: declaration.baseType,\n });\n }\n return declMap;\n}\n//# sourceMappingURL=interactionExtractionPipeline.js.map","const ATTR = 'data-qti-colorscheme';\nconst MAGNIFICATION_ATTR = 'data-qti-magnification';\n/**\n * Apply a PNP profile to the player root element.\n *\n * Currently handles color scheme (data-qti-colorscheme attribute).\n * Magnification is intentionally deferred — host stylesheets / browser zoom are sufficient for now.\n */\nexport function applyPnpToRoot(rootEl, pnp) {\n const scheme = pnp?.display?.colorScheme;\n if (!scheme || scheme === 'default') {\n rootEl.removeAttribute(ATTR);\n }\n else {\n rootEl.setAttribute(ATTR, scheme);\n }\n const magnification = pnp?.display?.magnification;\n if (magnification !== undefined && Number.isFinite(magnification) && magnification > 0) {\n rootEl.setAttribute(MAGNIFICATION_ATTR, String(magnification));\n rootEl.style?.setProperty?.('--qti-magnification', String(magnification));\n }\n else {\n rootEl.removeAttribute(MAGNIFICATION_ATTR);\n rootEl.style?.removeProperty?.('--qti-magnification');\n }\n}\n//# sourceMappingURL=applyPnp.js.map","import { parse as parseHtml } from 'node-html-parser';\n/**\n * Parse an XML string containing a QTI 3.0 <qti-catalog-info> element into a CatalogIndex.\n *\n * The mapper is not needed here because we parse the QTI 3.0 element names directly.\n * All element names use lower-case matching (node-html-parser normalises tags).\n */\nexport function extractCatalog(xml) {\n if (!xml.trim())\n return new Map();\n const doc = parseHtml(`<root>${xml}</root>`, { lowerCaseTagName: true });\n // Find <qti-catalog-info> (QTI 3.0 kebab form)\n const infoEl = doc.querySelector('qti-catalog-info');\n if (!infoEl)\n return new Map();\n return buildIndex(infoEl);\n}\n/**\n * Parse a raw QTI item XML string and extract the embedded catalog.\n * Used by Player when integrating with the full item XML.\n */\nexport function extractCatalogFromItemXml(itemXml) {\n const doc = parseHtml(itemXml, { lowerCaseTagName: true });\n const infoEl = doc.querySelector('qti-catalog-info');\n if (!infoEl)\n return new Map();\n return buildIndex(infoEl);\n}\n/**\n * Merge two CatalogIndex maps. itemLevel entries win on collision (same identifier).\n */\nexport function mergeCatalogs(base, override) {\n const merged = new Map(base);\n for (const [id, card] of override) {\n merged.set(id, card);\n }\n return merged;\n}\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\nfunction buildIndex(infoEl) {\n const index = new Map();\n for (const catalogEl of infoEl.querySelectorAll('qti-catalog')) {\n const identifier = catalogEl.getAttribute('id') ?? catalogEl.getAttribute('identifier');\n if (!identifier)\n continue;\n const entries = [];\n for (const cardEl of catalogEl.querySelectorAll('qti-card')) {\n const cardUsage = cardEl.getAttribute('support') ?? cardEl.getAttribute('usage');\n for (const entry of extractCardEntries(cardEl, cardUsage ?? undefined)) {\n entries.push(entry);\n }\n }\n if (entries.length > 0) {\n index.set(identifier, { entries });\n }\n }\n for (const cardEl of infoEl.querySelectorAll('qti-card')) {\n const identifier = cardEl.getAttribute('identifier');\n if (!identifier)\n continue;\n const entries = extractCardEntries(cardEl);\n if (entries.length > 0) {\n const existing = index.get(identifier);\n if (existing) {\n existing.entries.push(...entries);\n }\n else {\n index.set(identifier, { entries });\n }\n }\n }\n return index;\n}\nfunction extractCardEntries(cardEl, fallbackUsage) {\n const explicitEntries = cardEl.querySelectorAll('qti-card-entry');\n const entries = [];\n if (explicitEntries.length > 0) {\n for (const entryEl of explicitEntries) {\n const usage = entryEl.getAttribute('usage') ??\n entryEl.getAttribute('data-reading-type') ??\n fallbackUsage;\n if (!usage)\n continue;\n entries.push({\n usage,\n lang: getLang(entryEl),\n html: extractHtmlContent(entryEl),\n });\n }\n return entries;\n }\n if (fallbackUsage) {\n entries.push({\n usage: fallbackUsage,\n lang: getLang(cardEl),\n html: extractHtmlContent(cardEl),\n });\n }\n return entries;\n}\nfunction getLang(el) {\n return el.getAttribute('xml:lang') ?? el.getAttribute('xmllang') ?? el.getAttribute('lang') ?? undefined;\n}\nfunction extractHtmlContent(el) {\n const htmlContent = el.querySelector('qti-html-content');\n const fileHref = el.querySelector('qti-file-href');\n if (htmlContent)\n return htmlContent.innerHTML ?? htmlContent.text ?? '';\n if (fileHref)\n return fileHref.getAttribute('src') ?? fileHref.text?.trim() ?? '';\n return '';\n}\n//# sourceMappingURL=catalogExtractor.js.map","/**\n * Look up a catalog entry by card identifier, usage type, and optional language.\n *\n * Language fallback order (mirrors APIP 1.0 / HTTP Accept-Language conventions):\n * 1. Exact lang match (e.g. 'en-US')\n * 2. Language-prefix match (e.g. 'en' matches entry with lang 'en-US')\n * 3. Entry with no lang specified (universal fallback)\n * 4. null — no match found\n *\n * @param index CatalogIndex built by extractCatalog / extractCatalogFromItemXml\n * @param idref The data-catalog-idref value (maps to qti-card identifier)\n * @param usage Catalog usage type (e.g. 'glossary-on-screen')\n * @param lang Optional preferred language code (e.g. 'en-US', 'es')\n * @returns The matched entry's html string, or null if nothing found\n */\nexport function getCatalogEntry(index, idref, usage, lang) {\n const card = index.get(idref);\n if (!card)\n return null;\n const candidates = card.entries.filter((e) => e.usage === usage);\n if (candidates.length === 0)\n return null;\n // 1. Exact language match\n if (lang) {\n const exact = candidates.find((e) => e.lang === lang);\n if (exact)\n return exact.html;\n // 2. Language-prefix match: requested lang prefix matches entry lang\n // e.g. lang='en' matches entry.lang='en-US'\n // e.g. lang='en-US' matches entry.lang='en' (broader fallback)\n const prefix = lang.split('-')[0];\n const prefixMatch = candidates.find((e) => e.lang && (e.lang === prefix || e.lang.startsWith(`${prefix}-`) || lang.startsWith(`${e.lang}-`)));\n if (prefixMatch)\n return prefixMatch.html;\n }\n // 3. No-lang fallback (entry without a lang attribute)\n const noLang = candidates.find((e) => !e.lang);\n if (noLang)\n return noLang.html;\n // 4. If we get here and there's only one candidate, return it regardless of lang\n if (candidates.length === 1)\n return candidates[0].html;\n return null;\n}\n//# sourceMappingURL=catalogLookup.js.map","/**\n * QTI 3.0 Portable Custom Interaction (PCI) types.\n * Based on IMS QTI 3.0 Portable Custom Interaction specification.\n */\n/**\n * Raised when PCI content is present but the embedding host has not opted into executing it.\n */\nexport class PciModuleResolverRequiredError extends Error {\n constructor(responseIdentifier, authoredPath) {\n super(`PCI module loading is disabled for response '${responseIdentifier}'. ` +\n `Provide a host-controlled moduleResolver before loading '${authoredPath}'.`);\n this.responseIdentifier = responseIdentifier;\n this.authoredPath = authoredPath;\n this.name = 'PciModuleResolverRequiredError';\n }\n}\n/**\n * Thrown when a PCI module fails to load from both primary and fallback paths.\n */\nexport class PciLoadError extends Error {\n constructor(primaryPath, fallbackPath, cause) {\n super(fallbackPath\n ? `PCI module failed to load from '${primaryPath}' and fallback '${fallbackPath}'`\n : `PCI module failed to load from '${primaryPath}'`);\n this.primaryPath = primaryPath;\n this.fallbackPath = fallbackPath;\n this.name = 'PciLoadError';\n if (cause)\n Object.defineProperty(this, 'cause', { value: cause, writable: true, configurable: true });\n }\n}\n//# sourceMappingURL=types.js.map","import { PciLoadError, PciModuleResolverRequiredError } from './types.js';\n/**\n * Loads, initializes, and manages the lifecycle of a single PCI module.\n *\n * Usage:\n * const host = new PciHost(extractedData, { baseUrl, moduleResolver });\n * await host.load();\n * host.initialize(domNode);\n * host.getResponse(); // returns current response\n * host.destroy(); // cleanup on player teardown\n */\nexport class PciHost {\n constructor(data, options = {}) {\n this.module = null;\n this.destroyed = false;\n this.loadGeneration = 0;\n this._response = null;\n this._hasResponse = false;\n /**\n * True once a mounted module has reported a response. While set, the module\n * is the source of truth and `offerResponse()` will not overwrite it.\n */\n this._moduleOwnsResponse = false;\n /**\n * True between an authoritative `restore()` and the rebuild that applies it.\n * The mounted module still holds the superseded value during that window, so\n * `getResponse()` must report the held one.\n */\n this._restorePending = false;\n this._responseChangeListeners = new Set();\n this._remountRequestListeners = new Set();\n this.data = data;\n this.baseUrl = typeof options === 'string' ? options : (options.baseUrl ?? '');\n this.moduleResolver = typeof options === 'string' ? undefined : options.moduleResolver;\n }\n /**\n * Register a callback to fire when the PCI's response changes.\n * The player calls this to wire the PCI into its internal response map.\n */\n onResponseChange(callback) {\n this._responseChangeListeners.add(callback);\n return () => this._responseChangeListeners.delete(callback);\n }\n /**\n * Register a callback fired when an authoritative `restore()` lands on a\n * mounted module and the module must be rebuilt from the restored value.\n *\n * The renderer owns the DOM scaffold and its sanitization, so it performs the\n * rebuild: reset the sanitized markup into the mount node, then call\n * `remount(node)`. A host with no renderer wired here still gets the restored\n * value applied — see `restore()`.\n */\n onRemountRequest(callback) {\n this._remountRequestListeners.add(callback);\n return () => this._remountRequestListeners.delete(callback);\n }\n /**\n * Load the PCI module from primaryPath, falling back to fallbackPath.\n * Throws PciLoadError if both fail.\n */\n async load() {\n if (this.destroyed) {\n throw new Error('Cannot load a destroyed PciHost');\n }\n if (!this.moduleResolver) {\n throw new PciModuleResolverRequiredError(this.data.responseIdentifier, this.data.primaryPath);\n }\n const generation = ++this.loadGeneration;\n const primary = this.resolveUrl(this.data.primaryPath);\n try {\n const mod = await this.resolveModule(primary, this.data.primaryPath, 'primary');\n this.adoptResolvedModule(mod, this.data.primaryPath, generation);\n return;\n }\n catch (primaryErr) {\n if (!this.isCurrentLoad(generation))\n throw primaryErr;\n if (!this.data.fallbackPath) {\n throw new PciLoadError(this.data.primaryPath, undefined, primaryErr);\n }\n }\n const fallback = this.resolveUrl(this.data.fallbackPath);\n try {\n const mod = await this.resolveModule(fallback, this.data.fallbackPath, 'fallback');\n this.adoptResolvedModule(mod, this.data.fallbackPath, generation);\n }\n catch (fallbackErr) {\n if (!this.isCurrentLoad(generation))\n throw fallbackErr;\n throw new PciLoadError(this.data.primaryPath, this.data.fallbackPath, fallbackErr);\n }\n }\n /**\n * Initialize the PCI inside the given DOM element.\n * Must be called after load() resolves.\n */\n initialize(dom) {\n if (!this.module)\n return;\n const boundTo = {\n onReady: () => { },\n onResponseChange: (value) => {\n this._response = value;\n this._hasResponse = true;\n this._moduleOwnsResponse = true;\n this._restorePending = false;\n for (const listener of this._responseChangeListeners) {\n listener(this.data.responseIdentifier, value);\n }\n },\n };\n try {\n this.module.initialize(dom, this.data.config, boundTo);\n if (this._hasResponse) {\n this.module.setResponse(this._response);\n }\n // The module now holds the held value, however it got there.\n this._restorePending = false;\n }\n catch (error) {\n const failedModule = this.module;\n this.module = null;\n failedModule.destroy();\n throw error;\n }\n }\n /** Return the current response value from the PCI module. */\n getResponse() {\n if (this._restorePending)\n return this._response;\n return this.module ? this.module.getResponse() : this._response;\n }\n /**\n * Offer a response the player believes to be current.\n *\n * Declined once a mounted module has reported a response of its own. The\n * player's response map echoes every change back through `setResponses`, so\n * an unconditional push would hand the module its own value mid-interaction\n * and rebuild whatever internal state — selection, cursor, undo history —\n * the module derives from it. Use `restore()` when the player's value must\n * win regardless.\n *\n * @returns `false` when the module retained ownership and the value was not applied.\n */\n offerResponse(value) {\n if (this._moduleOwnsResponse)\n return false;\n this._response = value;\n this._hasResponse = true;\n if (this.module) {\n this.module.setResponse(value);\n this._restorePending = false;\n }\n return true;\n }\n /**\n * Authoritatively replace the response, discarding in-progress candidate\n * state and returning ownership to the player.\n *\n * A mounted module is rebuilt from the restored value rather than mutated\n * where a renderer is wired to `onRemountRequest`: \"discard candidate state\"\n * is what re-instantiation means, and it is the only form the QTI 3.0 PCI\n * contract offers, since state is injected at `getInstance` and there is no\n * setter. Until the rebuild lands, `getResponse()` reports the restored value\n * rather than the module's superseded one.\n *\n * With no rebuild path wired, the value is pushed into the module directly.\n * That mutates rather than discards candidate state, which is all a host\n * without a scaffold owner can do, and it keeps reset-to-default and session\n * restore effective for consumers driving `PciHost` themselves. Before mount,\n * the value is held and applied by `initialize()`.\n */\n restore(value) {\n this._response = value;\n this._hasResponse = true;\n this._moduleOwnsResponse = false;\n if (!this.module)\n return;\n if (this._remountRequestListeners.size === 0) {\n this.module.setResponse(value);\n return;\n }\n this._restorePending = true;\n for (const listener of this._remountRequestListeners)\n listener();\n }\n /**\n * Rebuild the module in place from the currently held response.\n *\n * The caller must reset the sanitized DOM scaffold into `dom` first: this\n * discards the previous module instance, resolves a fresh one through the\n * host resolver, and initializes it, which seeds the held response.\n */\n async remount(dom) {\n if (this.destroyed)\n throw new Error('Cannot remount a destroyed PciHost');\n this.module?.destroy();\n this.module = null;\n await this.load();\n this.initialize(dom);\n }\n /** Disable the PCI (e.g. when role is not candidate, or after final submission). */\n disable() {\n this.module?.disable();\n }\n /** Re-enable the PCI. */\n enable() {\n this.module?.enable();\n }\n /** Tear down the PCI and release all resources. */\n destroy() {\n this.destroyed = true;\n this.loadGeneration++;\n this.module?.destroy();\n this.module = null;\n this._responseChangeListeners.clear();\n this._remountRequestListeners.clear();\n }\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n resolveModule(resolvedUrl, authoredPath, kind) {\n return Promise.resolve(this.moduleResolver(resolvedUrl, {\n authoredPath,\n kind,\n responseIdentifier: this.data.responseIdentifier,\n customInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,\n }));\n }\n resolveUrl(path) {\n if (/^[a-z][a-z\\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {\n return path;\n }\n if (!this.baseUrl)\n return path;\n // Relative path: resolve against baseUrl\n const base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';\n try {\n return new URL(path, base).href;\n }\n catch {\n return base + path;\n }\n }\n isCurrentLoad(generation) {\n return !this.destroyed && generation === this.loadGeneration;\n }\n adoptResolvedModule(mod, authoredPath, generation) {\n const candidate = this.extractPciInterface(mod, authoredPath);\n if (!this.isCurrentLoad(generation)) {\n candidate.destroy();\n throw new Error('PciHost was destroyed before its module finished loading');\n }\n this.module?.destroy();\n this.module = candidate;\n // A freshly adopted module has reported nothing yet.\n this._moduleOwnsResponse = false;\n }\n /**\n * Extract a PciModule from the host resolver's result.\n * Supports: default export, named `getInstance` export, or the module itself.\n */\n extractPciInterface(mod, authoredPath) {\n const candidate = mod?.default ?? mod?.getInstance?.() ?? mod;\n const requiredMethods = [\n 'initialize',\n 'getResponse',\n 'setResponse',\n 'disable',\n 'enable',\n 'destroy',\n ];\n const missingMethods = requiredMethods.filter((method) => typeof candidate?.[method] !== 'function');\n if (missingMethods.length > 0) {\n throw new Error(`PCI module at '${authoredPath}' does not export a valid PciModule interface; ` +\n `missing: ${missingMethods.join(', ')}`);\n }\n return candidate;\n }\n}\n//# sourceMappingURL=PciHost.js.map","export const EXTENDED_TEXT_RECORD_FIELD_TYPES = {\n stringValue: 'string',\n floatValue: 'float',\n integerValue: 'integer',\n leftDigits: 'integer',\n rightDigits: 'integer',\n ndp: 'integer',\n nsf: 'integer',\n exponent: 'integer',\n};\nfunction digitValue(character) {\n const code = character.toUpperCase().charCodeAt(0);\n if (code >= 48 && code <= 57)\n return code - 48;\n if (code >= 65 && code <= 90)\n return code - 65 + 10;\n return -1;\n}\nfunction parseDigits(text, base) {\n let value = 0;\n for (const character of text) {\n const digit = digitValue(character);\n if (digit < 0 || digit >= base)\n return null;\n value = value * base + digit;\n }\n return value;\n}\n/**\n * Parse the lexical numeric response used by QTI string interactions.\n *\n * An exponent is recognized for base 10. For other bases, letters such as E\n * are digits and therefore cannot unambiguously introduce an exponent.\n */\nfunction parseNumericString(input, base) {\n if (!Number.isInteger(base) || base < 2 || base > 36) {\n return {\n valid: false,\n value: null,\n integerValue: null,\n leftDigits: null,\n rightDigits: null,\n ndp: null,\n nsf: null,\n exponent: null,\n };\n }\n const lexical = input.trim();\n const match = base === 10\n ? /^([+-]?)([0-9]*)(?:\\.([0-9]*))?(?:[eE]([+-]?\\d+))?$/.exec(lexical)\n : /^([+-]?)([0-9A-Za-z]*)(?:\\.([0-9A-Za-z]*))?$/.exec(lexical);\n const left = match?.[2] ?? '';\n const right = match?.[3] ?? '';\n if (!match || left.length + right.length === 0) {\n return {\n valid: false,\n value: null,\n integerValue: null,\n leftDigits: null,\n rightDigits: null,\n ndp: null,\n nsf: null,\n exponent: null,\n };\n }\n const leftValue = parseDigits(left || '0', base);\n const rightValue = parseDigits(right || '0', base);\n if (leftValue === null || rightValue === null) {\n return {\n valid: false,\n value: null,\n integerValue: null,\n leftDigits: null,\n rightDigits: null,\n ndp: null,\n nsf: null,\n exponent: null,\n };\n }\n const exponent = match[4] === undefined ? null : Number.parseInt(match[4], 10);\n const sign = match[1] === '-' ? -1 : 1;\n const significand = leftValue + rightValue / base ** right.length;\n const value = base === 10\n ? Number(lexical)\n : sign * significand * base ** (exponent ?? 0);\n if (!Number.isFinite(value)) {\n return {\n valid: false,\n value: null,\n integerValue: null,\n leftDigits: null,\n rightDigits: null,\n ndp: null,\n nsf: null,\n exponent,\n };\n }\n const allDigits = `${left}${right}`;\n const withoutLeadingZeroes = allDigits.replace(/^0+/, '');\n const nsf = withoutLeadingZeroes.length > 0 ? withoutLeadingZeroes.length : 1;\n return {\n valid: true,\n value,\n integerValue: right.length === 0 && exponent === null ? value : null,\n leftDigits: left.length,\n rightDigits: right.length,\n ndp: Math.max(0, right.length - (exponent ?? 0)),\n nsf,\n exponent,\n };\n}\n/** Build the eight-field numeric detail record mandated by QTI. */\nexport function createExtendedTextNumericRecord(input, base = 10) {\n const parsed = parseNumericString(input, base);\n return {\n stringValue: input,\n floatValue: parsed.value,\n integerValue: parsed.integerValue,\n leftDigits: parsed.leftDigits,\n rightDigits: parsed.rightDigits,\n ndp: parsed.ndp,\n nsf: parsed.nsf,\n exponent: parsed.exponent,\n };\n}\nfunction unwrapRecordStringValue(value) {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return value;\n const field = value.stringValue;\n if (field && typeof field === 'object' && 'kind' in field) {\n return field.kind === 'value'\n ? field.value\n : '';\n }\n return field;\n}\n/** Convert the current public response value into editor strings. */\nexport function extendedTextResponseToStrings(response, interaction) {\n if (interaction.cardinality === 'record') {\n const raw = unwrapRecordStringValue(response);\n return [raw === null || raw === undefined ? '' : String(raw)];\n }\n if (Array.isArray(response)) {\n return response.length > 0 ? response.map((value) => String(value ?? '')) : [''];\n }\n if (response === null || response === undefined)\n return [''];\n if (typeof response === 'number' && interaction.base !== 10 && Number.isInteger(response)) {\n return [response.toString(interaction.base)];\n }\n return [String(response)];\n}\nfunction numericValue(input, interaction) {\n const parsed = parseNumericString(input, interaction.base);\n if (!parsed.valid || parsed.value === null)\n return null;\n if (interaction.baseType === 'integer') {\n return parsed.integerValue;\n }\n return parsed.value;\n}\nfunction hasMeaningfulString(value, format) {\n const comparable = format === 'xhtml'\n ? value.replace(/<[^>]*>/g, '').replace(/ | /gi, ' ')\n : value;\n return comparable.trim().length > 0;\n}\n/** Convert editor strings into the public response shape for the declaration. */\nexport function createExtendedTextResponse(strings, interaction) {\n const nonEmpty = strings.filter((value) => hasMeaningfulString(value, interaction.format));\n if (interaction.cardinality === 'record') {\n return nonEmpty.length === 0 ? null : createExtendedTextNumericRecord(nonEmpty[0], interaction.base);\n }\n const values = nonEmpty\n .map((value) => {\n if (interaction.baseType === 'integer' || interaction.baseType === 'float') {\n return numericValue(value, interaction);\n }\n return value;\n })\n .filter((value) => value !== null);\n if (interaction.cardinality === 'multiple' || interaction.cardinality === 'ordered')\n return values;\n return values[0] ?? null;\n}\n/** Raw companion response captured by stringIdentifier. */\nexport function createExtendedTextStringResponse(strings, cardinality, format) {\n const nonEmpty = strings.filter((value) => hasMeaningfulString(value, format));\n if (cardinality === 'multiple' || cardinality === 'ordered')\n return nonEmpty;\n return nonEmpty[0] ?? null;\n}\n//# sourceMappingURL=response.js.map","import { buildOutcomeProcessingAst, buildResponseProcessingAst, buildTemplateProcessingAst, coerceBaseValue, DeclarationContext, evalExpr, execProgram, findDescendants, findFirstDescendant, getAttr, OperatorRegistry, qtiNull, qtiValue, toBoolean, toNumber, toStringValue, } from '@pie-qti/qti-processing';\nimport { Qti2xElementNameMapper, Qti2xAttributeNameMapper, Qti3ElementNameMapper, Qti3AttributeNameMapper, detectQtiVersion, } from '@pie-qti/qti-common';\nimport { parseAssessmentItemDocument } from '../document/AssessmentItemDocument.js';\nimport { createExtractionRegistry, registerFrameworkDeliveryFields, } from '../extraction/ExtractionRegistry.js';\nimport { extractInteractionData } from '../extraction/interactionExtractionPipeline.js';\nimport { getStandardInteractionModules } from '../interactions/modules.js';\nimport { createComponentRegistry } from './ComponentRegistry.js';\nimport { createSeededRng } from './random.js';\nimport { sanitizeHtml } from './sanitizer.js';\nimport { toTrustedHtml } from './trustedTypes.js';\nimport { sanitizeResourceUrl } from './urlPolicy.js';\nimport { applyPnpToRoot } from '../pnp/applyPnp.js';\nimport { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from '../catalog/catalogExtractor.js';\nimport { getCatalogEntry } from '../catalog/catalogLookup.js';\nimport { PciHost } from '../pci/PciHost.js';\nimport { createExtendedTextNumericRecord, EXTENDED_TEXT_RECORD_FIELD_TYPES, } from '../interactions/extended-text/response.js';\n/** @internal Used by AssessmentItemDefinition; deliberately absent from the package root API. */\nexport function preparePlayerDefinitionInternal(config) {\n const compiler = new Player(config, undefined, { compileOnly: true });\n try {\n return compiler.capturePreparedDefinition();\n }\n finally {\n compiler.destroy();\n }\n}\n/** @internal Used by ItemSession; deliberately absent from the package root API. */\nexport function createPlayerFromPreparedInternal(config, prepared, skipTemplateProcessing = false) {\n return new Player(config, prepared, {\n skipTemplateProcessing,\n });\n}\nexport class Player {\n constructor(config, prepared, construction = {}) {\n this.interactionDataCache = null;\n this.warnedImpliedZeroMaxScore = false;\n this.responseProcessingProgram = null;\n this.templateProcessingProgram = null;\n this.outcomeProcessingProgram = null;\n this._catalogIndex = new Map();\n this._stimulusCatalogIndexes = new Map();\n this._pciHosts = new Map();\n this._pnpChangeListeners = new Set();\n this.lifecycleStatus = 'initial';\n this.accumulatedDurationMs = 0;\n this.config = config;\n this.itemXml = config.itemXml ?? '';\n this.role = config.role ?? 'candidate';\n this.sessionGuid = createSessionGuid();\n this.sessionStartedAt = Date.now();\n this.rng = config.rng ?? (typeof config.seed === 'number' ? createSeededRng(config.seed) : Math.random);\n // Resolve QTI-version mappers without mutating caller-owned configuration.\n if (prepared) {\n this.mapper = prepared.mapper;\n }\n else if (!config.elementNameMapper) {\n const version = detectQtiVersion(this.itemXml);\n if (version === '3.0') {\n this.mapper = new Qti3ElementNameMapper();\n }\n else {\n this.mapper = new Qti2xElementNameMapper();\n }\n }\n else {\n this.mapper = config.elementNameMapper;\n }\n const attributeMapper = prepared?.attributeMapper ??\n config.attributeNameMapper ??\n (this.mapper.version === '3.0'\n ? new Qti3AttributeNameMapper()\n : new Qti2xAttributeNameMapper());\n this.config = {\n ...config,\n elementNameMapper: this.mapper,\n attributeNameMapper: attributeMapper,\n };\n if (prepared) {\n this.itemDocument = prepared.itemDocument;\n this.decls = cloneDeclarationMap(prepared.declarations);\n }\n else {\n this.itemDocument = parseAssessmentItemDocument({\n itemXml: this.itemXml,\n elementNameMapper: this.mapper,\n attributeNameMapper: attributeMapper,\n security: this.config.security,\n });\n this.decls = this.buildDeclarations();\n this.ensureBuiltinDeclarations(this.decls);\n }\n this.sourceDeclarations = cloneDeclarationMap(this.decls);\n this.ctx = new DeclarationContext(this.decls);\n this.ops = new OperatorRegistry();\n // Extraction + rendering registries (for interaction rendering)\n // Pass the element name mapper to the extraction registry for QTI version handling\n this.extractionRegistry =\n this.config.extractionRegistry ??\n createExtractionRegistry(this.mapper);\n this.componentRegistry =\n this.config.componentRegistry ??\n createComponentRegistry();\n // I18n provider (defaults to a simple fallback if not provided)\n this.i18nProvider = this.config.i18nProvider ?? this.createDefaultI18nProvider();\n if (!this.extractionRegistry.isSealed()) {\n // Register standard interaction extractors.\n for (const module of getStandardInteractionModules()) {\n this.extractionRegistry.register(module.extractor);\n registerFrameworkDeliveryFields(this.extractionRegistry, module.type, module.delivery);\n }\n this.extractionRegistry.seal();\n }\n // Build ASTs once.\n const processingBuildOptions = {\n elementNameMapper: this.mapper,\n resolveProcessingFragment: this.config.resolveProcessingFragment,\n maxProcessingFragmentDepth: this.config.processingFragmentLimits?.maxDepth,\n maxProcessingFragmentCharacters: this.config.processingFragmentLimits?.maxCharacters,\n };\n const templateProcessing = prepared ? null : this.itemDocument.getProcessingElement('template');\n this.templateProcessingProgram =\n prepared?.templateProcessingProgram ??\n (templateProcessing\n ? buildTemplateProcessingAst(templateProcessing, processingBuildOptions)\n : null);\n if (this.templateProcessingProgram &&\n !construction.compileOnly &&\n !construction.skipTemplateProcessing) {\n this.execTemplateProcessing();\n }\n const responseProcessing = prepared ? null : this.itemDocument.getProcessingElement('response');\n this.responseProcessing = prepared?.responseProcessing ?? this.itemDocument.describeResponseProcessing();\n this.responseProcessingProgram =\n prepared?.responseProcessingProgram ??\n (responseProcessing\n ? buildResponseProcessingAst(responseProcessing, processingBuildOptions)\n : null);\n const outcomeProcessing = prepared ? null : this.itemDocument.getProcessingElement('outcome');\n this.outcomeProcessingProgram =\n prepared?.outcomeProcessingProgram ??\n (outcomeProcessing\n ? buildOutcomeProcessingAst(outcomeProcessing, processingBuildOptions)\n : null);\n // Detect and log QTI version for compatibility awareness\n const detectedVersion = prepared ? null : this.detectQTIVersion();\n if (detectedVersion === 'unknown') {\n console.warn('[QTI Player] Could not detect QTI version. Assuming QTI 2.2 compatibility.');\n }\n else if (detectedVersion === '2.0') {\n console.warn('[QTI Player] QTI 2.0 detected. Some features may not be fully supported. QTI 2.2 is recommended.');\n }\n else if (detectedVersion === '2.1') {\n console.info('[QTI Player] QTI 2.1 detected. Using QTI 2.2 compatibility mode with CC2 template support.');\n }\n // Store PNP profile for later use (applyPnpToRoot is called once a root element is available).\n this._pnp = this.config.pnp;\n // Build the catalog index from shared catalog XML, item XML, and resolved delivery context.\n // Sanitized item-level delivery context entries win over raw item XML on collisions.\n // Stimulus entries are kept separately so rendered stimulus terms can avoid ID collisions.\n if (prepared) {\n this._catalogIndex = prepared.catalogIndex;\n this._stimulusCatalogIndexes = prepared.stimulusCatalogIndexes;\n }\n else {\n let mergedCatalog = new Map();\n let deliveryItemCatalog = new Map();\n for (const source of this.config.deliveryContext?.catalogSources ?? []) {\n const sourceCatalog = extractCatalog(source.xml);\n if (source.scope === 'stimulus' && source.stimulusIdentifier) {\n const existing = this._stimulusCatalogIndexes.get(source.stimulusIdentifier) ?? new Map();\n this._stimulusCatalogIndexes.set(source.stimulusIdentifier, mergeCatalogs(existing, sourceCatalog));\n }\n else {\n deliveryItemCatalog = mergeCatalogs(deliveryItemCatalog, sourceCatalog);\n }\n }\n if (this.config.catalogXml) {\n mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.config.catalogXml));\n }\n mergedCatalog = mergeCatalogs(mergedCatalog, extractCatalogFromItemXml(this.itemXml));\n this._catalogIndex = mergeCatalogs(mergedCatalog, deliveryItemCatalog);\n }\n // Check strict compliance if enabled\n if (!prepared && this.config.strictQtiCompliance?.enabled) {\n this.validateStrictCompliance();\n }\n }\n /** @internal Definition compiler capture; parser artifacts remain module-private. */\n capturePreparedDefinition() {\n const identifier = this.itemDocument.getAssessmentItemAttribute('identifier')?.trim();\n if (!identifier) {\n throw new Error('AssessmentItemDefinition requires an assessment-item identifier');\n }\n return Object.freeze({\n identifier,\n mapper: this.mapper,\n attributeMapper: this.config.attributeNameMapper,\n itemDocument: this.itemDocument,\n declarations: cloneDeclarationMap(this.sourceDeclarations),\n responseProcessing: this.responseProcessing,\n responseProcessingProgram: this.responseProcessingProgram,\n templateProcessingProgram: this.templateProcessingProgram,\n outcomeProcessingProgram: this.outcomeProcessingProgram,\n catalogIndex: this._catalogIndex,\n stimulusCatalogIndexes: this._stimulusCatalogIndexes,\n });\n }\n /**\n * Apply the PNP profile to a player root element.\n * Call this once the root DOM element is available (e.g. after mounting).\n * The player stores the element reference so updatePnp() can re-apply without re-parsing the item.\n */\n applyPnp(rootEl) {\n this._rootEl = rootEl;\n applyPnpToRoot(rootEl, this._pnp);\n }\n /**\n * Update the PNP profile mid-session without re-parsing the item XML.\n * Deep-merges the partial profile into the current profile and re-applies.\n */\n updatePnp(partial) {\n this._pnp = mergePnp(this._pnp, partial);\n if (this._rootEl) {\n applyPnpToRoot(this._rootEl, this._pnp);\n }\n for (const listener of this._pnpChangeListeners) {\n listener(this._pnp);\n }\n }\n /** Return the current resolved PNP profile. */\n getPnp() {\n return this._pnp;\n }\n onPnpChange(listener) {\n this._pnpChangeListeners.add(listener);\n return () => this._pnpChangeListeners.delete(listener);\n }\n /** Return the package/assessment-resolved delivery context, if one was supplied. */\n getDeliveryContext() {\n return this.config.deliveryContext;\n }\n /**\n * Look up a catalog entry by card identifier, usage type, and optional language.\n * Returns the HTML string for the matched entry, or null if not found.\n *\n * Language fallback: exact match → prefix match → no-lang entry → null.\n */\n getCatalogEntry(idref, usage, lang, options) {\n const stimulusHtml = options?.stimulusIdentifier\n ? getCatalogEntry(this._stimulusCatalogIndexes.get(options.stimulusIdentifier) ?? new Map(), idref, usage, lang)\n : null;\n const html = stimulusHtml ?? getCatalogEntry(this._catalogIndex, idref, usage, lang);\n if (html === null)\n return null;\n if (looksLikeCatalogUrl(html)) {\n return sanitizeResourceUrl(html.trim(), this.config.security?.urlPolicy, 'img');\n }\n return toTrustedHtml(this.sanitizeHtmlContent(html), this.config.security?.trustedTypesPolicyName);\n }\n /** Sanitize externally resolved item-adjacent HTML before it reaches a rendering sink. */\n sanitizeHtmlContent(html) {\n return sanitizeHtml(html, { security: this.config.security });\n }\n /**\n * Create a PciHost for an extracted PCI and register it for response tracking.\n * The caller is responsible for calling host.load() and\n * host.initialize(domNode) once the DOM element is available.\n */\n createPciHost(data) {\n const host = new PciHost(data, {\n baseUrl: this.config.pci?.baseUrl,\n moduleResolver: this.config.pci?.moduleResolver,\n });\n // Wire response changes back into the player's declaration context\n host.onResponseChange((responseId, value) => {\n if (this.lifecycleStatus !== 'initial' && this.lifecycleStatus !== 'interacting')\n return;\n const d = this.decls[responseId];\n if (d) {\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, value, d.identifier);\n }\n });\n this._pciHosts.set(data.responseIdentifier, host);\n return host;\n }\n /**\n * Offer a response value to the PCI identified by responseIdentifier. A\n * mounted module that has already reported a response keeps it.\n */\n offerPciResponse(responseIdentifier, value) {\n this._pciHosts.get(responseIdentifier)?.offerResponse(value);\n }\n /**\n * Authoritatively replace a PCI's response, discarding in-progress candidate\n * state. Session restore and reset-to-default use this.\n */\n restorePciResponse(responseIdentifier, value) {\n this._pciHosts.get(responseIdentifier)?.restore(value);\n }\n /**\n * Disable/enable all PCI hosts based on role.\n * 'candidate' = enabled; any other role = disabled.\n */\n syncPciDisabledState() {\n const disabled = this.role !== 'candidate';\n for (const host of this._pciHosts.values()) {\n if (disabled)\n host.disable();\n else\n host.enable();\n }\n }\n /**\n * Destroy all PCI hosts. Call on player teardown.\n */\n destroyPciHosts() {\n for (const host of this._pciHosts.values()) {\n host.destroy();\n }\n this._pciHosts.clear();\n }\n /** Breaking-change API: returns the typed declaration map */\n getDeclarations() {\n return this.decls;\n }\n /**\n * Apply candidate response values to the declaration context.\n *\n * Every candidate interaction reaches this method, including a PCI reporting\n * its own change, so a mounted PCI module is offered the value rather than\n * force-fed it. Use `restoreResponses()` when the caller's value must replace\n * in-progress module state.\n */\n setResponses(responses) {\n this.applyResponses(responses, (id, value) => this.offerPciResponse(id, value));\n }\n /**\n * Apply response values authoritatively, discarding in-progress PCI candidate\n * state. State replacement and explicit host overrides use this.\n */\n restoreResponses(responses) {\n this.applyResponses(responses, (id, value) => this.restorePciResponse(id, value));\n }\n applyResponses(responses, applyToPci) {\n for (const [id, raw] of Object.entries(responses)) {\n const d = this.decls[id];\n if (!d)\n continue;\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);\n applyToPci(id, this.qtiValueToPublic(d.value));\n }\n }\n /**\n * Destroy all resources owned by this player instance (PCI modules, etc.).\n * Call when unmounting to prevent memory leaks.\n */\n destroy() {\n this.destroyPciHosts();\n }\n processResponses() {\n return this.runResponseProcessing({ finalizeNonAdaptiveAttempt: true });\n }\n saveItemSession() {\n this.freezeDuration();\n return this.serializeItemSession();\n }\n restoreItemSession(state) {\n this.sessionGuid = state.sessionGuid;\n this.interactionDataCache = null;\n this.lifecycleStatus = state.lifecycleStatus;\n this.accumulatedDurationMs = Math.max(0, Number(state.duration) || 0);\n this.sessionStartedAt = Date.now();\n this.applySerializedVariables(state.responseVariables);\n this.applySerializedVariables(state.outcomeVariables);\n this.applySerializedVariables(state.templateVariables);\n this.applySerializedVariables(state.contextVariables);\n this.updateDuration();\n }\n /** @internal ItemSession uses this to activate a restored delivery handoff. */\n getLifecycleStatus() {\n return this.lifecycleStatus;\n }\n /** @internal ItemSession uses this to resume a suspended delivery handoff. */\n activateAttempt() {\n if (this.lifecycleStatus === 'suspended')\n this.lifecycleStatus = 'interacting';\n }\n suspendAttempt() {\n return this.runItemSessionAction({ action: 'suspendAttempt' });\n }\n endAttempt(options = {}) {\n return this.runItemSessionAction({ action: 'endAttempt', ...options });\n }\n scoreAttempt() {\n return this.runItemSessionAction({ action: 'scoreAttempt' });\n }\n newTemplate(options = {}) {\n return this.runItemSessionAction({ action: 'newTemplate', ...options });\n }\n runItemSessionAction(command) {\n switch (command.action) {\n case 'suspendAttempt':\n return this.runSuspendAttemptAction();\n case 'endAttempt':\n return this.runEndAttemptAction(command);\n case 'scoreAttempt':\n return this.runScoreAttemptAction();\n case 'newTemplate':\n return this.runNewTemplateAction(command);\n case 'submitAttempt':\n return this.runSubmitAttemptAction(command.countAttempt ?? true);\n }\n }\n runSuspendAttemptAction() {\n const validation = this.validateResponses(this.getResponses());\n this.lifecycleStatus = 'suspended';\n const sessionState = this.saveItemSession();\n return this.createItemSessionActionResult('suspendAttempt', sessionState, { validation });\n }\n runEndAttemptAction(options) {\n const validate = options.validateResponses ?? false;\n const validation = validate ? this.validateResponses(this.getResponses()) : undefined;\n if (validation && !validation.valid) {\n return this.createItemSessionActionResult('endAttempt', this.saveItemSession(), { validation });\n }\n const scoring = this.isAdaptive()\n ? this.runAdaptiveSubmitAttempt(options.countAttempt ?? true)\n : this.runResponseProcessing({\n finalizeNonAdaptiveAttempt: true,\n countAttempt: options.countAttempt ?? true,\n });\n this.lifecycleStatus = scoring.completed ? 'closed' : 'interacting';\n return this.createItemSessionActionResult('endAttempt', this.saveItemSession(), {\n completed: scoring.completed,\n validation,\n scoring,\n });\n }\n runScoreAttemptAction() {\n const scoring = this.runResponseProcessing({ finalizeNonAdaptiveAttempt: false });\n return this.createItemSessionActionResult('scoreAttempt', this.saveItemSession(), {\n completed: scoring.completed,\n scoring,\n });\n }\n runNewTemplateAction(options) {\n this.resetOutcomesToDefault();\n if (options.resetResponses ?? true) {\n this.resetResponsesToDefault();\n }\n this.resetTemplatesToDefault();\n this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'not_attempted'));\n this.ctx.setValue('numAttempts', qtiValue('integer', 'single', 0));\n this.execTemplateProcessing();\n this.lifecycleStatus = 'initial';\n this.accumulatedDurationMs = 0;\n this.sessionStartedAt = Date.now();\n this.updateDuration();\n return this.createItemSessionActionResult('newTemplate', this.serializeItemSession());\n }\n runSubmitAttemptAction(countAttempt) {\n const scoring = this.runAdaptiveSubmitAttempt(countAttempt);\n return this.createItemSessionActionResult('submitAttempt', this.saveItemSession(), {\n completed: scoring.completed,\n scoring,\n });\n }\n createItemSessionActionResult(action, sessionState, options = {}) {\n return {\n action,\n lifecycleStatus: this.lifecycleStatus,\n completionStatus: this.getCompletionStatus(),\n numAttempts: this.getNumAttempts(),\n duration: sessionState.duration,\n completed: options.completed ?? this.isCompleted(),\n sessionState,\n validation: options.validation,\n scoring: options.scoring,\n };\n }\n getSecurityConfig() {\n return this.config.security;\n }\n getTrustedTypesPolicyName() {\n return this.config.security?.trustedTypesPolicyName;\n }\n /**\n * Get the i18n provider instance\n * @returns I18nProvider instance\n */\n getI18nProvider() {\n return this.i18nProvider;\n }\n /**\n * Get attribute value with QTI version support.\n * Tries the attribute mapper's native form first, then falls back to direct lookup.\n * @param el - Element to get attribute from\n * @param canonicalName - Canonical (lowercase) attribute name\n * @returns Attribute value or null\n */\n getAttrMapped(el, canonicalName) {\n // Try mapped attribute name first (e.g., 'mapkey' -> 'map-key' for QTI 3.0)\n if (this.config.attributeNameMapper) {\n const nativeName = this.config.attributeNameMapper.toNative(canonicalName);\n const value = el.getAttribute(nativeName);\n if (value !== null)\n return value;\n }\n // Fallback to canonical name (for QTI 2.x compatibility)\n return getAttr(el, canonicalName);\n }\n /**\n * Create a simple fallback i18n provider when none is provided\n * This avoids a hard dependency on @pie-qti/i18n\n */\n createDefaultI18nProvider() {\n return {\n getLocale: () => 'en-US',\n setLocale: () => { },\n t: (key) => key, // Fallback to key\n plural: (key) => key,\n formatNumber: (value) => value.toString(),\n formatDate: (date) => date.toISOString(),\n };\n }\n /**\n * Detects the QTI version from the assessmentItem element.\n * Checks both namespace URI and version attribute.\n *\n * @returns QTI version string ('2.0', '2.1', '2.2') or 'unknown'\n */\n detectQTIVersion() {\n return this.itemDocument.detectVersion();\n }\n /**\n * Validates strict QTI 2.2 compliance if enabled in configuration.\n * Logs warnings or throws errors based on config settings.\n */\n validateStrictCompliance() {\n const config = this.config.strictQtiCompliance;\n if (!config?.enabled)\n return;\n const version = this.detectQTIVersion();\n if (version !== '2.2') {\n const message = `[QTI Player] Strict compliance enabled but item version is ${version}, not 2.2`;\n if (config.rejectUnknownExtensions) {\n throw new Error(message);\n }\n else if (config.logDeviations !== false) {\n console.warn(message);\n }\n }\n // Future: Add validation for non-standard elements/attributes\n }\n resetOutcomesToDefault() {\n for (const d of Object.values(this.decls)) {\n if (d.__kind !== 'outcome')\n continue;\n // Built-in stateful variables must survive across processing runs.\n // They are updated by the runtime (adaptive attempt tracking), not by outcome defaults.\n if (d.identifier === 'numAttempts' || d.identifier === 'completionStatus' || d.identifier === 'duration')\n continue;\n this.ctx.resetToDefault(d.identifier);\n }\n }\n resetResponsesToDefault() {\n for (const d of Object.values(this.decls)) {\n if (d.__kind !== 'response')\n continue;\n this.ctx.resetToDefault(d.identifier);\n this.restorePciResponse(d.identifier, d.value.kind === 'value' ? d.value.value : null);\n }\n }\n resetTemplatesToDefault() {\n for (const d of Object.values(this.decls)) {\n if (!d.isTemplate)\n continue;\n this.ctx.resetToDefault(d.identifier);\n }\n }\n /**\n * A MAXSCORE declared without a <defaultValue> is 0 per the numeric outcome rule, so an item\n * that never assigns it scores against a maximum of zero. That is the spec-correct reading of\n * under-specified content, and silently substituting 1 would make this engine disagree with a\n * conformant one — so surface the authoring gap instead of masking it.\n */\n warnOnceOnImpliedZeroMaxScore(outcomes) {\n if (this.warnedImpliedZeroMaxScore)\n return;\n if (!this.decls.MAXSCORE?.impliedNumericDefault)\n return;\n if (outcomes.MAXSCORE !== 0)\n return;\n this.warnedImpliedZeroMaxScore = true;\n console.warn(`[QTI Player] MAXSCORE is 0 for item \"${this.itemDocument.getAssessmentItemAttribute('identifier') ?? 'unknown'}\": its outcomeDeclaration ` +\n 'has no <defaultValue>, so QTI initializes it to 0 and response processing never assigned it. ' +\n 'Declare <defaultValue> on the MAXSCORE outcomeDeclaration to score against a real maximum.');\n }\n runResponseProcessing(options) {\n this.updateDuration();\n // Spec-aligned behavior: each processing run starts from outcome defaults.\n // This prevents stale outcomes when response/outcome processing doesn't set every variable.\n this.resetOutcomesToDefault();\n // Execute response processing if present\n if (this.responseProcessing.present) {\n // If responseProcessing has explicit statements, run the compiled program.\n // Otherwise, fall back to template-based processing (responseProcessing@template).\n if (this.responseProcessing.hasStatements) {\n this.execResponseProcessingProgram();\n }\n else if (this.responseProcessing.template) {\n this.execResponseProcessingTemplate(this.responseProcessing.template);\n }\n }\n // Execute outcome processing if present (runs after responseProcessing)\n this.execOutcomeProcessingProgram();\n // Compatibility: processResponses() has historically finalized non-adaptive items.\n // New scoreAttempt() uses this same engine with finalization disabled.\n if (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt) {\n this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'completed'));\n if (options.countAttempt ?? true) {\n const currentAttempts = this.getNumAttempts();\n this.ctx.setValue('numAttempts', qtiValue('integer', 'single', currentAttempts + 1));\n }\n }\n const outcomes = this.collectOutcomes();\n this.warnOnceOnImpliedZeroMaxScore(outcomes);\n const score = Number(outcomes.SCORE ?? 0);\n const maxScore = Number(outcomes.MAXSCORE ?? 1);\n const completionStatus = outcomes.completionStatus ?? 'not_attempted';\n const completed = completionStatus === 'completed' || (!this.isAdaptive() && options.finalizeNonAdaptiveAttempt);\n return {\n score,\n maxScore,\n completed,\n outcomeValues: outcomes,\n modalFeedback: this.getModalFeedback(outcomes),\n };\n }\n getItemBodyHtml() {\n const inner = this.itemDocument.serializeItemBodyChildren();\n if (!inner)\n return '';\n return this.renderHtmlContent(inner);\n }\n /**\n * Extract rubric blocks for the current role.\n *\n * QTI uses `<rubricBlock view=\"...\">` to provide role-specific guidance.\n * We return sanitized HTML for host rendering. `scope: \"direct\"` rubrics\n * are assessmentItem children; `scope: \"itemBody\"` rubrics are authored in\n * the rendered item body flow.\n */\n getRubrics(options = {}) {\n const role = this.role;\n const rubrics = this.itemDocument.readRubricBlocks();\n if (rubrics.length === 0)\n return [];\n const blocks = [];\n for (const rubric of rubrics) {\n const { scope } = rubric;\n if (options.scope && options.scope !== 'all' && scope !== options.scope)\n continue;\n const view = [...rubric.view];\n // If view is specified, show only when it includes the current role.\n if (view.length > 0 && role && !view.includes(role))\n continue;\n const printed = this.renderPrintedVariables(rubric.content);\n const sanitized = sanitizeHtml(printed, { security: this.config.security });\n const html = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);\n blocks.push({ view, html, scope, use: rubric.use });\n }\n return blocks;\n }\n getComponentRegistry() {\n return this.componentRegistry;\n }\n getExtractionRegistry() {\n return this.extractionRegistry;\n }\n /**\n * Canonical interaction API (new): extracted, typed interaction data.\n */\n getInteractionData() {\n if (this.interactionDataCache)\n return this.interactionDataCache;\n this.interactionDataCache = extractInteractionData({\n document: this.itemDocument,\n extractionRegistry: this.extractionRegistry,\n declarations: this.decls,\n config: this.config,\n // Seeds `shuffle`. The GUID is persisted in saved state and restored, so a\n // resumed session reproduces the order the candidate already saw, while a\n // different candidate or a new attempt gets a different one.\n sessionGuid: this.sessionGuid,\n });\n return this.interactionDataCache;\n }\n /**\n * Convenience API (used by tests/bench): returns a minimal interaction list with QTI-ish field names.\n */\n getInteractions() {\n return this.getInteractionData().map((i) => ({\n ...i,\n responseIdentifier: i.responseId,\n }));\n }\n getResponseInteractions() {\n return this.getInteractions().filter((i) => i.type !== 'endAttemptInteraction');\n }\n /**\n * Returns response identifiers of endAttempt interactions with countAttempt=\"false\".\n * Used to detect hint-only submissions (e.g. Request Hint button).\n */\n getHintEndAttemptIdentifiers() {\n return this.getInteractions()\n .filter((i) => i.type === 'endAttemptInteraction' && i.countAttempt === false)\n .map((i) => i.responseIdentifier);\n }\n getResponseIdentifiers() {\n return this.getResponseInteractions().map((i) => i.responseIdentifier);\n }\n isAdaptive() {\n return (this.itemDocument.getAssessmentItemAttribute('adaptive') || '').toLowerCase() === 'true';\n }\n getNumAttempts() {\n return Math.max(0, Math.floor(toNumber(this.ctx.getValue('numAttempts')) || 0));\n }\n getCompletionStatus() {\n const s = (toStringValue(this.ctx.getValue('completionStatus')) || '').trim();\n return (s || 'not_attempted');\n }\n isCompleted() {\n return this.getCompletionStatus() === 'completed';\n }\n runAdaptiveSubmitAttempt(countAttempt = true) {\n if (this.isCompleted()) {\n throw new Error('Cannot submit: item is already completed');\n }\n // QTI adaptive semantics: numAttempts should reflect the attempt being processed.\n if (this.isAdaptive() && countAttempt) {\n const next = this.getNumAttempts() + 1;\n this.ctx.setValue('numAttempts', qtiValue('integer', 'single', next));\n // Promote completionStatus from not_attempted -> unknown on first submission unless RP sets it.\n if (this.getCompletionStatus() === 'not_attempted') {\n this.ctx.setValue('completionStatus', qtiValue('identifier', 'single', 'unknown'));\n }\n }\n const base = this.processResponses();\n const completionStatus = this.getCompletionStatus();\n const completed = completionStatus === 'completed';\n const canContinue = this.isAdaptive() ? !completed : false;\n return {\n ...base,\n completed,\n numAttempts: this.getNumAttempts(),\n completionStatus,\n canContinue,\n };\n }\n getResponses() {\n const out = {};\n for (const d of Object.values(this.decls)) {\n if (d.__kind !== 'response')\n continue;\n const pciHost = this._pciHosts.get(d.identifier);\n if (pciHost) {\n const currentResponse = pciHost.getResponse();\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, currentResponse, d.identifier);\n }\n out[d.identifier] = this.qtiValueToPublic(d.value);\n }\n return out;\n }\n /**\n * Get correct response for a specific response identifier\n * @param responseId - The response identifier\n * @returns The correct response value, or undefined if not available\n */\n getCorrectResponse(responseId) {\n const decl = this.decls[responseId];\n if (!decl || decl.__kind !== 'response')\n return undefined;\n const respDecl = decl; // ResponseDeclaration from qti-processing\n if (!respDecl.correctResponse)\n return undefined;\n if (respDecl.correctResponse.kind !== 'value')\n return undefined;\n return this.qtiValueToPublic(respDecl.correctResponse);\n }\n /**\n * Get all correct responses as a map\n * @returns Map of responseId to correct response value\n */\n getCorrectResponses() {\n const out = {};\n for (const d of Object.values(this.decls)) {\n if (d.__kind !== 'response')\n continue;\n const respDecl = d;\n if (!respDecl.correctResponse || respDecl.correctResponse.kind !== 'value')\n continue;\n out[d.identifier] = this.qtiValueToPublic(respDecl.correctResponse);\n }\n return out;\n }\n getTemplateVariables() {\n const out = {};\n for (const d of Object.values(this.decls)) {\n if (!d.isTemplate)\n continue;\n out[d.identifier] = this.qtiValueToPublic(d.value);\n }\n return out;\n }\n setTemplateVariables(vars) {\n for (const [id, raw] of Object.entries(vars)) {\n const d = this.decls[id];\n if (!d?.isTemplate)\n continue;\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);\n }\n }\n getSessionState() {\n const out = {};\n for (const d of Object.values(this.decls)) {\n out[d.identifier] = this.qtiValueToPublic(d.value);\n }\n return out;\n }\n validateResponses(responses) {\n const interactions = this.getInteractions();\n const entries = {};\n const issues = [];\n for (const i of interactions) {\n const responseId = i.responseIdentifier;\n const decl = this.decls[responseId];\n const value = responses[responseId];\n const isMeaningfulEntry = (entry) => {\n if (entry === null || entry === undefined)\n return false;\n if (typeof entry !== 'string')\n return true;\n const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'\n ? entry.replace(/<[^>]*>/g, '').replace(/ | /gi, ' ')\n : entry;\n return comparable.trim().length > 0;\n };\n const constrainedChoices = [\n ...(i.choices ?? []),\n ...(i.gapTexts ?? []),\n ...(i.gapImages ?? []),\n ...(i.sourceSet ?? []),\n ...(i.targetSet ?? []),\n ...(i.associableHotspots ?? []),\n ];\n const minimum = Math.max(0, Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0), Number(i.minPlays ?? 0));\n const required = i.type !== 'endAttemptInteraction' &&\n (minimum > 0 || constrainedChoices.some((choice) => Number(choice.matchMin ?? 0) > 0));\n let complete = !required;\n if (i.type === 'mediaInteraction' && required) {\n const minPlays = Number(i.minPlays || 0);\n complete = Number(value || 0) >= minPlays;\n }\n else if (required) {\n if (Array.isArray(value)) {\n const nonEmptyValues = value.filter(isMeaningfulEntry);\n complete = nonEmptyValues.length > 0;\n // Enforce minChoices / minAssociations where applicable\n const minChoices = Math.max(Number(i.minChoices ?? 0), Number(i.minAssociations ?? 0), Number(i.minStrings ?? 0));\n if (complete && minChoices > 0) {\n complete = nonEmptyValues.length >= minChoices;\n }\n // Enforce matchMin per-choice: each pairing entry \"id1 id2\" in value must\n // appear at least matchMin times for the relevant choice.\n // Collect all choice arrays that can carry matchMin across all pairing interaction types.\n for (const choice of constrainedChoices) {\n const min = Number(choice.matchMin || 0);\n if (min > 0) {\n const count = value.filter((p) => {\n const parts = p.split(' ');\n return parts[0] === choice.identifier || parts[1] === choice.identifier;\n }).length;\n if (count < min) {\n complete = false;\n break;\n }\n }\n }\n }\n else if (decl?.cardinality === 'record') {\n const stringValue = value && typeof value === 'object'\n ? value.stringValue\n : undefined;\n complete = isMeaningfulEntry(stringValue);\n }\n else {\n complete = isMeaningfulEntry(value);\n }\n }\n const errors = [];\n const warnings = [];\n if (decl) {\n if (decl.cardinality === 'multiple' || decl.cardinality === 'ordered') {\n if (!(value === null || value === undefined || Array.isArray(value))) {\n errors.push(`Expected an array for ${decl.cardinality} response '${responseId}'`);\n }\n }\n else if (decl.cardinality === 'record') {\n if (!(value === null || value === undefined || (typeof value === 'object' && !Array.isArray(value)))) {\n errors.push(`Expected an object for record response '${responseId}'`);\n }\n }\n else {\n if (Array.isArray(value)) {\n errors.push(`Expected a single value for response '${responseId}'`);\n }\n }\n }\n if (i.type === 'extendedTextInteraction' &&\n Array.isArray(value) &&\n Number(i.maxStrings ?? 0) > 0 &&\n value.filter(isMeaningfulEntry).length > Number(i.maxStrings)) {\n errors.push(`Response '${responseId}' exceeds maxStrings=${i.maxStrings}`);\n }\n const valid = errors.length === 0;\n entries[responseId] = {\n responseId,\n interactionType: i.type,\n required,\n complete,\n valid,\n errors,\n warnings,\n };\n for (const e of errors) {\n issues.push({\n responseId,\n code: 'invalid_shape',\n message: e,\n severity: 'error',\n });\n }\n }\n const allValid = Object.values(entries).every((e) => e.valid);\n return { valid: allValid, entries, issues };\n }\n getProgress(responses) {\n const v = this.validateResponses(responses);\n const required = Object.values(v.entries).filter((e) => e.required);\n const answered = required.filter((e) => e.complete).length;\n const total = required.length;\n return { total, answered, unanswered: Math.max(0, total - answered) };\n }\n canSubmitResponses(responses) {\n const v = this.validateResponses(responses);\n const required = Object.values(v.entries).filter((e) => e.required);\n return v.valid && required.every((e) => e.complete);\n }\n /**\n * True if the learner has made any meaningful interaction, even if submission is not yet allowed.\n * Used by assessment/session controllers to track \"answered\" state.\n */\n isAttempted(responses) {\n for (const i of this.getResponseInteractions()) {\n const id = i.responseIdentifier;\n const v = responses[id];\n const isMeaningful = (entry) => {\n if (entry === null || entry === undefined)\n return false;\n if (typeof entry !== 'string')\n return true;\n const comparable = i.type === 'extendedTextInteraction' && i.format === 'xhtml'\n ? entry.replace(/<[^>]*>/g, '').replace(/ | /gi, ' ')\n : entry;\n return comparable.trim().length > 0;\n };\n if (i.type === 'mediaInteraction') {\n if (Number(v || 0) > 0)\n return true;\n continue;\n }\n if (Array.isArray(v)) {\n if (v.some(isMeaningful))\n return true;\n continue;\n }\n if (v && typeof v === 'object') {\n const record = v;\n if (Object.values(record).some(isMeaningful))\n return true;\n continue;\n }\n if (isMeaningful(v))\n return true;\n }\n return false;\n }\n // ----------------------------------------------------------------------------\n // Execution\n // ----------------------------------------------------------------------------\n execTemplateProcessing() {\n if (!this.templateProcessingProgram)\n return;\n execProgram({\n ctx: this.ctx,\n ops: this.ops,\n rng: this.rng,\n customOperators: this.config.customOperators,\n }, this.templateProcessingProgram);\n }\n execResponseProcessingProgram() {\n if (!this.responseProcessingProgram)\n return;\n execProgram({\n ctx: this.ctx,\n ops: this.ops,\n rng: this.rng,\n customOperators: this.config.customOperators,\n }, this.responseProcessingProgram);\n }\n execOutcomeProcessingProgram() {\n if (!this.outcomeProcessingProgram)\n return;\n execProgram({\n ctx: this.ctx,\n ops: this.ops,\n rng: this.rng,\n customOperators: this.config.customOperators,\n }, this.outcomeProcessingProgram);\n }\n execResponseProcessingTemplate(templateUrl) {\n const name = templateUrl.split('/').pop()?.toLowerCase().replace(/\\.xml$/, '');\n if (!name) {\n console.warn(`[QTI Player] Could not extract template name from URL: ${templateUrl}`);\n return;\n }\n const responseMatchesCorrect = () => {\n const expression = {\n kind: 'expr.match',\n id: 'fixed-template-match',\n a: { kind: 'expr.variable', id: 'fixed-template-response', identifier: 'RESPONSE' },\n b: { kind: 'expr.correct', id: 'fixed-template-correct', identifier: 'RESPONSE' },\n };\n return toBoolean(evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, expression));\n };\n const setScore = (value) => {\n this.ctx.setValue('SCORE', qtiValue('float', 'single', value));\n };\n const setIdentifierOutcome = (identifier, value) => {\n this.ctx.setValue(identifier, qtiValue('identifier', 'single', value));\n };\n const mapResponse = (point) => {\n const response = this.ctx.getValue('RESPONSE');\n if (response.kind === 'null')\n return 0;\n const mapped = evalExpr({ ctx: this.ctx, ops: this.ops, rng: this.rng, customOperators: this.config.customOperators }, {\n kind: point ? 'expr.mapResponsePoint' : 'expr.mapResponse',\n id: point ? 'fixed-template-map-response-point' : 'fixed-template-map-response',\n identifier: 'RESPONSE',\n });\n const value = toNumber(mapped);\n return Number.isFinite(value) ? value : 0;\n };\n switch (name) {\n case 'match_correct':\n case 'cc2_match': {\n setScore(responseMatchesCorrect() ? 1 : 0);\n return;\n }\n case 'cc2_match_basic': {\n if (responseMatchesCorrect()) {\n const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));\n this.ctx.setValue('SCORE', Number.isFinite(maxScore) ? qtiValue('float', 'single', maxScore) : qtiNull('float', 'single'));\n setIdentifierOutcome('FEEDBACKBASIC', 'correct');\n }\n else {\n setIdentifierOutcome('FEEDBACKBASIC', 'incorrect');\n }\n return;\n }\n case 'match_nothing':\n case 'cc2_match_nothing': { // QTI 2.1 compatibility\n const isEmptyResponse = (v) => {\n if (!v)\n return true;\n if (v.kind === 'null')\n return true;\n if (v.kind === 'invalid')\n return false;\n if (v.value === null || v.value === undefined)\n return true;\n if (Array.isArray(v.value))\n return v.value.length === 0;\n if (typeof v.value === 'string')\n return v.value.trim().length === 0;\n return false;\n };\n const allEmpty = isEmptyResponse(this.ctx.getValue('RESPONSE'));\n const max = toNumber(this.ctx.getValue('MAXSCORE'));\n this.ctx.setValue('SCORE', qtiValue('float', 'single', allEmpty ? (Number.isFinite(max) ? max : 1) : 0));\n return;\n }\n case 'map_response': {\n setScore(mapResponse(false));\n return;\n }\n case 'cc2_map_response': {\n const score = mapResponse(false);\n setScore(score);\n const maxScore = toNumber(this.ctx.getValue('MAXSCORE'));\n setIdentifierOutcome('FEEDBACK', Number.isFinite(maxScore) && score === maxScore ? 'correct' : 'incorrect');\n return;\n }\n case 'map_response_point':\n case 'cc2_map_response_point': { // QTI 2.1 compatibility\n setScore(mapResponse(true));\n return;\n }\n default:\n console.warn(`[QTI Player] Unsupported response processing template: ${name}`);\n return;\n }\n }\n // ----------------------------------------------------------------------------\n // Declarations\n // ----------------------------------------------------------------------------\n buildDeclarations() {\n const decls = {};\n const addDecl = (kind, el) => {\n const identifier = this.getAttrMapped(el, 'identifier');\n const cardinality = (this.getAttrMapped(el, 'cardinality') || 'single');\n const baseType = cardinality === 'record'\n ? undefined\n : (this.getAttrMapped(el, 'baseType') || 'string');\n if (!identifier)\n return;\n const declaredDefault = this.parseDefaultValue(el, baseType, cardinality);\n const impliedNumericDefault = !declaredDefault && this.hasImpliedNumericDefault(kind, baseType, cardinality);\n const defaultValue = declaredDefault ?? this.impliedDefaultValue(kind, baseType, cardinality);\n decls[identifier] = {\n identifier,\n ...(baseType ? { baseType } : {}),\n cardinality,\n defaultValue,\n value: defaultValue,\n isTemplate: kind === 'template',\n impliedNumericDefault,\n // @ts-expect-error internal marker for templates\n __kind: kind,\n };\n // Response + outcome declarations may define mappings used by mapResponse/mapOutcome.\n // (Templates do not participate in mapping.)\n if (kind === 'response' || kind === 'outcome') {\n const mappingEl = findFirstDescendant(el, this.mapper.toNative('mapping'));\n if (mappingEl && baseType) {\n decls[identifier].mapping = this.parseMapping(mappingEl, baseType);\n }\n }\n // Outcome declarations may define a lookup table (matchTable or interpolationTable)\n // used by the lookupOutcomeValue rule.\n if (kind === 'outcome') {\n const matchTableEl = findFirstDescendant(el, this.mapper.toNative('matchtable'));\n const interpolationTableEl = findFirstDescendant(el, this.mapper.toNative('interpolationtable'));\n if (matchTableEl) {\n decls[identifier].lookupTable = this.parseMatchTable(matchTableEl);\n }\n else if (interpolationTableEl) {\n decls[identifier].lookupTable = this.parseInterpolationTable(interpolationTableEl);\n }\n }\n if (kind === 'response') {\n const correctEl = findFirstDescendant(el, this.mapper.toNative('correctresponse'));\n if (correctEl) {\n decls[identifier].correctResponse = this.parseCorrectResponse(correctEl, baseType, cardinality);\n }\n const areaMappingEl = findFirstDescendant(el, this.mapper.toNative('areamapping'));\n if (areaMappingEl) {\n decls[identifier].areaMapping = this.parseAreaMapping(areaMappingEl);\n }\n }\n };\n for (const el of this.itemDocument.findDeclarationElements('response'))\n addDecl('response', el);\n for (const el of this.itemDocument.findDeclarationElements('outcome'))\n addDecl('outcome', el);\n for (const el of this.itemDocument.findDeclarationElements('template'))\n addDecl('template', el);\n return decls;\n }\n parseMatchTable(el) {\n const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();\n const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;\n return {\n kind: 'table.matchTable',\n defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,\n entries: findDescendants(el, this.mapper.toNative('matchtableentry')).map((e) => ({\n sourceValue: (getAttr(e, 'sourceValue') || '').trim(),\n targetValue: (getAttr(e, 'targetValue') || '').trim(),\n })),\n };\n }\n parseInterpolationTable(el) {\n const defaultValueRaw = (getAttr(el, 'defaultValue') || '').trim();\n const defaultValue = defaultValueRaw ? Number(defaultValueRaw) : undefined;\n const interpolationMethod = (getAttr(el, 'interpolationMethod') || 'linear').trim();\n return {\n kind: 'table.interpolationTable',\n defaultValue: Number.isFinite(defaultValue) ? defaultValue : undefined,\n interpolationMethod,\n entries: findDescendants(el, this.mapper.toNative('interpolationtableentry'))\n .map((e) => ({\n sourceValue: Number((getAttr(e, 'sourceValue') || '').trim()),\n targetValue: Number((getAttr(e, 'targetValue') || '').trim()),\n }))\n .filter((e) => Number.isFinite(e.sourceValue) && Number.isFinite(e.targetValue)),\n };\n }\n ensureBuiltinDeclarations(decls) {\n // completionStatus + numAttempts are defined in QTI (esp. adaptive items) and commonly used\n // without explicit outcomeDeclaration in authoring content.\n if (!decls.completionStatus) {\n decls.completionStatus = {\n identifier: 'completionStatus',\n baseType: 'identifier',\n cardinality: 'single',\n value: qtiValue('identifier', 'single', 'not_attempted'),\n isTemplate: false,\n // @ts-expect-error internal marker\n __kind: 'outcome',\n };\n }\n if (!decls.numAttempts) {\n decls.numAttempts = {\n identifier: 'numAttempts',\n baseType: 'integer',\n cardinality: 'single',\n defaultValue: qtiValue('integer', 'single', 0),\n value: qtiValue('integer', 'single', 0),\n isTemplate: false,\n // @ts-expect-error internal marker\n __kind: 'outcome',\n };\n }\n if (!decls.duration) {\n decls.duration = {\n identifier: 'duration',\n baseType: 'duration',\n cardinality: 'single',\n defaultValue: qtiValue('duration', 'single', 0),\n value: qtiValue('duration', 'single', 0),\n isTemplate: false,\n // @ts-expect-error internal marker\n __kind: 'outcome',\n };\n }\n // Common scoring defaults\n if (!decls.SCORE) {\n decls.SCORE = {\n identifier: 'SCORE',\n baseType: 'float',\n cardinality: 'single',\n value: qtiValue('float', 'single', 0),\n isTemplate: false,\n // @ts-expect-error internal marker\n __kind: 'outcome',\n };\n }\n if (!decls.MAXSCORE) {\n decls.MAXSCORE = {\n identifier: 'MAXSCORE',\n baseType: 'float',\n cardinality: 'single',\n value: qtiValue('float', 'single', 1),\n isTemplate: false,\n // @ts-expect-error internal marker\n __kind: 'outcome',\n };\n }\n }\n applySessionState(state) {\n for (const [id, raw] of Object.entries(state)) {\n const d = this.decls[id];\n if (!d)\n continue;\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, raw, d.identifier);\n }\n const restoredDuration = Number(state.duration);\n if (Number.isFinite(restoredDuration) && restoredDuration >= 0) {\n this.accumulatedDurationMs = restoredDuration;\n this.sessionStartedAt = Date.now();\n this.updateDuration();\n }\n }\n applySerializedVariables(vars) {\n for (const v of Object.values(vars)) {\n const d = this.decls[v.identifier];\n if (!d)\n continue;\n d.value = this.coerceToDeclarationValue(d.baseType, d.cardinality, v.value, d.identifier);\n if (d.__kind === 'response') {\n this.restorePciResponse(d.identifier, this.qtiValueToPublic(d.value));\n }\n }\n }\n serializeItemSession() {\n const responseVariables = {};\n const outcomeVariables = {};\n const templateVariables = {};\n const contextVariables = {};\n const contextIds = new Set(['completionStatus', 'numAttempts', 'duration']);\n for (const d of Object.values(this.decls)) {\n const variable = this.serializeVariable(d);\n if (d.isTemplate) {\n templateVariables[d.identifier] = { ...variable, kind: 'template' };\n }\n else if (contextIds.has(d.identifier)) {\n contextVariables[d.identifier] = { ...variable, kind: 'context' };\n }\n else if (d.__kind === 'response') {\n responseVariables[d.identifier] = { ...variable, kind: 'response' };\n }\n else if (d.__kind === 'outcome') {\n outcomeVariables[d.identifier] = { ...variable, kind: 'outcome' };\n }\n }\n const validation = this.validateResponses(this.getResponses());\n return {\n itemIdentifier: this.itemDocument.getAssessmentItemAttribute('identifier') ?? undefined,\n sessionGuid: this.sessionGuid,\n lifecycleStatus: this.lifecycleStatus,\n completionStatus: this.getCompletionStatus(),\n numAttempts: this.getNumAttempts(),\n duration: this.getDuration(),\n responseVariables,\n outcomeVariables,\n templateVariables,\n contextVariables,\n validationMessages: validation.issues,\n savedAt: new Date().toISOString(),\n };\n }\n serializeVariable(d) {\n return {\n identifier: d.identifier,\n kind: (d.__kind ?? (d.isTemplate ? 'template' : 'context')),\n ...(d.baseType ? { baseType: d.baseType } : {}),\n cardinality: d.cardinality,\n value: this.qtiValueToSerializable(d.value),\n defaultValue: this.qtiValueToSerializable(d.defaultValue),\n };\n }\n qtiValueToSerializable(value) {\n if (!value || value.kind !== 'value')\n return null;\n if (value.cardinality !== 'record')\n return cloneRuntimeValue(value.value);\n const serialized = {};\n for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {\n serialized[fieldIdentifier] = {\n ...(fieldValue.baseType ? { baseType: fieldValue.baseType } : {}),\n cardinality: fieldValue.cardinality ?? 'single',\n value: this.qtiValueToSerializable(fieldValue),\n };\n }\n return serialized;\n }\n qtiValueToPublic(value) {\n if (!value || value.kind !== 'value')\n return null;\n if (value.cardinality !== 'record')\n return cloneRuntimeValue(value.value);\n const record = {};\n for (const [fieldIdentifier, fieldValue] of Object.entries(value.value)) {\n record[fieldIdentifier] = this.qtiValueToPublic(fieldValue);\n }\n return record;\n }\n updateDuration() {\n const elapsedMs = Math.max(0, Date.now() - this.sessionStartedAt);\n const durationMs = this.accumulatedDurationMs + elapsedMs;\n this.ctx.setValue('duration', qtiValue('duration', 'single', durationMs));\n }\n freezeDuration() {\n this.updateDuration();\n const duration = this.getDuration();\n this.accumulatedDurationMs = duration;\n this.sessionStartedAt = Date.now();\n return duration;\n }\n getDuration() {\n const value = this.ctx.getValue('duration');\n return Math.max(0, Math.floor(toNumber(value) || 0));\n }\n /**\n * QTI 2.1 §5.2, carried into 2.2 and 3.0: an outcome variable with no declared default is\n * initialized to NULL unless it is of a numeric type, in which case it is initialized to 0.\n * Response and template variables keep NULL — an unanswered numeric response must stay\n * distinguishable from an answered zero.\n */\n hasImpliedNumericDefault(kind, baseType, cardinality) {\n if (kind !== 'outcome' || cardinality !== 'single')\n return false;\n return baseType === 'integer' || baseType === 'float';\n }\n impliedDefaultValue(kind, baseType, cardinality) {\n if (this.hasImpliedNumericDefault(kind, baseType, cardinality)) {\n return qtiValue(baseType, 'single', 0);\n }\n return qtiNull(baseType, cardinality);\n }\n /** Returns undefined when the declaration carries no <defaultValue> at all. */\n parseDefaultValue(declEl, baseType, cardinality) {\n const defaultEl = findFirstDescendant(declEl, this.mapper.toNative('defaultvalue'));\n if (!defaultEl)\n return undefined;\n return this.parseDeclarationValues(defaultEl, baseType, cardinality);\n }\n parseCorrectResponse(correctEl, baseType, cardinality) {\n return this.parseDeclarationValues(correctEl, baseType, cardinality);\n }\n parseDeclarationValues(container, baseType, cardinality) {\n const valueElements = findDescendants(container, this.mapper.toNative('value'));\n if (cardinality === 'record') {\n const record = {};\n for (const valueElement of valueElements) {\n const fieldIdentifier = this.getAttrMapped(valueElement, 'fieldIdentifier');\n const fieldBaseType = this.getAttrMapped(valueElement, 'baseType');\n if (!fieldIdentifier || !fieldBaseType)\n continue;\n record[fieldIdentifier] = coerceBaseValue(fieldBaseType, valueElement.textContent || '');\n }\n return Object.keys(record).length > 0\n ? qtiValue(undefined, 'record', record)\n : qtiNull(undefined, 'record');\n }\n if (!baseType)\n return qtiNull(undefined, cardinality);\n const values = valueElements.map((value) => (value.textContent || '').trim());\n if (cardinality === 'multiple' || cardinality === 'ordered') {\n return qtiValue(baseType, cardinality, values.map((t) => {\n const v = coerceBaseValue(baseType, t);\n return v.kind === 'value' ? v.value : null;\n }));\n }\n return coerceBaseValue(baseType, values[0] ?? '');\n }\n parseMapping(mappingEl, baseType) {\n const defaultValue = Number(this.getAttrMapped(mappingEl, 'defaultValue') || 0);\n const lowerBound = this.getAttrMapped(mappingEl, 'lowerBound') ? Number(this.getAttrMapped(mappingEl, 'lowerBound')) : undefined;\n const upperBound = this.getAttrMapped(mappingEl, 'upperBound') ? Number(this.getAttrMapped(mappingEl, 'upperBound')) : undefined;\n const mappingCaseSensitive = this.getAttrMapped(mappingEl, 'caseSensitive') || 'true';\n const entries = {};\n const normalizePairKey = (k) => {\n const parts = k.trim().split(/\\s+/).filter(Boolean);\n if (parts.length === 2)\n return [...parts].sort().join(' ');\n return k.trim();\n };\n const normalizeDirectedPairKey = (k) => {\n const parts = k.trim().split(/\\s+/).filter(Boolean);\n if (parts.length >= 2)\n return `${parts[0]} ${parts[1]}`;\n return k.trim();\n };\n for (const e of findDescendants(mappingEl, this.mapper.toNative('mapentry'))) {\n const mapKey = this.getAttrMapped(e, 'mapKey');\n const mappedValue = this.getAttrMapped(e, 'mappedValue');\n if (!mapKey || mappedValue === null)\n continue;\n const effectiveCaseSensitive = this.getAttrMapped(e, 'caseSensitive') || mappingCaseSensitive || 'true';\n const storedKey = baseType === 'pair'\n ? normalizePairKey(mapKey)\n : baseType === 'directedPair'\n ? normalizeDirectedPairKey(mapKey)\n : mapKey;\n entries[storedKey] = { mapKey: storedKey, mappedValue: Number(mappedValue), caseSensitive: effectiveCaseSensitive };\n if (effectiveCaseSensitive !== 'true') {\n const lowerKey = storedKey.toLowerCase();\n entries[lowerKey] = {\n mapKey: lowerKey,\n mappedValue: Number(mappedValue),\n caseSensitive: effectiveCaseSensitive,\n };\n }\n }\n return { defaultValue, lowerBound, upperBound, caseSensitive: mappingCaseSensitive, entries };\n }\n parseAreaMapping(areaMappingEl) {\n const defaultValue = Number(getAttr(areaMappingEl, 'defaultValue') || 0);\n const lowerBound = getAttr(areaMappingEl, 'lowerBound')\n ? Number(getAttr(areaMappingEl, 'lowerBound'))\n : undefined;\n const upperBound = getAttr(areaMappingEl, 'upperBound')\n ? Number(getAttr(areaMappingEl, 'upperBound'))\n : undefined;\n const entries = [];\n for (const e of findDescendants(areaMappingEl, this.mapper.toNative('areamapentry'))) {\n const shape = (getAttr(e, 'shape') || 'default');\n const coords = String(getAttr(e, 'coords') || '');\n const mappedValue = Number(getAttr(e, 'mappedValue') || 0);\n entries.push({ shape, coords, mappedValue });\n }\n return { defaultValue, lowerBound, upperBound, entries };\n }\n coerceToDeclarationValue(baseType, cardinality, raw, identifier) {\n if (raw === null || raw === undefined)\n return qtiNull(baseType, cardinality);\n // Allow callers to pass fully-formed QtiValue (e.g. session restore).\n if (typeof raw === 'object' && raw && 'kind' in raw) {\n return cloneRuntimeValue(raw);\n }\n const extendedTextBase = identifier ? this.getExtendedTextBase(identifier) : undefined;\n if (cardinality === 'record') {\n return this.coerceRecordValue(raw, extendedTextBase ?? 10);\n }\n if (!baseType)\n return qtiNull(undefined, cardinality);\n // For file types, preserve QTIFileResponse objects directly\n if (baseType === 'file') {\n if (cardinality === 'multiple' || cardinality === 'ordered') {\n const arr = Array.isArray(raw) ? raw : [raw];\n return qtiValue(baseType, cardinality, cloneRuntimeValue(arr.filter((v) => v !== null && v !== undefined)));\n }\n return qtiValue(baseType, cardinality, cloneRuntimeValue(raw));\n }\n if (cardinality === 'multiple' || cardinality === 'ordered') {\n const arr = Array.isArray(raw) ? raw : [raw];\n const coerced = arr\n .map((v) => String(v ?? '').trim())\n .filter((s) => s.length > 0)\n .map((t) => {\n if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {\n const numeric = createExtendedTextNumericRecord(t, extendedTextBase);\n return baseType === 'integer' ? numeric.integerValue : numeric.floatValue;\n }\n const v = coerceBaseValue(baseType, t);\n return v.kind === 'value' ? v.value : null;\n })\n .filter((v) => v !== null);\n // Multiple/ordered can legitimately be an empty container (distinct from null).\n return qtiValue(baseType, cardinality, coerced);\n }\n const t = String(raw ?? '').trim();\n if (t.length === 0)\n return qtiNull(baseType, cardinality);\n if (extendedTextBase && (baseType === 'integer' || baseType === 'float')) {\n const numeric = createExtendedTextNumericRecord(t, extendedTextBase);\n const value = baseType === 'integer' ? numeric.integerValue : numeric.floatValue;\n return value === null ? qtiNull(baseType, 'single') : qtiValue(baseType, 'single', value);\n }\n return coerceBaseValue(baseType, t);\n }\n getExtendedTextBase(responseIdentifier) {\n return this.itemDocument.getExtendedTextBase(responseIdentifier);\n }\n coerceRecordValue(raw, base) {\n let source = raw;\n if (typeof source === 'string') {\n const stringSource = source;\n if (stringSource.trim().length === 0)\n return qtiNull(undefined, 'record');\n if (stringSource.trimStart().startsWith('{')) {\n try {\n source = JSON.parse(stringSource);\n }\n catch {\n return qtiNull(undefined, 'record');\n }\n }\n else {\n source = createExtendedTextNumericRecord(stringSource, base);\n }\n }\n if (!source || typeof source !== 'object' || Array.isArray(source)) {\n return qtiNull(undefined, 'record');\n }\n const fields = {};\n for (const [fieldIdentifier, rawField] of Object.entries(source)) {\n if (rawField && typeof rawField === 'object' && 'kind' in rawField) {\n fields[fieldIdentifier] = rawField;\n continue;\n }\n let fieldBaseType = EXTENDED_TEXT_RECORD_FIELD_TYPES[fieldIdentifier];\n let fieldValue = rawField;\n if (rawField && typeof rawField === 'object' && !Array.isArray(rawField) && 'value' in rawField) {\n const serializedField = rawField;\n fieldBaseType = serializedField.baseType ?? fieldBaseType;\n fieldValue = serializedField.value;\n }\n if (!fieldBaseType) {\n fieldBaseType = typeof fieldValue === 'boolean'\n ? 'boolean'\n : typeof fieldValue === 'number'\n ? (Number.isInteger(fieldValue) ? 'integer' : 'float')\n : 'string';\n }\n if (fieldValue === null || fieldValue === undefined) {\n fields[fieldIdentifier] = qtiNull(fieldBaseType, 'single');\n }\n else if (fieldBaseType === 'file' && typeof fieldValue === 'object') {\n fields[fieldIdentifier] = qtiValue('file', 'single', fieldValue);\n }\n else {\n fields[fieldIdentifier] = coerceBaseValue(fieldBaseType, String(fieldValue));\n }\n }\n return Object.keys(fields).length > 0\n ? qtiValue(undefined, 'record', fields)\n : qtiNull(undefined, 'record');\n }\n collectOutcomes() {\n const out = {};\n for (const d of Object.values(this.decls)) {\n if (d.__kind !== 'outcome')\n continue;\n if (d.value.kind === 'value')\n out[d.identifier] = this.qtiValueToPublic(d.value);\n else if (d.value.kind === 'null')\n out[d.identifier] = null;\n }\n // Ensure MAXSCORE always has a value (fallback to 1.0 if null or missing)\n if (out.MAXSCORE === null || out.MAXSCORE === undefined) {\n out.MAXSCORE = 1.0;\n }\n return out;\n }\n // ----------------------------------------------------------------------------\n // printedVariable + feedback\n // ----------------------------------------------------------------------------\n renderPrintedVariables(html) {\n const readIdentifier = (attrs) => {\n const m = attrs.match(/identifier\\s*=\\s*(?:\"([^\"]+)\"|'([^']+)'|([^\\s>]+))/i);\n return (m?.[1] || m?.[2] || m?.[3] || '').trim() || null;\n };\n const renderId = (id) => {\n if (!id)\n return '';\n const v = this.ctx.getValue(id);\n if (v.kind !== 'value')\n return '';\n if (Array.isArray(v.value))\n return v.value.map(String).join(', ');\n return String(v.value);\n };\n let out = html.replace(/<printedVariable\\b([^>]*)>([\\s\\S]*?)<\\/printedVariable>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));\n out = out.replace(/<printedVariable\\b([^>]*)\\/>/gi, (_m, attrs) => renderId(readIdentifier(String(attrs))));\n return out;\n }\n renderHtmlContent(html) {\n const printed = this.renderPrintedVariables(html);\n const sanitized = sanitizeHtml(printed, { security: this.config.security });\n return toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);\n }\n getModalFeedback(outcomes) {\n const active = [];\n for (const feedback of this.itemDocument.readModalFeedback()) {\n const { identifier, outcomeIdentifier, showHide, title } = feedback;\n const sanitized = sanitizeHtml(feedback.content, { security: this.config.security });\n const content = toTrustedHtml(sanitized, this.config.security?.trustedTypesPolicyName);\n const outcomeValue = outcomes[outcomeIdentifier];\n const shouldShow = showHide === 'show' ? outcomeValue === identifier : outcomeValue !== identifier;\n if (shouldShow && content) {\n active.push({ identifier, outcomeIdentifier, showHide, content, title });\n }\n }\n return active;\n }\n}\n// ---------------------------------------------------------------------------\n// Module-level helpers\n// ---------------------------------------------------------------------------\nfunction mergePnp(base, partial) {\n return {\n display: { ...(base?.display ?? {}), ...(partial.display ?? {}) },\n content: { ...(base?.content ?? {}), ...(partial.content ?? {}) },\n cognitive: { ...(base?.cognitive ?? {}), ...(partial.cognitive ?? {}) },\n };\n}\nfunction createSessionGuid() {\n // `Crypto` is typed as always providing `randomUUID`, but it is restricted to secure\n // contexts and so is genuinely absent when the player is served over plain HTTP.\n // Reading through a `Partial<Crypto>` keeps TypeScript from narrowing the fallback\n // branch to `never` on the strength of a type that overstates what is available.\n const webCrypto = typeof crypto !== 'undefined' ? crypto : undefined;\n if (typeof webCrypto?.randomUUID === 'function') {\n return webCrypto.randomUUID();\n }\n // `getRandomValues` carries no secure-context restriction and offers the same entropy\n // guarantee, so it covers the plain-HTTP case. The previous fallback here used\n // `Math.random()`, which is not a CSPRNG and left session GUIDs predictable in\n // exactly the environments that reached it.\n if (typeof webCrypto?.getRandomValues === 'function') {\n const bytes = new Uint8Array(16);\n webCrypto.getRandomValues(bytes);\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n return `item-session-${hex}`;\n }\n throw new Error('No Web Crypto API available: cannot generate a session GUID. @pie-qti/item-player ' +\n 'requires crypto.randomUUID or crypto.getRandomValues (present in all supported ' +\n 'browsers and in Node >= 20).');\n}\nfunction cloneDeclarationMap(declarations) {\n return structuredClone(declarations);\n}\n/** Detach serializable runtime values from caller- and declaration-owned references. */\nfunction cloneRuntimeValue(value) {\n if (!value || typeof value !== 'object')\n return value;\n return structuredClone(value);\n}\nfunction looksLikeCatalogUrl(value) {\n const trimmed = value.trim();\n return /^(https?:\\/\\/|\\/\\/|\\/|\\.{0,2}\\/|data:|blob:)/i.test(trimmed) ||\n /\\.(png|jpe?g|gif|webp|svg|mp3|wav|ogg|mp4|webm|pdf)(\\?.*)?$/i.test(trimmed);\n}\n//# sourceMappingURL=Player.js.map","const ROLES_WITH_CORRECT_RESPONSE_ACCESS = new Set([\n 'scorer',\n 'author',\n 'tutor',\n 'testConstructor',\n]);\nexport function getRoleCapabilities(role) {\n const isCandidate = role === 'candidate';\n const canViewCorrectResponses = ROLES_WITH_CORRECT_RESPONSE_ACCESS.has(role);\n return {\n isCandidate,\n isReadOnly: !isCandidate,\n canViewCorrectResponses,\n };\n}\n//# sourceMappingURL=rolePolicy.js.map","/**\n * Feedback text utilities for QTI items\n *\n * NOTE: The cleanFeedbackText function contains vendor-specific transforms\n * for content that uses semicolons after \"Correct\" and \"Incorrect\" labels.\n * This is common in some QTI authoring tools but not part of the QTI specification.\n *\n * To customize this behavior for your vendor's content, you can:\n * 1. Modify the patterns in this file\n * 2. Create a vendor-specific transform plugin (see VENDOR-TRANSFORM-PLUGIN-GUIDE.md)\n * 3. Pass custom transforms via the feedbackTransforms option\n */\n/**\n * Default feedback text transforms\n * These are vendor-specific patterns commonly found in certain QTI authoring tools\n */\nexport const DEFAULT_FEEDBACK_TRANSFORMS = [\n // Remove semicolons after \"Incorrect\" (with or without <strong> tags)\n { pattern: /<strong>Incorrect;<\\/strong>/gi, replacement: '<strong>Incorrect</strong> ' },\n { pattern: /Incorrect;/gi, replacement: 'Incorrect ' },\n // Remove semicolons after \"Correct\" (with or without <strong> tags)\n { pattern: /<strong>Correct;<\\/strong>/gi, replacement: '<strong>Correct</strong> ' },\n { pattern: /Correct;/gi, replacement: 'Correct ' },\n];\n/**\n * Clean up feedback text formatting using configurable transforms\n *\n * @param content - The feedback content HTML string\n * @param transforms - Optional custom transforms (defaults to DEFAULT_FEEDBACK_TRANSFORMS)\n * @returns Cleaned feedback content\n */\nexport function cleanFeedbackText(content, transforms = DEFAULT_FEEDBACK_TRANSFORMS) {\n if (!content)\n return content;\n let result = content;\n for (const transform of transforms) {\n result = result.replace(transform.pattern, transform.replacement);\n }\n return result;\n}\n/**\n * Default outcome identifier for feedback display\n * This can be overridden if your QTI content uses a different identifier\n */\nexport const DEFAULT_FEEDBACK_OUTCOME_ID = 'FEEDBACK';\n/**\n * Process feedbackInline elements in QTI content\n *\n * Conditionally shows/hides feedback based on outcome values and the showHide attribute.\n * Optionally applies text cleaning heuristics and wraps content with styling span.\n *\n * @param html - The HTML content containing feedbackInline elements\n * @param options - Processing options\n * @returns Modified HTML with processed feedbackInline elements\n *\n * @example\n * ```typescript\n * const html = processFeedbackInline(content, {\n * outcomeValues: { FEEDBACK: 'choiceA' },\n * applyHeuristics: true,\n * wrapWithSpan: true\n * });\n * ```\n */\nexport function processFeedbackInline(html, options) {\n const { outcomeValues, applyHeuristics = false, wrapWithSpan = false, transforms } = options;\n if (!html)\n return html;\n return html.replace(/<feedbackInline\\b([^>]*)>([\\s\\S]*?)<\\/feedbackInline>/gi, (_match, attrs, content) => {\n const outcomeId = feedbackInlineAttr(attrs, 'outcomeIdentifier');\n const feedbackId = feedbackInlineAttr(attrs, 'identifier');\n const showHide = feedbackInlineAttr(attrs, 'showHide') ?? 'show';\n const outcomeValue = outcomeId ? outcomeValues[outcomeId] : undefined;\n // If outcome value is not set (undefined, null, empty string), hide feedback\n if (outcomeId === null ||\n feedbackId === null ||\n outcomeValue === undefined ||\n outcomeValue === null ||\n outcomeValue === '') {\n return '';\n }\n // Determine if feedback should be shown based on showHide attribute\n const matchesFeedback = Array.isArray(outcomeValue)\n ? outcomeValue.includes(feedbackId)\n : outcomeValue === feedbackId;\n const shouldShow = showHide.toLowerCase() === 'show' ? matchesFeedback : !matchesFeedback;\n if (!shouldShow)\n return '';\n // Apply text cleaning heuristics if enabled\n if (applyHeuristics) {\n content = cleanFeedbackText(content, transforms);\n }\n // Wrap with styling span if enabled\n if (wrapWithSpan) {\n return ` <span class=\"qti-feedback-inline\">${content}</span>`;\n }\n return content;\n });\n}\nfunction feedbackInlineAttr(attrs, name) {\n const match = new RegExp(`\\\\b${name}\\\\s*=\\\\s*\"([^\"]*)\"`, 'i').exec(attrs) ??\n new RegExp(`\\\\b${name}\\\\s*=\\\\s*'([^']*)'`, 'i').exec(attrs);\n return match?.[1] ?? null;\n}\n//# sourceMappingURL=feedbackUtils.js.map","import { isBlockedStylesheetCss } from '@pie-qti/ims-cp-core';\nexport function buildScopedStylesheetCss(deliveryContext, scopeSelector = '[data-qti-item-body-scope]') {\n if (!deliveryContext)\n return '';\n return deliveryContext.stylesheets\n .map((stylesheet) => stylesheetToScopedCss(stylesheet, scopeSelector))\n .filter(Boolean)\n .join('\\n');\n}\nfunction stylesheetToScopedCss(stylesheet, scopeSelector) {\n const css = stylesheet.cssText?.trim();\n if (!css || isBlockedStylesheetCss(css))\n return '';\n const stylesheetScope = getStylesheetScopeSelector(stylesheet, scopeSelector);\n const scoped = scopeCssRules(css, stylesheetScope);\n if (!scoped)\n return '';\n return scoped;\n}\n/**\n * At-rules whose block contains nested *rules*, so scoping recurses into the\n * block while the prelude is preserved verbatim.\n *\n * Anything not listed here is passed through untouched. That is the safe\n * default both ways: at-rules whose block holds declarations rather than rules\n * (`@font-face`, `@page`, `@property`, `@counter-style`) or non-selector keys\n * (`@keyframes` percentages) must not be scoped, and an at-rule this list has\n * never heard of is more safely left alone than guessed at.\n */\nconst NESTED_RULE_AT_RULES = new Set(['media', 'supports', 'container', 'layer', 'scope']);\n/** Matches a leading `:root`, `html` or `body` not followed by more name characters. */\nconst DOCUMENT_ROOT_PREFIX = /^(?::root|html|body)(?![\\w-])/;\n/** Matches an at-rule name, with any vendor prefix, at the start of a prelude. */\nconst AT_RULE_NAME = /^@(?:-[a-z]+-)?([\\w-]+)/i;\n/**\n * Confine every selector in `css` to `scopeSelector`.\n *\n * This walks the stylesheet brace-by-brace. It used to be a single regex over\n * `([^{}@]+)\\{([^{}]*)\\}`, which handled flat selector rules and silently\n * destroyed at-rules. Because `@` was excluded from the selector pattern rather\n * than *understood*, an `@media` block never matched as a unit, so the inner\n * rules matched on their own and were emitted **without the condition** — the\n * media query was dropped and its rules applied unconditionally, so a\n * print-only or narrow-viewport rule took effect everywhere. `@keyframes`\n * degraded the same way, with its percentage selectors scoped into\n * `[scope] 0%` and the animation name discarded, and `@font-face` became\n * `[scope] font-face`.\n *\n * A CSS parser would be the textbook answer and is deliberately not added:\n * scoping needs rule boundaries only, not property grammar, and this runs in\n * the delivery path.\n *\n * Note that `isBlockedStylesheetCss` rejects any stylesheet containing `url(`\n * or `@import` before this is reached, so `@font-face` with a real `src` never\n * arrives here in practice. `@media`, `@supports` and `@keyframes` do.\n */\nexport function scopeCssRules(css, scopeSelector = '[data-qti-item-body-scope]') {\n if (!css)\n return '';\n const scope = scopeSelector?.trim();\n if (!scope)\n return css;\n return scopeRuleList(stripComments(css), scope).trim();\n}\nfunction scopeRuleList(css, scope) {\n let out = '';\n let index = 0;\n while (index < css.length) {\n const node = readNode(css, index);\n if (node.end <= index)\n break;\n out += renderNode(node, scope);\n index = node.end;\n }\n return out;\n}\nfunction renderNode(node, scope) {\n if (node.kind === 'statement') {\n const text = node.text.trim();\n return text === ';' ? '' : `${text}\\n`;\n }\n if (node.kind === 'trailing') {\n return node.text.trim() ? `${node.text.trim()}\\n` : '';\n }\n const prelude = node.prelude.trim();\n if (!prelude)\n return '';\n if (prelude.startsWith('@')) {\n const name = AT_RULE_NAME.exec(prelude)?.[1]?.toLowerCase();\n if (name && NESTED_RULE_AT_RULES.has(name)) {\n const inner = scopeRuleList(node.block, scope);\n if (!inner.trim())\n return '';\n return `${prelude} {\\n${inner}}\\n`;\n }\n return `${prelude} {${node.block}}\\n`;\n }\n // Rules with no declarations are dropped, as they were before.\n const declarations = node.block.trim();\n if (!declarations)\n return '';\n const selectors = splitTopLevel(prelude, ',')\n .map((selector) => scopeSelectorText(selector.trim(), scope))\n .filter(Boolean);\n if (selectors.length === 0)\n return '';\n return `${selectors.join(', ')} { ${declarations} }\\n`;\n}\nfunction getStylesheetScopeSelector(stylesheet, scopeSelector) {\n if (stylesheet.source !== 'stimulus' || !stylesheet.stimulusIdentifier)\n return scopeSelector;\n return `${scopeSelector} [data-stimulus-idref=\"${escapeCssString(stylesheet.stimulusIdentifier)}\"]`;\n}\nfunction scopeSelectorText(selector, scopeSelector) {\n if (!selector)\n return '';\n if (selector === scopeSelector || selector.startsWith(`${scopeSelector} `))\n return selector;\n // `:root`/`html`/`body` are replaced rather than prefixed: `[scope] :root`\n // cannot match, because `:root` is the document element and is not a\n // descendant of the item body. Whatever followed is preserved, so\n // `html.dark .a` becomes `[scope].dark .a`.\n const rootPrefix = DOCUMENT_ROOT_PREFIX.exec(selector);\n if (rootPrefix)\n return `${scopeSelector}${selector.slice(rootPrefix[0].length)}`;\n // Everything else becomes a descendant, including a leading pseudo. This\n // used to attach — `[scope]:is(.a, .b)` — which is a different selector: an\n // authored `:is(.a, .b) .c` means \"some element matching .a or .b\", so\n // attaching demands that the item body itself carry the authored class, and\n // it does not. The same holds for `:hover` and `::selection`.\n return `${scopeSelector} ${selector}`;\n}\n/**\n * Read one node starting at `start`, tracking strings and parentheses so a `{`\n * inside `content: \"{\"` or a `,` inside `:is(a, b)` is not mistaken for\n * structure.\n */\nfunction readNode(css, start) {\n let index = start;\n let quote = null;\n let parenDepth = 0;\n while (index < css.length) {\n const char = css[index];\n if (quote) {\n if (char === '\\\\')\n index += 1;\n else if (char === quote)\n quote = null;\n }\n else if (char === '\"' || char === \"'\") {\n quote = char;\n }\n else if (char === '(') {\n parenDepth += 1;\n }\n else if (char === ')') {\n if (parenDepth > 0)\n parenDepth -= 1;\n }\n else if (parenDepth === 0 && char === ';') {\n return { kind: 'statement', text: css.slice(start, index + 1), end: index + 1 };\n }\n else if (parenDepth === 0 && char === '{') {\n const blockEnd = findBlockEnd(css, index);\n return {\n kind: 'rule',\n prelude: css.slice(start, index),\n block: css.slice(index + 1, blockEnd.contentEnd),\n end: blockEnd.end,\n };\n }\n index += 1;\n }\n return { kind: 'trailing', text: css.slice(start), end: css.length };\n}\n/**\n * Find the `}` matching the `{` at `openIndex`. Unbalanced input — a truncated\n * stylesheet — is treated as running to the end rather than throwing.\n */\nfunction findBlockEnd(css, openIndex) {\n let depth = 0;\n let quote = null;\n for (let index = openIndex; index < css.length; index += 1) {\n const char = css[index];\n if (quote) {\n if (char === '\\\\')\n index += 1;\n else if (char === quote)\n quote = null;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n continue;\n }\n if (char === '{')\n depth += 1;\n else if (char === '}') {\n depth -= 1;\n if (depth === 0)\n return { contentEnd: index, end: index + 1 };\n }\n }\n return { contentEnd: css.length, end: css.length };\n}\n/** Split on `separator` at paren depth zero and outside strings. */\nfunction splitTopLevel(value, separator) {\n const parts = [];\n let current = '';\n let quote = null;\n let parenDepth = 0;\n for (let index = 0; index < value.length; index += 1) {\n const char = value[index];\n if (quote) {\n current += char;\n if (char === '\\\\' && index + 1 < value.length) {\n current += value[index + 1];\n index += 1;\n }\n else if (char === quote) {\n quote = null;\n }\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n current += char;\n continue;\n }\n if (char === '(')\n parenDepth += 1;\n else if (char === ')' && parenDepth > 0)\n parenDepth -= 1;\n if (char === separator && parenDepth === 0) {\n parts.push(current);\n current = '';\n continue;\n }\n current += char;\n }\n parts.push(current);\n return parts;\n}\n/**\n * Remove comments before walking, so a comment between two rules is not\n * absorbed into the next rule's selector list. String-aware, so a literal\n * `content: \"/*\"` survives — the previous regex strip was not.\n */\nfunction stripComments(css) {\n let out = '';\n let quote = null;\n let index = 0;\n while (index < css.length) {\n const char = css[index];\n if (quote) {\n out += char;\n if (char === '\\\\' && index + 1 < css.length) {\n out += css[index + 1];\n index += 2;\n continue;\n }\n if (char === quote)\n quote = null;\n index += 1;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n out += char;\n index += 1;\n continue;\n }\n if (char === '/' && css[index + 1] === '*') {\n const close = css.indexOf('*/', index + 2);\n index = close === -1 ? css.length : close + 2;\n // Keep a space so `a/**/b` does not become the single token `ab`.\n out += ' ';\n continue;\n }\n out += char;\n index += 1;\n }\n return out;\n}\nfunction escapeCssString(value) {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n|\\r|\\f/g, ' ');\n}\n//# sourceMappingURL=stylesheetRender.js.map","/**\n * Build the effective stimulus content map for an item render.\n *\n * Resolved delivery-context content is the package/assessment source of truth.\n */\nexport function buildEffectiveStimulusContent(deliveryContext, sanitize) {\n return Object.fromEntries(Object.entries(deliveryContext?.stimuli ?? {}).map(([identifier, stimulus]) => [\n identifier,\n sanitize(stimulus.bodyHtml),\n ]));\n}\n/**\n * Inject shared stimulus bodies at QTI refs or host-authored docking points.\n *\n * Any resolved stimulus that has no matching docking point is prepended in\n * delivery-context order so undocked package content is still visible.\n */\nexport function injectStimulusContent(itemBodyHtml, stimulusContent) {\n if (Object.keys(stimulusContent).length === 0)\n return itemBodyHtml;\n const docked = new Set();\n let html = itemBodyHtml.replace(/<([a-z][\\w:-]*)([^>]*\\bdata-stimulus-idref=([\"'])([^\"']+)\\3[^>]*)>\\s*<\\/\\1>/gi, (match, tagName, attrs, _quote, identifier) => {\n const content = stimulusContent[identifier];\n if (!content)\n return match;\n docked.add(identifier);\n return `<${tagName}${mergeClassAttribute(attrs, 'qti-stimulus-dock')}>${content}</${tagName}>`;\n });\n html = html.replace(/<qti-assessment-stimulus-ref\\b([^>]*)\\/?>\\s*(?:<\\/qti-assessment-stimulus-ref>)?/gi, (match, attrs) => {\n const identifier = extractAttribute(attrs, 'identifier');\n if (!identifier)\n return match;\n if (docked.has(identifier))\n return '';\n const content = stimulusContent[identifier];\n if (!content)\n return match;\n docked.add(identifier);\n return `<div data-stimulus-idref=\"${escapeHtmlAttribute(identifier)}\" class=\"qti-stimulus-dock\">${content}</div>`;\n });\n const undocked = Object.entries(stimulusContent)\n .filter(([identifier]) => !docked.has(identifier))\n .map(([identifier, content]) => `<div data-stimulus-idref=\"${escapeHtmlAttribute(identifier)}\" class=\"qti-stimulus-block\">${content}</div>`)\n .join('');\n return undocked ? undocked + html : html;\n}\nfunction extractAttribute(attrs, name) {\n const match = attrs.match(new RegExp(`\\\\b${name}\\\\s*=\\\\s*[\"']([^\"']+)[\"']`, 'i'));\n return match?.[1] ?? null;\n}\nfunction mergeClassAttribute(attrs, className) {\n const classMatch = attrs.match(/\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/i);\n if (!classMatch)\n return `${attrs} class=\"${className}\"`;\n const quote = classMatch[1];\n const existing = classMatch[2] ?? '';\n const classes = new Set(existing.split(/\\s+/).filter(Boolean));\n classes.add(className);\n return attrs.replace(classMatch[0], `class=${quote}${Array.from(classes).join(' ')}${quote}`);\n}\nfunction escapeHtmlAttribute(value) {\n return value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n//# sourceMappingURL=stimulusRender.js.map","import { isStandardInlineInteractionTagName, isStandardInlineInteractionType, } from '../modules.js';\nexport function isInlineInteractionType(type) {\n return isStandardInlineInteractionType(type);\n}\nexport function isInlineInteractionTagName(tagName) {\n return isStandardInlineInteractionTagName(tagName);\n}\nexport function createInlinePlaceholderHtml(html, interactions) {\n return html\n .replace(/<textEntryInteraction[^>]*responseIdentifier=\"([^\"]+)\"[^>]*?(?:\\/>|><\\/textEntryInteraction>)/gi, (match, responseId) => hasInlineInteraction(interactions, responseId, 'textEntryInteraction')\n ? placeholder('textEntry', responseId)\n : match)\n .replace(/<qti-text-entry-interaction[^>]*response-identifier=\"([^\"]+)\"[^>]*?(?:\\/>|><\\/qti-text-entry-interaction>)/gi, (match, responseId) => hasInlineInteraction(interactions, responseId, 'textEntryInteraction')\n ? placeholder('textEntry', responseId)\n : match)\n .replace(/<inlineChoiceInteraction[^>]*responseIdentifier=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/inlineChoiceInteraction>/gi, (match, responseId) => hasInlineInteraction(interactions, responseId, 'inlineChoiceInteraction')\n ? placeholder('inlineChoice', responseId)\n : match)\n .replace(/<qti-inline-choice-interaction[^>]*response-identifier=\"([^\"]+)\"[^>]*>[\\s\\S]*?<\\/qti-inline-choice-interaction>/gi, (match, responseId) => hasInlineInteraction(interactions, responseId, 'inlineChoiceInteraction')\n ? placeholder('inlineChoice', responseId)\n : match);\n}\nexport function createInlineRenderPlan(html, interactions) {\n const placeholderHtml = createInlinePlaceholderHtml(html, interactions);\n const result = [];\n const combinedPattern = /\\[TEXTENTRY:([^\\]]+)\\]|\\[INLINECHOICE:([^\\]]+)\\]/g;\n let lastIndex = 0;\n let match;\n while ((match = combinedPattern.exec(placeholderHtml)) !== null) {\n if (match.index > lastIndex) {\n result.push({ type: 'html', content: placeholderHtml.substring(lastIndex, match.index) });\n }\n if (match[0].startsWith('[TEXTENTRY:')) {\n const interaction = findInlineInteraction(interactions, match[1], 'textEntryInteraction');\n if (interaction)\n result.push({ type: 'textEntry', interaction });\n }\n else {\n const interaction = findInlineInteraction(interactions, match[2], 'inlineChoiceInteraction');\n if (interaction)\n result.push({ type: 'inlineChoice', interaction });\n }\n lastIndex = match.index + match[0].length;\n }\n if (lastIndex < placeholderHtml.length) {\n result.push({ type: 'html', content: placeholderHtml.substring(lastIndex) });\n }\n return result.length > 0 ? result : [{ type: 'html', content: placeholderHtml }];\n}\nfunction placeholder(kind, responseId) {\n return kind === 'textEntry' ? `[TEXTENTRY:${responseId}]` : `[INLINECHOICE:${responseId}]`;\n}\nfunction hasInlineInteraction(interactions, responseId, type) {\n return Boolean(findInlineInteraction(interactions, responseId, type));\n}\nfunction findInlineInteraction(interactions, responseId, type) {\n return (interactions.find((interaction) => interaction.responseId === responseId && interaction.type === type) ??\n null);\n}\n//# sourceMappingURL=render-plan.js.map","import { normalizeHeuristicsConfig, } from '@pie-qti/ims-cp-core';\nimport { parse } from 'node-html-parser';\nimport { sanitizeHtml } from '../core/sanitizer.js';\nimport { htmlToString, toTrustedHtml } from '../core/trustedTypes.js';\nimport { getRoleCapabilities } from '../core/rolePolicy.js';\nimport { processFeedbackInline } from '../components/utils/feedbackUtils.js';\nimport { buildScopedStylesheetCss } from '../components/utils/stylesheetRender.js';\nimport { buildEffectiveStimulusContent, injectStimulusContent } from '../components/utils/stimulusRender.js';\nimport { createInlineRenderPlan, isInlineInteractionTagName, isInlineInteractionType, } from '../interactions/inline/render-plan.js';\nexport function createItemPresentation({ source, responses = {}, disabled = false, role = 'candidate', outcomeValues = {}, heuristicsConfig, itemBodyScopeSelector = '[data-qti-item-body-scope]', renderItemBodyRubrics = true, onComponentError, }) {\n const roleCapabilities = getRoleCapabilities(role);\n const effectiveDisabled = disabled || roleCapabilities.isReadOnly;\n const correctResponses = roleCapabilities.canViewCorrectResponses ? source.correctResponses : {};\n const { html, scopedCss } = buildItemBodyPresentation({\n source,\n role,\n outcomeValues,\n heuristicsConfig,\n itemBodyScopeSelector,\n renderItemBodyRubrics,\n });\n const inlineFlow = createInlineRenderPlan(html, source.interactions).map((segment) => {\n if (segment.type === 'html') {\n // Inline planning parses and reserializes the composed body, so sanitation\n // belongs after that final string transform and immediately before TT.\n const sanitized = sanitizeHtml(segment.content, { security: source.security });\n return {\n kind: 'html',\n html: finalizeItemBodyHtml(sanitized, source.security),\n };\n }\n if (segment.type === 'textEntry') {\n return {\n kind: 'interaction',\n mount: {\n placement: 'inline',\n renderer: 'text-entry',\n interaction: segment.interaction,\n },\n };\n }\n return {\n kind: 'interaction',\n mount: {\n placement: 'inline',\n renderer: 'inline-choice',\n interaction: segment.interaction,\n },\n };\n });\n const blockFlow = createBlockInteractionMounts({\n interactions: source.interactions,\n source,\n responses,\n correctResponses,\n roleCapabilities,\n effectiveDisabled,\n onComponentError,\n }).map((mount) => ({\n kind: 'interaction',\n mount,\n }));\n return freezePresentation({\n capabilities: roleCapabilities,\n disabled: effectiveDisabled,\n correctResponses,\n directRubrics: source.directRubrics ?? [],\n flow: [...inlineFlow, ...blockFlow],\n scopedCss,\n });\n}\nfunction freezePresentation(value) {\n if (!value || typeof value !== 'object' || Object.isFrozen(value))\n return value;\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)\n return value;\n Object.freeze(value);\n for (const child of Object.values(value)) {\n freezePresentation(child);\n }\n return value;\n}\nfunction buildItemBodyPresentation({ source, role, outcomeValues, heuristicsConfig, itemBodyScopeSelector, renderItemBodyRubrics, }) {\n let html = htmlToString(source.itemBodyHtml);\n const scopedCss = buildScopedStylesheetCss(source.deliveryContext, itemBodyScopeSelector);\n const effectiveStimulusContent = buildEffectiveStimulusContent(source.deliveryContext, (content) => sanitizeHtml(content, { security: source.security }));\n html = injectStimulusContent(html, effectiveStimulusContent);\n html = renderRubricBlocksForRole(html, role, { renderRubrics: renderItemBodyRubrics });\n const heuristics = normalizeHeuristicsConfig(heuristicsConfig);\n html = processFeedbackInline(html, {\n outcomeValues,\n applyHeuristics: heuristics.feedbackTextFormatting,\n wrapWithSpan: false,\n });\n return { html: hideBlockInteractionMarkup(html), scopedCss };\n}\nfunction finalizeItemBodyHtml(html, security) {\n return toTrustedHtml(html, security?.trustedTypesPolicyName);\n}\nfunction renderRubricBlocksForRole(html, role, { renderRubrics }) {\n if (!html || !/rubric-?block/i.test(html)) {\n return html;\n }\n try {\n const root = parse(html, { lowerCaseTagName: false, comment: false });\n renderRubricBlockChildren(root, role, { renderRubrics });\n return root.toString();\n }\n catch {\n return html;\n }\n}\nfunction renderRubricBlockChildren(element, role, { renderRubrics }) {\n const children = [...element.childNodes];\n for (const child of children) {\n const tagName = child.rawTagName?.toLowerCase();\n if (tagName &&\n isRubricBlockTag(tagName) &&\n (!renderRubrics || !rubricBlockVisibleToRole(child, role))) {\n child.remove();\n continue;\n }\n if (child.childNodes?.length) {\n renderRubricBlockChildren(child, role, { renderRubrics });\n }\n if (tagName && isRubricBlockTag(tagName)) {\n child.replaceWith(renderRubricBlockWrapper(child));\n }\n }\n}\nfunction isRubricBlockTag(tagName) {\n return tagName === 'rubricblock' || tagName === 'qti-rubric-block';\n}\nfunction rubricBlockVisibleToRole(element, role) {\n const view = element.getAttribute('view')?.trim();\n if (!view) {\n return true;\n }\n return splitRubricView(view).includes(role);\n}\nfunction renderRubricBlockWrapper(element) {\n const view = element.getAttribute('view')?.trim();\n const use = element.getAttribute('use')?.trim();\n const attrs = [\n 'class=\"qti-rubric-block\"',\n view ? `data-qti-rubric-view=\"${escapeHtmlAttribute(view)}\"` : '',\n use ? `data-qti-rubric-use=\"${escapeHtmlAttribute(use)}\"` : '',\n ]\n .filter(Boolean)\n .join(' ');\n return `<div ${attrs}>${serializeHtmlChildren(element)}</div>`;\n}\nfunction splitRubricView(view) {\n return view.split(/[\\s,]+/).filter(Boolean);\n}\nfunction serializeHtmlChildren(element) {\n return [...element.childNodes]\n .map((child) => child.toString())\n .join('');\n}\nfunction escapeHtmlAttribute(value) {\n return value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\nfunction hideBlockInteractionMarkup(html) {\n // positionObjectStage is hidden as a unit: it owns the background object and wraps its\n // interactions, all of which the component renders. Matching only the interaction inside it\n // would leave the stage's background image visible in the item body as well.\n return html.replace(/<(\\w+Interaction|qti-[\\w-]+-interaction|positionObjectStage|qti-position-object-stage)(\\s[^>]*)?>[\\s\\S]*?<\\/\\1>/gi, (match, tagName) => {\n const lower = tagName.toLowerCase();\n if (isInlineInteractionTagName(lower))\n return match;\n return `<span class=\"qti-hidden-interaction\">${match}</span>`;\n });\n}\nfunction createBlockInteractionMounts({ interactions, source, responses, correctResponses, roleCapabilities, effectiveDisabled, onComponentError, }) {\n return interactions\n .filter((interaction) => !isInlineInteractionType(interaction.type))\n .map((interaction) => {\n try {\n const stringIdentifier = 'stringIdentifier' in interaction && typeof interaction.stringIdentifier === 'string'\n ? interaction.stringIdentifier\n : undefined;\n const block = {\n placement: 'block',\n renderer: 'web-component',\n interaction,\n tagName: source.componentRegistry.getTagName(interaction),\n key: interactionKey(interaction),\n response: responses[interaction.responseId] ?? null,\n ...(stringIdentifier\n ? { stringResponse: responses[stringIdentifier] ?? null }\n : {}),\n correctResponse: roleCapabilities.canViewCorrectResponses\n ? (correctResponses[interaction.responseId] ?? null)\n : null,\n pnp: source.pnp,\n eliminationTool: source.pnp?.cognitive?.eliminationTool === true,\n disabled: effectiveDisabled,\n componentRole: roleCapabilities.canViewCorrectResponses ? 'scorer' : undefined,\n };\n return block;\n }\n catch (error) {\n onComponentError?.(interaction, error);\n return null;\n }\n })\n .filter((item) => item !== null);\n}\nexport function interactionKey(interaction) {\n const anyInteraction = interaction;\n const ids = Array.isArray(anyInteraction?.choices) && anyInteraction.choices.length > 0\n ? anyInteraction.choices.map((choice) => choice?.identifier).filter(Boolean).join(',')\n : '';\n const prompt = typeof anyInteraction?.prompt === 'string' ? anyInteraction.prompt : '';\n return `${interaction.type}|${interaction.responseId}|${ids}|${prompt}`;\n}\n//# sourceMappingURL=itemPresentationPlan.js.map","import { createItemPresentation, } from '../presentation/itemPresentationPlan.js';\nimport { createPlayerFromPreparedInternal, Player } from './Player.js';\n/**\n * Browser adapters use this without gaining access to the private session engine.\n * @internal\n */\nexport function getItemSessionBinding(session) {\n const runtimeSession = session;\n if (typeof runtimeSession.getRuntimeBinding !== 'function') {\n throw new Error('ItemSession runtime binding is unavailable');\n }\n return runtimeSession.getRuntimeBinding();\n}\n/**\n * Construct sessions through AssessmentItemDefinition.openSession().\n * @internal\n */\nexport class LiveItemSession {\n /** @internal Construct sessions through AssessmentItemDefinition.openSession(). */\n constructor(itemIdentifier, config, options = {}, prepared) {\n this.itemIdentifier = itemIdentifier;\n this.listeners = new Set();\n this.revision = 0;\n this.disposed = false;\n this.defaultRole = config.role ?? 'candidate';\n const playerConfig = { ...config };\n this.player = prepared\n ? createPlayerFromPreparedInternal(playerConfig, prepared, Boolean(options.restore))\n : new Player(playerConfig);\n try {\n if (options.responses) {\n this.assertKnownResponseIdentifiers(Object.keys(options.responses));\n }\n if (options.restore)\n this.player.restoreItemSession(options.restore);\n if (options.activate && this.player.getLifecycleStatus() === 'suspended') {\n this.player.activateAttempt();\n }\n if (options.responses) {\n const lifecycle = this.player.getLifecycleStatus();\n if (!isResponseWritableLifecycle(lifecycle)) {\n throw new Error(`Cannot override responses while item session is ${lifecycle}`);\n }\n this.player.setResponses({ ...options.responses });\n }\n this.currentView = this.captureView();\n }\n catch (error) {\n this.player.destroy();\n throw error;\n }\n this.runtimeBinding = this.createBinding();\n }\n state() {\n return immutableSnapshot(this.currentView);\n }\n dispatch(command) {\n this.assertActive();\n if (commandRequiresWritableLifecycle(command) &&\n !isResponseWritableLifecycle(this.currentView.lifecycleStatus)) {\n throw new Error(`Cannot ${describeCommand(command)} while item session is ${this.currentView.lifecycleStatus}`);\n }\n const previous = this.currentView;\n let result;\n switch (command.action) {\n case 'setResponse':\n this.assertKnownResponseIdentifiers([command.responseIdentifier]);\n this.player.setResponses({ [command.responseIdentifier]: command.value });\n break;\n case 'setResponses':\n this.assertKnownResponseIdentifiers(Object.keys(command.responses));\n this.player.setResponses({ ...command.responses });\n break;\n case 'updatePnp':\n this.player.updatePnp(command.profile);\n break;\n default:\n result = this.player.runItemSessionAction(command);\n }\n this.revision += 1;\n this.currentView = this.captureView(result?.sessionState);\n const transition = freezeTransition({ command, previous, current: this.currentView, result });\n this.notify(transition);\n return transition;\n }\n present(view = {}) {\n this.assertActive();\n return createItemPresentation({\n ...view,\n disabled: view.disabled === true || !isResponseWritableLifecycle(this.currentView.lifecycleStatus),\n source: {\n itemBodyHtml: this.player.getItemBodyHtml(),\n interactions: this.player.getInteractionData(),\n correctResponses: this.player.getCorrectResponses(),\n componentRegistry: this.player.getComponentRegistry(),\n deliveryContext: this.player.getDeliveryContext(),\n pnp: this.player.getPnp(),\n security: this.player.getSecurityConfig(),\n directRubrics: this.player.getRubrics({ scope: 'direct' }),\n },\n responses: immutableSnapshot(this.currentView.responses),\n outcomeValues: immutableSnapshot(this.currentView.outcomes),\n role: this.defaultRole,\n });\n }\n subscribe(listener) {\n this.assertActive();\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n serialize() {\n this.assertActive();\n return immutableSnapshot(this.player.saveItemSession());\n }\n /**\n * Browser/runtime capabilities carried by the session across package bundles.\n * @internal\n */\n getRuntimeBinding() {\n this.assertActive();\n return this.runtimeBinding;\n }\n dispose() {\n if (this.disposed)\n return;\n const previous = this.currentView;\n this.disposed = true;\n this.revision += 1;\n this.currentView = immutableSnapshot({\n ...previous,\n revision: this.revision,\n disposed: true,\n });\n this.player.destroy();\n this.notify(freezeTransition({\n command: { action: 'dispose' },\n previous,\n current: this.currentView,\n }));\n this.listeners.clear();\n }\n captureView(serialized = this.player.saveItemSession()) {\n const responses = valuesOf(serialized.responseVariables);\n return immutableSnapshot({\n revision: this.revision,\n itemIdentifier: serialized.itemIdentifier || this.itemIdentifier || undefined,\n role: this.defaultRole,\n lifecycleStatus: serialized.lifecycleStatus,\n completionStatus: serialized.completionStatus,\n numAttempts: serialized.numAttempts,\n duration: serialized.duration,\n adaptive: this.player.isAdaptive(),\n completed: this.player.isCompleted(),\n canSubmit: this.player.canSubmitResponses(responses),\n disposed: this.disposed,\n responses,\n outcomes: valuesOf(serialized.outcomeVariables),\n templates: valuesOf(serialized.templateVariables),\n context: valuesOf(serialized.contextVariables),\n });\n }\n createBinding() {\n return Object.freeze({\n role: this.defaultRole,\n applyPnp: (root) => {\n this.assertActive();\n this.player.applyPnp(root);\n },\n getPnp: () => {\n this.assertActive();\n return this.player.getPnp();\n },\n onPnpChange: (listener) => {\n this.assertActive();\n return this.player.onPnpChange(() => listener());\n },\n getCatalogEntry: (idref, usage, lang, options) => {\n this.assertActive();\n return this.player.getCatalogEntry(idref, usage, lang, options);\n },\n getComponentRegistry: () => {\n this.assertActive();\n return this.player.getComponentRegistry();\n },\n getDeliveryContext: () => {\n this.assertActive();\n return this.player.getDeliveryContext();\n },\n getSecurityConfig: () => {\n this.assertActive();\n return this.player.getSecurityConfig();\n },\n getI18nProvider: () => {\n this.assertActive();\n return this.player.getI18nProvider();\n },\n createPciHost: (data) => {\n this.assertActive();\n const host = this.player.createPciHost(data);\n host.onResponseChange(() => {\n if (this.disposed ||\n !isResponseWritableLifecycle(this.currentView.lifecycleStatus))\n return;\n const previous = this.currentView;\n this.revision += 1;\n this.currentView = this.captureView();\n this.notify(freezeTransition({\n command: {\n action: 'setResponse',\n responseIdentifier: data.responseIdentifier,\n value: host.getResponse(),\n },\n previous,\n current: this.currentView,\n }));\n });\n return host;\n },\n });\n }\n notify(transition) {\n for (const listener of [...this.listeners]) {\n try {\n listener(immutableSnapshot(transition));\n }\n catch (error) {\n console.error('[QTI ItemSession] subscriber failed:', error);\n }\n }\n }\n assertActive() {\n if (this.disposed)\n throw new Error('ItemSession has been disposed');\n }\n assertKnownResponseIdentifiers(responseIdentifiers) {\n const knownIdentifiers = new Set(Object.keys(this.player.getResponses()));\n const unknown = responseIdentifiers.find((identifier) => !knownIdentifiers.has(identifier));\n if (unknown)\n throw new Error(`Unknown response identifier '${unknown}'`);\n }\n}\nfunction isResponseWritableLifecycle(status) {\n return status === 'initial' || status === 'interacting';\n}\nfunction commandRequiresWritableLifecycle(command) {\n return command.action === 'setResponse' ||\n command.action === 'setResponses' ||\n command.action === 'suspendAttempt' ||\n command.action === 'endAttempt' ||\n command.action === 'submitAttempt';\n}\nfunction describeCommand(command) {\n return command.action === 'setResponse' || command.action === 'setResponses'\n ? 'update responses'\n : `run ${command.action}`;\n}\nfunction valuesOf(variables) {\n return Object.fromEntries(Object.entries(variables).map(([identifier, variable]) => [\n identifier,\n immutableSnapshot(variable.value),\n ]));\n}\nfunction freezeTransition(transition) {\n return immutableSnapshot(transition);\n}\n/** Clone and freeze plain data without mutating values owned by the caller or a PCI module. */\nfunction immutableSnapshot(value) {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((entry) => immutableSnapshot(entry)));\n }\n if (!value || typeof value !== 'object')\n return value;\n if (ArrayBuffer.isView(value))\n return structuredClone(value);\n if (value instanceof ArrayBuffer)\n return value.slice(0);\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null)\n return value;\n const snapshot = Object.fromEntries(Object.entries(value).map(([key, entry]) => [\n key,\n immutableSnapshot(entry),\n ]));\n return Object.freeze(snapshot);\n}\n//# sourceMappingURL=ItemSession.js.map","import { Qti2xAttributeNameMapper, Qti2xElementNameMapper, Qti3AttributeNameMapper, Qti3ElementNameMapper, detectQtiVersion, } from '@pie-qti/qti-common';\nimport { createExtractionRegistry, registerFrameworkDeliveryFields, } from '../extraction/ExtractionRegistry.js';\nimport { getStandardInteractionModules } from '../interactions/modules.js';\nimport { createComponentRegistry } from './ComponentRegistry.js';\nimport { preparePlayerDefinitionInternal } from './Player.js';\nimport { LiveItemSession, } from './ItemSession.js';\n/**\n * Compile QTI source and immutable delivery configuration into a reusable item definition.\n */\nexport function createAssessmentItemDefinition(input) {\n return new CompiledAssessmentItemDefinition(input);\n}\nclass CompiledAssessmentItemDefinition {\n constructor(input) {\n if (!input.itemXml.trim()) {\n throw new Error('AssessmentItemDefinition requires non-empty itemXml');\n }\n this.rngFactory = input.rngFactory;\n const plugins = input.plugins ? Object.freeze([...input.plugins]) : Object.freeze([]);\n const snapshot = snapshotDefinitionConfig(input);\n const { elementNameMapper, attributeNameMapper } = resolveNameMappers(snapshot);\n const config = compileDefinitionConfig(snapshot, {\n elementNameMapper,\n attributeNameMapper,\n }, plugins);\n this.prepared = preparePlayerDefinitionInternal({ ...config });\n this.identifier = readPreparedIdentifier(this.prepared);\n this.playerConfig = config;\n Object.freeze(this);\n }\n openSession(options = {}) {\n if (options.restore?.itemIdentifier &&\n this.identifier &&\n options.restore.itemIdentifier !== this.identifier) {\n throw new Error(`Cannot restore item session for '${options.restore.itemIdentifier}' into '${this.identifier}'`);\n }\n return new LiveItemSession(this.identifier, createSessionPlayerConfig(this.playerConfig, this.rngFactory), options, this.prepared);\n }\n}\nfunction readPreparedIdentifier(prepared) {\n if (!prepared ||\n typeof prepared !== 'object' ||\n !('identifier' in prepared) ||\n typeof prepared.identifier !== 'string') {\n throw new Error('AssessmentItemDefinition compilation did not produce an identifier');\n }\n return prepared.identifier;\n}\nfunction resolveNameMappers(config) {\n if (config.elementNameMapper && config.attributeNameMapper) {\n return {\n elementNameMapper: config.elementNameMapper,\n attributeNameMapper: config.attributeNameMapper,\n };\n }\n const qti3 = detectQtiVersion(config.itemXml ?? '') === '3.0';\n return {\n elementNameMapper: config.elementNameMapper ?? (qti3 ? new Qti3ElementNameMapper() : new Qti2xElementNameMapper()),\n attributeNameMapper: config.attributeNameMapper ??\n (qti3 ? new Qti3AttributeNameMapper() : new Qti2xAttributeNameMapper()),\n };\n}\nfunction snapshotDefinitionConfig(input) {\n const { plugins, rngFactory, ...baseConfig } = input;\n void plugins;\n void rngFactory;\n const config = {\n ...baseConfig,\n itemXml: input.itemXml,\n ...(input.processingFragmentLimits\n ? { processingFragmentLimits: Object.freeze({ ...input.processingFragmentLimits }) }\n : {}),\n ...(input.pci ? { pci: Object.freeze({ ...input.pci }) } : {}),\n ...(input.customOperators\n ? { customOperators: Object.freeze({ ...input.customOperators }) }\n : {}),\n ...(input.security ? { security: freezePlainSnapshot(input.security) } : {}),\n ...(input.pnp ? { pnp: freezePlainSnapshot(input.pnp) } : {}),\n ...(input.deliveryContext\n ? { deliveryContext: freezePlainSnapshot(input.deliveryContext) }\n : {}),\n };\n return Object.freeze(config);\n}\nfunction compileDefinitionConfig(config, mappers, plugins) {\n const extractionRegistry = createExtractionRegistry(mappers.elementNameMapper);\n for (const module of getStandardInteractionModules()) {\n extractionRegistry.register(module.extractor);\n registerFrameworkDeliveryFields(extractionRegistry, module.type, module.delivery);\n }\n const componentRegistry = createComponentRegistry();\n const registeredPluginNames = new Set();\n for (const plugin of plugins) {\n validateDefinitionPlugin(plugin, registeredPluginNames);\n plugin.registerExtractors?.(extractionRegistry);\n plugin.registerComponents?.(componentRegistry);\n registeredPluginNames.add(plugin.name);\n }\n extractionRegistry.seal();\n componentRegistry.seal();\n return Object.freeze({\n ...config,\n elementNameMapper: mappers.elementNameMapper,\n attributeNameMapper: mappers.attributeNameMapper,\n extractionRegistry,\n componentRegistry,\n });\n}\nfunction validateDefinitionPlugin(plugin, registeredPluginNames) {\n if (plugin.kind !== 'assessment-item-definition-plugin') {\n throw new Error(`Definition plugin '${plugin.name || '<unnamed>'}' must declare kind 'assessment-item-definition-plugin'`);\n }\n if (!plugin.name || typeof plugin.name !== 'string') {\n throw new Error('AssessmentItemDefinition plugin must have a valid name');\n }\n if (!/^\\d+\\.\\d+\\.\\d+/.test(plugin.version)) {\n throw new Error(`Definition plugin '${plugin.name}' has invalid version format: ${plugin.version}`);\n }\n if (registeredPluginNames.has(plugin.name)) {\n throw new Error(`Definition plugin '${plugin.name}' is registered more than once`);\n }\n const missing = (plugin.dependencies ?? []).filter((dependency) => !registeredPluginNames.has(dependency));\n if (missing.length > 0) {\n throw new Error(`Definition plugin '${plugin.name}' has missing dependencies: ${missing.join(', ')}`);\n }\n}\nfunction createSessionPlayerConfig(config, rngFactory) {\n return {\n ...config,\n ...(rngFactory ? { rng: rngFactory() } : {}),\n // Give each session a private top-level object while the compiled definition\n // and its sealed extension registries remain shared and immutable.\n };\n}\nfunction freezePlainSnapshot(value) {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((entry) => freezePlainSnapshot(entry)));\n }\n if (!value || typeof value !== 'object')\n return value;\n if (Object.getPrototypeOf(value) !== Object.prototype)\n return value;\n const snapshot = Object.fromEntries(Object.entries(value).map(([key, entry]) => [\n key,\n freezePlainSnapshot(entry),\n ]));\n return Object.freeze(snapshot);\n}\n//# sourceMappingURL=AssessmentItemDefinition.js.map","import { createAssessmentItemDefinition, } from '@pie-qti/item-player';\nexport function getAssessmentItemIdentifier(itemXml) {\n const identifierMatch = itemXml.match(/assessmentItem[^>]+identifier=[\"']([^\"']+)[\"']/);\n return identifierMatch?.[1] || 'unknown';\n}\n/**\n * Runs QTI ResponseProcessing for one AssessmentItem and normalizes the result\n * to the BackendAdapter scoring shape used by AssessmentPlayer.\n */\nexport function scoreAssessmentItem({ itemXml, responses, itemSession, }) {\n const itemIdentifier = getAssessmentItemIdentifier(itemXml);\n try {\n // Use a scorer-grade view of the item for accurate scoring.\n // NOTE: This reference scorer is intentionally insecure and runs client-side.\n // In production, scoring must happen server-side with secured item content.\n const definition = createAssessmentItemDefinition({\n itemXml,\n role: 'scorer',\n });\n const session = definition.openSession(itemSession ? { restore: itemSession } : { responses });\n let result;\n try {\n result = session.dispatch(itemSession\n ? { action: 'scoreAttempt' }\n : { action: 'endAttempt', countAttempt: false, validateResponses: false }).result?.scoring;\n if (!result)\n throw new Error('QTI scoring produced no result');\n }\n finally {\n session.dispose();\n }\n return {\n itemIdentifier,\n score: result.score,\n maxScore: result.maxScore,\n completed: result.completed,\n outcomeValues: result.outcomeValues,\n };\n }\n catch (error) {\n console.error('Scoring error:', error);\n return {\n itemIdentifier,\n score: 0,\n maxScore: 1,\n completed: false,\n outcomeValues: {},\n };\n }\n}\n//# sourceMappingURL=assessment-item-scorer.js.map","/**\n * Reference Backend Adapter - localStorage Implementation\n *\n * This is a REFERENCE IMPLEMENTATION demonstrating the BackendAdapter contract.\n * It uses localStorage for persistence and performs scoring CLIENT-SIDE.\n *\n * ## Security Warning\n *\n * This implementation is INSECURE for production use because:\n * - Scoring is done client-side (can be manipulated)\n * - QTI XML with correct answers is stored in client\n * - No authentication or authorization checks\n *\n * ## Purpose\n *\n * This adapter serves as:\n * 1. Reference implementation showing the API contract\n * 2. Development/demo tool for offline testing\n * 3. Template for building secure backend adapters\n *\n * ## Production Use\n *\n * Replace this with a real backend adapter that:\n * - Stores QTI XML server-side\n * - Performs scoring server-side\n * - Validates all requests with authentication\n * - Filters sensitive data based on role\n */\nimport { buildExpression, buildOutcomeProcessingAst, DeclarationContext, evalExpr, execProgram, OperatorRegistry, parseXml, serializeXml, qtiNull, qtiValue, } from '@pie-qti/qti-processing';\nimport { createResolvedItemDeliveryContext, extractAssessmentStimulusRefs, extractQtiStylesheets, parseAssessmentStimulusXml, resolveCheckedPackagePath, resolveCheckedPackagePathFromFile, } from '@pie-qti/ims-cp-core';\nimport { scoreAssessmentItem } from './assessment-item-scorer.js';\n/**\n * Storage key prefix for localStorage\n */\nconst STORAGE_PREFIX = 'qti_session_';\n/**\n * Cache key for item bank queries\n */\nconst BANK_CACHE_PREFIX = 'qti_bank_cache_';\nclass AssessmentSectionReferenceLimitError extends Error {\n}\nfunction toCanonicalQtiName(name) {\n const withoutPrefix = (name ?? '').replace(/^qti-/, '');\n return withoutPrefix.replace(/-([a-z])/g, (_, char) => char.toUpperCase());\n}\nconst qtiElementNameMapper = {\n version: 'qti2x-or-qti3',\n toCanonical: (elementName) => toCanonicalQtiName(elementName).toLowerCase(),\n toNative: (canonicalName) => canonicalName,\n isValidElementName: () => true,\n};\n/**\n * Reference Backend Adapter using localStorage\n *\n * @example\n * ```typescript\n * const adapter = new ReferenceBackendAdapter();\n * const response = await adapter.initSession({\n * assessmentId: 'test-001',\n * candidateId: 'student-123'\n * });\n * ```\n */\nexport class ReferenceBackendAdapter {\n constructor() {\n this.registeredAssessments = new Map();\n }\n /**\n * Register/override a client-provided assessment structure for a given assessmentId.\n *\n * This is useful for demos or web-components that supply assessment XML directly.\n * Security: this remains a reference/demo adapter; production backends should not\n * accept client-authored assessments.\n */\n registerAssessment(assessmentId, assessment) {\n this.registeredAssessments.set(assessmentId, assessment);\n }\n getAssessment(assessmentId) {\n return this.registeredAssessments.get(assessmentId) ?? this.createDemoAssessment(assessmentId);\n }\n hasAnyResponse(responses) {\n for (const value of Object.values(responses)) {\n if (value == null)\n continue;\n if (Array.isArray(value)) {\n if (value.length > 0)\n return true;\n continue;\n }\n if (typeof value === 'string') {\n if (value.trim().length > 0)\n return true;\n continue;\n }\n return true;\n }\n return false;\n }\n /**\n * Initialize a new assessment session\n */\n async initSession(request) {\n // Check if resuming existing session\n if (request.resumeSessionId) {\n const stored = this.loadSession(request.resumeSessionId);\n if (stored) {\n return {\n sessionId: stored.sessionId,\n assessment: stored.assessment,\n restoredState: stored.state,\n };\n }\n }\n // Create new session\n const sessionId = this.generateSessionId(request.assessmentId, request.candidateId);\n // In a real backend, you would:\n // 1. Fetch assessment from database\n // 2. Filter QTI XML based on role\n // 3. Remove responseProcessing for candidates\n //\n // For reference implementation, we'll use demo data\n const assessment = this.getAssessment(request.assessmentId);\n const firstItemIdentifier = this.getItemOrder(assessment)[0] ?? '';\n const state = {\n currentItemIdentifier: firstItemIdentifier,\n visitedItems: [],\n itemResponses: {},\n itemScores: {},\n itemSessions: {},\n timing: {\n startedAt: Date.now(),\n itemTimes: {},\n totalTime: 0,\n },\n };\n const session = {\n sessionId,\n assessmentId: request.assessmentId,\n candidateId: request.candidateId,\n assessment,\n state,\n createdAt: Date.now(),\n finalized: false,\n };\n this.saveSession(session);\n return {\n sessionId,\n assessment,\n };\n }\n /**\n * Submit responses and get scoring result\n */\n async submitResponses(request) {\n const session = this.loadSession(request.sessionId);\n if (!session) {\n return {\n success: false,\n error: 'Session not found',\n };\n }\n if (session.finalized) {\n return {\n success: false,\n error: 'Session already finalized',\n };\n }\n const receivedAt = Date.now();\n const assessmentLimit = session.assessment.timeLimits;\n const effectiveAssessmentLimitSeconds = request.timing?.scope === 'assessment' && request.timing.limitSeconds !== undefined\n ? request.timing.limitSeconds\n : assessmentLimit?.maxTime;\n const assessmentAllowsLate = assessmentLimit?.allowLateSubmission ?? request.timing?.allowLateSubmission;\n if (effectiveAssessmentLimitSeconds !== undefined &&\n assessmentAllowsLate !== true &&\n receivedAt - session.createdAt > effectiveAssessmentLimitSeconds * 1000) {\n return {\n success: false,\n error: 'Assessment time limit expired',\n };\n }\n const evidenceExpired = request.timing?.limitSeconds !== undefined &&\n request.timing.elapsedMs >= request.timing.limitSeconds * 1000;\n if (evidenceExpired && request.timing?.allowLateSubmission !== true) {\n return {\n success: false,\n error: 'Time limit expired',\n };\n }\n // Find the item XML\n const itemXml = this.findItemXml(session.assessment, request.itemIdentifier);\n if (!itemXml) {\n return {\n success: false,\n error: 'Item not found',\n };\n }\n // **SECURITY WARNING**: Client-side scoring is INSECURE\n // In production, this MUST be done server-side\n const result = scoreAssessmentItem({ itemXml, responses: request.responses, itemSession: request.itemSession });\n // Store responses and result\n session.state.itemResponses[request.itemIdentifier] = request.responses;\n if (!session.state.itemScores) {\n session.state.itemScores = {};\n }\n session.state.itemScores[request.itemIdentifier] = result;\n if (request.itemSession) {\n session.state.itemSessions = {\n ...(session.state.itemSessions ?? {}),\n [request.itemIdentifier]: request.itemSession,\n };\n }\n const previousItemSession = session.state.itemSessionStates?.[request.itemIdentifier];\n session.state.itemSessionStates = {\n ...(session.state.itemSessionStates ?? {}),\n [request.itemIdentifier]: {\n itemIdentifier: request.itemIdentifier,\n attemptCount: (previousItemSession?.attemptCount ?? 0) + 1,\n isAnswered: this.hasAnyResponse(request.responses),\n isSubmitted: true,\n lastSubmissionTime: request.submittedAt,\n },\n };\n // Update timing\n if (request.timeSpent) {\n session.state.timing.itemTimes[request.itemIdentifier] = request.timeSpent;\n }\n // Add to visited items if not already there\n if (!session.state.visitedItems.includes(request.itemIdentifier)) {\n session.state.visitedItems.push(request.itemIdentifier);\n }\n this.saveSession(session);\n const order = this.getItemOrder(session.assessment);\n const idx = order.indexOf(request.itemIdentifier);\n let nextItemIdentifier = idx >= 0 ? order[idx + 1] : undefined;\n // QTI branchRule evaluation (backend-authoritative).\n // Evaluate each rule in order; the first matching rule determines the next item.\n // Special targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION are returned as-is for\n // the client to interpret.\n const itemRef = this.findItemRef(session.assessment, request.itemIdentifier);\n if (itemRef?.branchRule && itemRef.branchRule.length > 0) {\n const outcomeVars = {\n ...result.outcomeValues,\n SCORE: result.score,\n };\n nextItemIdentifier = undefined; // reset — branch rules take full control\n for (const rule of itemRef.branchRule) {\n const matches = rule.conditionXml\n ? this.evaluateConditionXml(rule.conditionXml, outcomeVars)\n : true; // unconditional branch\n if (matches) {\n nextItemIdentifier = rule.target;\n break;\n }\n }\n }\n return {\n success: true,\n result,\n nextItemIdentifier,\n updatedState: session.state,\n };\n }\n /**\n * Save session state (for auto-save)\n */\n async saveState(request) {\n const session = this.loadSession(request.sessionId);\n if (!session) {\n return {\n success: false,\n savedAt: Date.now(),\n };\n }\n // Update state\n session.state = request.state;\n this.saveSession(session);\n return {\n success: true,\n savedAt: Date.now(),\n };\n }\n /**\n * Finalize assessment and compute final scores\n */\n async finalizeAssessment(request) {\n const session = this.loadSession(request.sessionId);\n if (!session) {\n return {\n success: false,\n totalScore: 0,\n maxScore: 0,\n itemScores: {},\n finalizedAt: Date.now(),\n };\n }\n // Mark as finalized\n session.finalized = true;\n this.saveSession(session);\n // Compute total score\n const itemScores = session.state.itemScores || {};\n const fallbackTotal = Object.values(itemScores).reduce((sum, result) => sum + result.score, 0);\n const maxScore = Object.values(itemScores).reduce((sum, result) => sum + result.maxScore, 0);\n // Execute test-level outcome processing if available\n const outcomes = this.runOutcomeProcessing(session.assessment, itemScores);\n const totalScore = outcomes !== null ? (outcomes['SCORE_TOTAL'] ?? outcomes['SCORE'] ?? fallbackTotal) : fallbackTotal;\n return {\n success: true,\n totalScore,\n maxScore,\n itemScores,\n finalizedAt: Date.now(),\n };\n }\n /**\n * Execute test-level outcome processing (T9/T1).\n * Returns a map of outcome variable values, or null if no outcomeProcessing is defined.\n */\n runOutcomeProcessing(assessment, itemScores) {\n if (!assessment.outcomeProcessingXml) {\n return null;\n }\n try {\n // Build declaration map from outcomeDeclarations\n const decls = {};\n for (const d of assessment.outcomeDeclarations || []) {\n const baseType = d.baseType;\n const cardinality = d.cardinality;\n let defaultQtiValue;\n if (d.defaultValue !== undefined) {\n defaultQtiValue = qtiValue(baseType, cardinality, d.defaultValue);\n }\n else if (baseType === 'float' || baseType === 'integer') {\n defaultQtiValue = qtiValue(baseType, 'single', 0);\n }\n else {\n defaultQtiValue = qtiNull();\n }\n decls[d.identifier] = {\n identifier: d.identifier,\n baseType,\n cardinality,\n defaultValue: defaultQtiValue,\n value: { ...defaultQtiValue },\n };\n }\n const ctx = new DeclarationContext(decls);\n const ops = new OperatorRegistry();\n // Build test items array for testVariables expression\n const testItems = Object.entries(itemScores).map(([id, scoring]) => ({\n identifier: id,\n variables: {\n SCORE: qtiValue('float', 'single', scoring.score),\n // Add any other outcome values from the scoring result\n ...Object.fromEntries(Object.entries(scoring.outcomeValues || {}).map(([k, v]) => [\n k,\n typeof v === 'number'\n ? qtiValue('float', 'single', v)\n : qtiValue('string', 'single', String(v)),\n ])),\n },\n }));\n // Parse and execute outcome processing\n const opEl = parseXml(assessment.outcomeProcessingXml).documentElement;\n if (!opEl)\n return null;\n const program = buildOutcomeProcessingAst(opEl, {\n scope: 'test',\n elementNameMapper: qtiElementNameMapper,\n });\n execProgram({\n ctx,\n ops,\n rng: Math.random,\n test: { items: testItems },\n }, program);\n // Extract outcome values\n const result = {};\n for (const d of assessment.outcomeDeclarations || []) {\n const v = ctx.getValue(d.identifier);\n if (v.kind === 'value') {\n result[d.identifier] = v.value;\n }\n }\n return result;\n }\n catch (err) {\n console.warn('[ReferenceBackendAdapter] outcomeProcessing failed:', err);\n return null;\n }\n }\n /**\n * Resume existing session (alias for initSession with resumeSessionId)\n */\n async resumeSession(sessionId) {\n return this.initSession({\n assessmentId: '',\n candidateId: '',\n resumeSessionId: sessionId,\n });\n }\n /**\n * Query item bank for random item selection\n *\n * This reference implementation:\n * - Caches bank queries to avoid repeated calls\n * - Implements retry logic with exponential backoff\n * - Returns demo items (in production, fetch from real item bank)\n *\n * @param request - Item bank query request\n * @returns Selected items from bank\n */\n async queryItemBank(request) {\n const { sessionId, bankId, count, withReplacement, filters } = request;\n // Validate session exists\n const session = this.loadSession(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n // Check cache first\n const cacheKey = this.getBankCacheKey(sessionId, bankId, count, withReplacement, filters);\n const cached = this.loadBankCache(cacheKey);\n if (cached) {\n return {\n items: cached.items,\n selectedAt: cached.timestamp,\n };\n }\n // Simulate network call with retry logic\n const items = await this.fetchItemsFromBank(bankId, count, withReplacement, filters);\n // Cache the result (5 minute TTL)\n this.saveBankCache(cacheKey, {\n items,\n timestamp: Date.now(),\n ttl: 5 * 60 * 1000, // 5 minutes\n });\n return {\n items,\n selectedAt: Date.now(),\n };\n }\n // =========================================================================\n // PRIVATE HELPERS\n // =========================================================================\n generateSessionId(assessmentId, candidateId) {\n return `${assessmentId}:${candidateId}:${Date.now()}`;\n }\n loadSession(sessionId) {\n try {\n const key = STORAGE_PREFIX + sessionId;\n const data = localStorage.getItem(key);\n if (!data)\n return null;\n return JSON.parse(data);\n }\n catch {\n return null;\n }\n }\n saveSession(session) {\n try {\n const key = STORAGE_PREFIX + session.sessionId;\n localStorage.setItem(key, JSON.stringify(session));\n }\n catch (error) {\n console.error('Failed to save session to localStorage:', error);\n }\n }\n findItemXml(assessment, itemIdentifier) {\n const findInSection = (section) => {\n for (const item of section.assessmentItemRefs) {\n if (item.identifier === itemIdentifier)\n return item.itemXml;\n }\n for (const child of section.sections ?? []) {\n const found = findInSection(child);\n if (found !== null)\n return found;\n }\n return null;\n };\n for (const part of assessment.testParts) {\n for (const section of part.sections) {\n const found = findInSection(section);\n if (found !== null)\n return found;\n }\n }\n return null;\n }\n findItemRef(assessment, itemIdentifier) {\n const findInSection = (section) => {\n for (const item of section.assessmentItemRefs) {\n if (item.identifier === itemIdentifier)\n return item;\n }\n for (const child of section.sections ?? []) {\n const found = findInSection(child);\n if (found)\n return found;\n }\n return null;\n };\n for (const part of assessment.testParts) {\n for (const section of part.sections) {\n const found = findInSection(section);\n if (found)\n return found;\n }\n }\n return null;\n }\n /**\n * Create demo assessment for testing\n *\n * In production, this would fetch from database\n */\n createDemoAssessment(assessmentId) {\n // This is a minimal demo assessment\n // In production, load from database and filter based on role\n return {\n identifier: assessmentId,\n title: 'Demo Assessment',\n navigationMode: 'nonlinear',\n submissionMode: 'simultaneous',\n testParts: [\n {\n identifier: 'part1',\n rubricBlocks: [],\n itemSessionControl: {\n maxAttempts: 1,\n showFeedback: true,\n allowReview: true,\n showSolution: false,\n allowComment: false,\n allowSkipping: true,\n validateResponses: true,\n },\n sections: [\n {\n identifier: 'section1',\n title: 'Section 1',\n visible: true,\n assessmentItemRefs: [\n {\n identifier: 'item1',\n role: 'candidate',\n // In production, load from database\n // For candidates, responseProcessing should be removed server-side\n itemXml: `<assessmentItem identifier=\"item1\" title=\"Sample Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>What is 2 + 2?</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">4</simpleChoice>\n <simpleChoice identifier=\"B\">3</simpleChoice>\n <simpleChoice identifier=\"C\">5</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n },\n {\n identifier: 'item2',\n role: 'candidate',\n itemXml: `<assessmentItem identifier=\"item2\" title=\"Follow-up Item\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse>\n <value>A</value>\n </correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue>\n <value>0</value>\n </defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Demo follow-up item</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">ok</simpleChoice>\n <simpleChoice identifier=\"B\">no</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n },\n ],\n },\n ],\n },\n ],\n };\n }\n // =========================================================================\n // STATIC: QTI TEST XML PARSER\n // =========================================================================\n /**\n * Parse a QTI assessmentTest XML string into a SecureAssessment structure.\n *\n * Handles:\n * - S1: section-level itemSessionControl\n * - S9: assessmentSectionRef href resolution (requires fileResolver)\n * - T9/T1: outcomeDeclarations + outcomeProcessing extraction\n *\n * @param testXml - Raw QTI assessmentTest XML string\n * @param options.role - Role to assign to items (default: 'candidate')\n * @param options.itemXmlMap - Map of item identifier -> itemXml for pre-loaded items\n * @param options.fileResolver - Async function to load external files by relative href\n * @param options.baseUrl - Base URL for resolving relative hrefs\n */\n static async parseAssessmentTestXml(testXml, options = {}) {\n const { role = 'candidate', itemXmlMap = {}, fileResolver, baseUrl } = options;\n const maxSectionDepth = options.sectionReferenceLimits?.maxDepth ?? 32;\n if (!Number.isInteger(maxSectionDepth) || maxSectionDepth < 1) {\n throw new Error('sectionReferenceLimits.maxDepth must be a positive integer');\n }\n const doc = parseXml(testXml);\n const root = doc.documentElement;\n if (!root)\n throw new Error('Empty assessmentTest XML');\n const getAttr = (el, name) => {\n const direct = el.getAttribute(name);\n if (direct !== null && direct !== '')\n return direct;\n const mapped = el.getAttribute(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));\n return mapped === null || mapped === '' ? undefined : mapped;\n };\n const childElements = (el) => Array.from(el.childNodes).filter((n) => n.nodeType === 1);\n const childrenByTag = (el, tag) => childElements(el).filter((c) => toCanonicalQtiName(c.localName) === tag);\n // Parse itemSessionControl element\n const parseItemSessionControl = (el) => {\n const isc = childrenByTag(el, 'itemSessionControl')[0];\n if (!isc)\n return undefined;\n const boolAttr = (name) => {\n const v = getAttr(isc, name);\n return v === undefined ? undefined : v !== 'false';\n };\n const intAttr = (name) => {\n const v = getAttr(isc, name);\n return v === undefined ? undefined : parseInt(v, 10);\n };\n return {\n maxAttempts: intAttr('maxAttempts'),\n showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),\n allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),\n showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),\n allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),\n allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),\n validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),\n };\n };\n const parseTimeLimits = (el) => {\n const limitsEl = childrenByTag(el, 'timeLimit')[0] ?? childrenByTag(el, 'timeLimits')[0];\n if (!limitsEl)\n return undefined;\n const numberAttr = (name) => {\n const value = getAttr(limitsEl, name);\n if (value === undefined)\n return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n };\n const boolAttr = (name) => {\n const value = getAttr(limitsEl, name);\n return value === undefined ? undefined : value === 'true';\n };\n return {\n minTime: numberAttr('minTime'),\n maxTime: numberAttr('maxTime'),\n allowLateSubmission: boolAttr('allowLateSubmission'),\n };\n };\n const parseConditionExpressions = (el, tag) => {\n const expressions = childrenByTag(el, tag)\n .map((condition) => childElements(condition)[0])\n .filter((expression) => Boolean(expression))\n .map((expression) => serializeXml(expression));\n return expressions.length > 0 ? expressions : undefined;\n };\n const parseBranchRules = (el) => {\n const rules = childrenByTag(el, 'branchRule').flatMap((rule) => {\n const target = getAttr(rule, 'target');\n if (!target)\n return [];\n const expression = childElements(rule)[0];\n return [{ target, conditionXml: expression ? serializeXml(expression) : undefined }];\n });\n return rules.length > 0 ? rules : undefined;\n };\n const parseSelection = (el) => {\n const selection = childrenByTag(el, 'selection')[0];\n if (!selection)\n return undefined;\n const select = Number.parseInt(getAttr(selection, 'select') ?? '', 10);\n if (!Number.isInteger(select) || select < 0)\n return undefined;\n const withReplacementRaw = getAttr(selection, 'withReplacement');\n return {\n select,\n withReplacement: withReplacementRaw === undefined ? undefined : withReplacementRaw === 'true',\n };\n };\n const parseOrdering = (el) => {\n const ordering = childrenByTag(el, 'ordering')[0];\n if (!ordering)\n return undefined;\n return { shuffle: getAttr(ordering, 'shuffle') === 'true' };\n };\n const resolveCheckedHref = (href, sourceHref) => {\n if (!href)\n return undefined;\n if (sourceHref) {\n return resolveCheckedPackagePathFromFile(sourceHref, href) ?? undefined;\n }\n return baseUrl\n ? resolveCheckedPackagePathFromFile(baseUrl, href) ?? undefined\n : resolveCheckedPackagePath(undefined, href) ?? undefined;\n };\n const loadText = async (href, sourceHref) => {\n if (!href)\n return undefined;\n const candidates = [href, resolveCheckedHref(href, sourceHref)].filter((value, index, all) => Boolean(value) && all.indexOf(value) === index);\n for (const candidate of candidates) {\n if (itemXmlMap[candidate] !== undefined) {\n return itemXmlMap[candidate];\n }\n }\n if (!fileResolver)\n return undefined;\n for (const candidate of candidates) {\n try {\n return await fileResolver(candidate);\n }\n catch {\n // Try the next candidate before giving up.\n }\n }\n return undefined;\n };\n const buildDeliveryContext = async (itemXml, itemHref) => {\n if (!itemHref) {\n return undefined;\n }\n const stimulusXmlByPath = {};\n const packageTextByPath = {};\n const preloadText = async (baseHref, href) => {\n const resolvedPath = resolveCheckedPackagePathFromFile(baseHref, href);\n if (!resolvedPath)\n return;\n const text = await loadText(resolvedPath);\n if (text !== undefined) {\n packageTextByPath[resolvedPath] = text;\n }\n };\n for (const stylesheet of extractQtiStylesheets(itemXml)) {\n await preloadText(itemHref, stylesheet.href);\n }\n for (const ref of extractAssessmentStimulusRefs(itemXml)) {\n const stimulusPath = resolveCheckedPackagePathFromFile(itemHref, ref.href);\n if (!stimulusPath)\n continue;\n const stimulusXml = await loadText(stimulusPath);\n if (stimulusXml) {\n stimulusXmlByPath[stimulusPath] = stimulusXml;\n for (const stylesheet of parseAssessmentStimulusXml(stimulusXml).stylesheets) {\n await preloadText(stimulusPath, stylesheet.href);\n }\n }\n }\n return createResolvedItemDeliveryContext({\n itemXml,\n itemHref,\n readText: (path) => packageTextByPath[path] ?? stimulusXmlByPath[path] ?? itemXmlMap[path],\n });\n };\n let resolveSectionRef;\n const parseItemRef = async (ref, sourceHref) => {\n const itemId = getAttr(ref, 'identifier') ?? 'item';\n const href = getAttr(ref, 'href');\n const itemHref = resolveCheckedHref(href, sourceHref);\n const resolvedXml = href && !itemHref\n ? ''\n : itemXmlMap[itemId] ??\n (href ? itemXmlMap[href] : undefined) ??\n (itemHref ? itemXmlMap[itemHref] : undefined) ??\n (await loadText(itemHref)) ??\n '';\n const requiredRaw = getAttr(ref, 'required');\n const fixedRaw = getAttr(ref, 'fixed');\n const weights = childrenByTag(ref, 'weight').flatMap((weight) => {\n const identifier = getAttr(weight, 'identifier');\n const value = Number(getAttr(weight, 'value'));\n return identifier && Number.isFinite(value) ? [{ identifier, value }] : [];\n });\n return {\n identifier: itemId,\n itemXml: resolvedXml,\n role,\n required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',\n fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',\n timeLimits: parseTimeLimits(ref),\n deliveryContext: await buildDeliveryContext(resolvedXml, itemHref),\n branchRule: parseBranchRules(ref),\n preConditions: parseConditionExpressions(ref, 'preCondition'),\n weights: weights.length > 0 ? weights : undefined,\n };\n };\n // Parse a single assessmentSection element without flattening nested sections.\n const parseSection = async (sectionEl, sourceHref, ancestorHrefs = [], depth = 1) => {\n const identifier = getAttr(sectionEl, 'identifier') ?? 'section';\n if (depth > maxSectionDepth) {\n throw new AssessmentSectionReferenceLimitError(`assessmentSection nesting exceeds maxDepth (${maxSectionDepth}) at \"${identifier}\"`);\n }\n const title = getAttr(sectionEl, 'title');\n const visibleRaw = getAttr(sectionEl, 'visible');\n const visible = visibleRaw === undefined ? true : visibleRaw !== 'false';\n const requiredRaw = getAttr(sectionEl, 'required');\n const fixedRaw = getAttr(sectionEl, 'fixed');\n const itemSessionControl = parseItemSessionControl(sectionEl);\n const timeLimits = parseTimeLimits(sectionEl);\n // rubricBlocks\n const rubricBlockEls = childrenByTag(sectionEl, 'rubricBlock');\n const rubricBlocks = rubricBlockEls.length > 0\n ? rubricBlockEls.map((b, idx) => ({\n identifier: getAttr(b, 'identifier') ?? `${identifier}-rubric-${idx + 1}`,\n view: (getAttr(b, 'view') ?? 'candidate').split(/\\s+/).filter(Boolean),\n use: getAttr(b, 'use'),\n content: serializeXml(b),\n }))\n : undefined;\n const assessmentItemRefs = [];\n const sections = [];\n const children = [];\n for (const child of childElements(sectionEl)) {\n const name = toCanonicalQtiName(child.localName);\n if (name === 'assessmentItemRef') {\n const item = await parseItemRef(child, sourceHref);\n assessmentItemRefs.push(item);\n children.push({ type: 'item', item });\n }\n else if (name === 'assessmentSection') {\n const section = await parseSection(child, sourceHref, ancestorHrefs, depth + 1);\n sections.push(section);\n children.push({ type: 'section', section });\n }\n else if (name === 'assessmentSectionRef') {\n const section = await resolveSectionRef(child, sourceHref, ancestorHrefs, depth + 1);\n if (section) {\n sections.push(section);\n children.push({ type: 'section', section });\n }\n }\n }\n return {\n identifier,\n title,\n visible,\n required: requiredRaw === undefined ? undefined : requiredRaw !== 'false',\n fixed: fixedRaw === undefined ? undefined : fixedRaw !== 'false',\n assessmentItemRefs,\n sections: sections.length > 0 ? sections : undefined,\n children: children.length > 0 ? children : undefined,\n rubricBlocks,\n itemSessionControl,\n timeLimits,\n selection: parseSelection(sectionEl),\n ordering: parseOrdering(sectionEl),\n preConditions: parseConditionExpressions(sectionEl, 'preCondition'),\n };\n };\n // Resolve assessmentSectionRef: load and parse referenced section file\n resolveSectionRef = async (sectionRefEl, sourceHref, ancestorHrefs = [], depth = 1) => {\n const href = getAttr(sectionRefEl, 'href');\n if (!href) {\n console.warn('[ReferenceBackendAdapter] assessmentSectionRef missing href, skipping');\n return null;\n }\n if (!fileResolver) {\n console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href=\"${href}\" found but no fileResolver provided, skipping`);\n return null;\n }\n try {\n const resolvedHref = resolveCheckedHref(href, sourceHref);\n if (!resolvedHref) {\n console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href=\"${href}\" is unsafe, skipping`);\n return null;\n }\n if (ancestorHrefs.includes(resolvedHref)) {\n throw new AssessmentSectionReferenceLimitError(`Cyclic assessmentSectionRef detected: ${[...ancestorHrefs, resolvedHref].join(' -> ')}`);\n }\n if (depth > maxSectionDepth) {\n throw new AssessmentSectionReferenceLimitError(`assessmentSectionRef nesting exceeds maxDepth (${maxSectionDepth}) at \"${resolvedHref}\"`);\n }\n const sectionXml = await fileResolver(resolvedHref);\n const secDoc = parseXml(sectionXml);\n const secRoot = secDoc.documentElement;\n if (!secRoot || toCanonicalQtiName(secRoot.localName) !== 'assessmentSection') {\n console.warn(`[ReferenceBackendAdapter] assessmentSectionRef href=\"${href}\": root element is not <assessmentSection>, skipping`);\n return null;\n }\n return parseSection(secRoot, resolvedHref, [...ancestorHrefs, resolvedHref], depth);\n }\n catch (err) {\n if (err instanceof AssessmentSectionReferenceLimitError)\n throw err;\n console.warn(`[ReferenceBackendAdapter] Failed to load assessmentSectionRef href=\"${href}\":`, err);\n return null;\n }\n };\n // Parse testPart children (sections + sectionRefs)\n const parseSectionsForTestPart = async (testPartEl) => {\n const sections = [];\n for (const child of childElements(testPartEl)) {\n if (toCanonicalQtiName(child.localName) === 'assessmentSection') {\n sections.push(await parseSection(child));\n }\n else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {\n const resolved = await resolveSectionRef(child);\n if (resolved)\n sections.push(resolved);\n }\n }\n return sections;\n };\n // Parse testPart-level itemSessionControl\n const parseTestPartItemSessionControl = (testPartEl) => {\n const isc = childrenByTag(testPartEl, 'itemSessionControl')[0];\n if (!isc)\n return undefined;\n const boolAttr = (name) => {\n const v = getAttr(isc, name);\n return v === undefined ? undefined : v !== 'false';\n };\n const intAttr = (name) => {\n const v = getAttr(isc, name);\n return v === undefined ? undefined : parseInt(v, 10);\n };\n return {\n maxAttempts: intAttr('maxAttempts'),\n showFeedback: boolAttr('showFeedback') ?? boolAttr('show-feedback'),\n allowReview: boolAttr('allowReview') ?? boolAttr('allow-review'),\n showSolution: boolAttr('showSolution') ?? boolAttr('show-solution'),\n allowComment: boolAttr('allowComment') ?? boolAttr('allow-comment'),\n allowSkipping: boolAttr('allowSkipping') ?? boolAttr('allow-skipping'),\n validateResponses: boolAttr('validateResponses') ?? boolAttr('validate-responses'),\n };\n };\n // Extract outcomeDeclarations\n const outcomeDeclarations = childrenByTag(root, 'outcomeDeclaration').map((d) => {\n const identifier = getAttr(d, 'identifier') ?? 'OUTCOME';\n const baseType = getAttr(d, 'baseType') ?? 'float';\n const cardinality = getAttr(d, 'cardinality') ?? 'single';\n // Parse defaultValue if present\n const defaultValueEl = childrenByTag(d, 'defaultValue')[0];\n let defaultValue = undefined;\n if (defaultValueEl) {\n const valueEl = childrenByTag(defaultValueEl, 'value')[0];\n if (valueEl) {\n const text = valueEl.textContent?.trim() ?? '0';\n if (baseType === 'float' || baseType === 'integer') {\n defaultValue = Number(text);\n }\n else {\n defaultValue = text;\n }\n }\n }\n return { identifier, baseType, cardinality, defaultValue };\n });\n // Extract outcomeProcessing XML\n const outcomeProcessingEl = childrenByTag(root, 'outcomeProcessing')[0];\n const outcomeProcessingXml = outcomeProcessingEl\n ? serializeXml(outcomeProcessingEl)\n : undefined;\n const testFeedback = childrenByTag(root, 'testFeedback').flatMap((feedback, index) => {\n const outcomeIdentifier = getAttr(feedback, 'outcomeIdentifier');\n if (!outcomeIdentifier)\n return [];\n const content = Array.from(feedback.childNodes).map((node) => serializeXml(node)).join('');\n return [{\n identifier: getAttr(feedback, 'identifier') ?? `test-feedback-${index + 1}`,\n outcomeIdentifier,\n showHide: (getAttr(feedback, 'showHide') ?? 'show'),\n access: (getAttr(feedback, 'access') ?? 'atEnd'),\n content,\n }];\n });\n // Extract assessment-level timeLimits.\n const timeLimits = parseTimeLimits(root);\n // Parse testParts\n const testPartEls = childrenByTag(root, 'testPart');\n const firstTestPart = testPartEls[0];\n // Retain top-level compatibility fields while preserving the authoritative\n // mode on every testPart below.\n const navigationMode = (getAttr(firstTestPart ?? root, 'navigationMode') ?? 'nonlinear');\n const submissionMode = (getAttr(firstTestPart ?? root, 'submissionMode') ?? 'simultaneous');\n const testParts = [];\n for (const tp of testPartEls) {\n const tpIdentifier = getAttr(tp, 'identifier') ?? 'part-1';\n const tpNavigationMode = (getAttr(tp, 'navigationMode') ?? 'nonlinear');\n const tpSubmissionMode = (getAttr(tp, 'submissionMode') ?? 'simultaneous');\n const tpItemSessionControl = parseTestPartItemSessionControl(tp);\n const tpTimeLimits = parseTimeLimits(tp);\n const tpRubricBlockEls = childrenByTag(tp, 'rubricBlock');\n const tpRubricBlocks = tpRubricBlockEls.length > 0\n ? tpRubricBlockEls.map((b, idx) => ({\n identifier: getAttr(b, 'identifier') ?? `${tpIdentifier}-rubric-${idx + 1}`,\n view: (getAttr(b, 'view') ?? 'candidate').split(/\\s+/).filter(Boolean),\n use: getAttr(b, 'use'),\n content: serializeXml(b),\n }))\n : undefined;\n const sections = await parseSectionsForTestPart(tp);\n testParts.push({\n identifier: tpIdentifier,\n navigationMode: tpNavigationMode,\n submissionMode: tpSubmissionMode,\n sections,\n rubricBlocks: tpRubricBlocks,\n itemSessionControl: tpItemSessionControl,\n timeLimits: tpTimeLimits,\n });\n }\n // If no testParts, try top-level sections\n if (testParts.length === 0) {\n const topSections = [];\n for (const child of childElements(root)) {\n if (toCanonicalQtiName(child.localName) === 'assessmentSection') {\n topSections.push(await parseSection(child));\n }\n else if (toCanonicalQtiName(child.localName) === 'assessmentSectionRef') {\n const resolved = await resolveSectionRef(child);\n if (resolved)\n topSections.push(resolved);\n }\n }\n if (topSections.length > 0) {\n testParts.push({\n identifier: 'part-1',\n navigationMode,\n submissionMode,\n sections: topSections,\n });\n }\n }\n return {\n identifier: getAttr(root, 'identifier') ?? 'assessment',\n title: getAttr(root, 'title') ?? 'Assessment',\n navigationMode,\n submissionMode,\n testParts,\n timeLimits,\n outcomeDeclarations: outcomeDeclarations.length > 0 ? outcomeDeclarations : undefined,\n outcomeProcessingXml,\n testFeedback: testFeedback.length > 0 ? testFeedback : undefined,\n baseUrl,\n };\n }\n evaluateConditionXml(conditionXml, vars) {\n // conditionXml is an operator element like <gt>...</gt> (not wrapped in <expression>).\n const doc = parseXml(conditionXml);\n const root = doc.documentElement;\n if (!root)\n return false;\n const decls = {};\n for (const [k, raw] of Object.entries(vars)) {\n let v = qtiNull();\n if (typeof raw === 'number')\n v = qtiValue('float', 'single', raw);\n else if (typeof raw === 'boolean')\n v = qtiValue('boolean', 'single', raw);\n else if (typeof raw === 'string')\n v = qtiValue('string', 'single', raw);\n decls[k] = {\n identifier: k,\n baseType: v.kind === 'value' ? v.baseType : 'string',\n cardinality: 'single',\n defaultValue: qtiNull(),\n value: v,\n };\n }\n const ctx = new DeclarationContext(decls);\n const ops = new OperatorRegistry();\n const expr = buildExpression(root, { scope: 'test' });\n const out = evalExpr({ ctx, ops, rng: Math.random }, expr);\n return out.kind === 'value' && out.baseType === 'boolean' ? Boolean(out.value) : false;\n }\n getItemOrder(assessment) {\n const out = [];\n const visit = (section) => {\n const components = section.children ?? [\n ...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item', item })),\n ...(section.sections ?? []).map((child) => ({ type: 'section', section: child })),\n ];\n for (const component of components) {\n if (component.type === 'item')\n out.push(component.item.identifier);\n else\n visit(component.section);\n }\n };\n for (const part of assessment.testParts || []) {\n for (const section of part.sections || []) {\n visit(section);\n }\n }\n return out;\n }\n // =========================================================================\n // ITEM BANK HELPERS\n // =========================================================================\n /**\n * Generate cache key for item bank query\n */\n getBankCacheKey(sessionId, bankId, count, withReplacement, filters) {\n const filterKey = filters ? JSON.stringify(filters) : '';\n return `${BANK_CACHE_PREFIX}${sessionId}:${bankId}:${count}:${withReplacement}:${filterKey}`;\n }\n /**\n * Load item bank cache from localStorage\n */\n loadBankCache(cacheKey) {\n try {\n const data = localStorage.getItem(cacheKey);\n if (!data)\n return null;\n const entry = JSON.parse(data);\n // Check if cache is expired\n const now = Date.now();\n if (now - entry.timestamp > entry.ttl) {\n // Clean up expired cache\n localStorage.removeItem(cacheKey);\n return null;\n }\n return entry;\n }\n catch {\n return null;\n }\n }\n /**\n * Save item bank cache to localStorage\n */\n saveBankCache(cacheKey, entry) {\n try {\n localStorage.setItem(cacheKey, JSON.stringify(entry));\n }\n catch (error) {\n console.error('Failed to save bank cache to localStorage:', error);\n }\n }\n /**\n * Fetch items from item bank with retry logic\n *\n * **DEMO IMPLEMENTATION**: Returns hardcoded items\n * In production, this would make HTTP request to item bank service\n */\n async fetchItemsFromBank(bankId, count, withReplacement, filters, retryCount = 0) {\n const maxRetries = 3;\n const baseDelay = 1000; // 1 second\n try {\n // Simulate network call delay\n await this.delay(100);\n // **DEMO**: Return hardcoded items\n // In production, replace with:\n // const response = await fetch(`/api/item-banks/${bankId}`, {\n // method: 'POST',\n // headers: { 'Content-Type': 'application/json' },\n // body: JSON.stringify({ count, withReplacement, filters })\n // });\n // return response.json();\n const demoItems = [\n {\n identifier: `bank-${bankId}-item1`,\n role: 'candidate',\n itemXml: `<assessmentItem identifier=\"bank-${bankId}-item1\" title=\"Bank Item 1\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse><value>A</value></correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue><value>0</value></defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Sample question from bank ${bankId}</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">Option A</simpleChoice>\n <simpleChoice identifier=\"B\">Option B</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n },\n {\n identifier: `bank-${bankId}-item2`,\n role: 'candidate',\n itemXml: `<assessmentItem identifier=\"bank-${bankId}-item2\" title=\"Bank Item 2\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse><value>B</value></correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue><value>0</value></defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Another question from bank ${bankId}</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">Option A</simpleChoice>\n <simpleChoice identifier=\"B\">Option B</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n },\n {\n identifier: `bank-${bankId}-item3`,\n role: 'candidate',\n itemXml: `<assessmentItem identifier=\"bank-${bankId}-item3\" title=\"Bank Item 3\" adaptive=\"false\" timeDependent=\"false\">\n <responseDeclaration identifier=\"RESPONSE\" cardinality=\"single\" baseType=\"identifier\">\n <correctResponse><value>A</value></correctResponse>\n </responseDeclaration>\n <outcomeDeclaration identifier=\"SCORE\" cardinality=\"single\" baseType=\"float\">\n <defaultValue><value>0</value></defaultValue>\n </outcomeDeclaration>\n <itemBody>\n <p>Third question from bank ${bankId}</p>\n <choiceInteraction responseIdentifier=\"RESPONSE\" shuffle=\"false\" maxChoices=\"1\">\n <simpleChoice identifier=\"A\">Option A</simpleChoice>\n <simpleChoice identifier=\"B\">Option B</simpleChoice>\n </choiceInteraction>\n </itemBody>\n <responseProcessing>\n <responseCondition>\n <responseIf>\n <match>\n <variable identifier=\"RESPONSE\" />\n <correct identifier=\"RESPONSE\" />\n </match>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">1</baseValue>\n </setOutcomeValue>\n </responseIf>\n <responseElse>\n <setOutcomeValue identifier=\"SCORE\">\n <baseValue baseType=\"float\">0</baseValue>\n </setOutcomeValue>\n </responseElse>\n </responseCondition>\n </responseProcessing>\n</assessmentItem>`,\n },\n ];\n // Apply filtering if specified (demo implementation)\n let filteredItems = [...demoItems];\n if (filters?.difficulty) {\n // In production, server would filter by metadata\n console.log(`Filtering by difficulty: ${filters.difficulty}`);\n }\n // Select requested number of items\n if (withReplacement) {\n // Allow duplicates\n const selected = [];\n for (let i = 0; i < count; i++) {\n const randomIndex = Math.floor(Math.random() * filteredItems.length);\n selected.push(filteredItems[randomIndex]);\n }\n return selected;\n }\n else {\n // No duplicates - shuffle and take first N\n const shuffled = shuffleArray(filteredItems, Math.random);\n return shuffled.slice(0, Math.min(count, shuffled.length));\n }\n }\n catch (error) {\n // Implement exponential backoff retry\n if (retryCount < maxRetries) {\n const delay = baseDelay * Math.pow(2, retryCount);\n console.warn(`Item bank query failed (attempt ${retryCount + 1}/${maxRetries + 1}). ` +\n `Retrying in ${delay}ms...`, error);\n await this.delay(delay);\n return this.fetchItemsFromBank(bankId, count, withReplacement, filters, retryCount + 1);\n }\n // All retries exhausted\n throw new Error(`Failed to load items from bank \"${bankId}\" after ${maxRetries + 1} attempts: ${error}`);\n }\n }\n /**\n * Delay helper for async operations\n */\n delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n/**\n * Fisher-Yates shuffle using a provided RNG (returns a new array).\n *\n * Mirrors the helper of the same name in `core/AssessmentPlayer.ts`. Replaces a\n * `sort(() => Math.random() - 0.5)` comparator, which is not a uniform shuffle: the\n * comparator is inconsistent, so the result depends on the sort algorithm and leaves\n * elements biased toward their original positions.\n */\nfunction shuffleArray(arr, rng) {\n const out = [...arr];\n for (let i = out.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1));\n [out[i], out[j]] = [out[j], out[i]];\n }\n return out;\n}\n//# sourceMappingURL=ReferenceBackendAdapter.js.map","export function normalizeQtiViewTokens(view) {\n return (view ?? [])\n .flatMap((token) => token.split(/[\\s,]+/))\n .map((token) => token.trim())\n .filter(Boolean);\n}\nexport function isQtiViewVisibleForRole(view, role = 'candidate') {\n const tokens = normalizeQtiViewTokens(view);\n if (tokens.length === 0)\n return true;\n return tokens.includes(role);\n}\nexport function filterQtiRoleVisible(blocks, role) {\n return blocks.filter((block) => isQtiViewVisibleForRole(block.view, role));\n}\n","import { isQtiViewVisibleForRole } from './role-view.js';\nexport function normalizeQtiToolConfig(options) {\n return (options.tools ?? []).filter((tool) => tool.enabled !== false && isQtiViewVisibleForRole(tool.view, options.role ?? 'candidate'));\n}\n","import { isQtiViewVisibleForRole } from './role-view.js';\nimport { normalizeQtiToolConfig } from './tool-normalization.js';\nexport function normalizeQtiSharedContext(options) {\n const passages = [];\n const rubricBlocks = [];\n for (const [index, block] of (options.rubricBlocks ?? []).entries()) {\n const normalized = toSharedHtmlBlock(block, index, options);\n if (!isQtiViewVisibleForRole(normalized.view, options.role))\n continue;\n if (normalized.kind === 'passage') {\n passages.push(normalized);\n }\n else {\n rubricBlocks.push(normalized);\n }\n }\n return {\n passages,\n stimuli: [],\n rubricBlocks,\n testFeedback: [],\n stylesheets: [],\n catalogSources: [],\n assetDiagnostics: [],\n };\n}\nfunction toSharedHtmlBlock(block, index, options) {\n const kind = toSharedHtmlBlockKind(block.use);\n const defaultTools = kind === 'passage' ? options.passageTools : options.rubricTools;\n const tools = normalizeQtiToolConfig({ tools: block.tools ?? defaultTools, role: options.role });\n return {\n identifier: block.identifier ?? `${block.use ?? 'rubric'}-${index}`,\n kind,\n scope: 'section',\n view: block.view,\n ...(tools.length > 0 ? { tools } : {}),\n rawHtml: block.content,\n };\n}\nfunction toSharedHtmlBlockKind(use) {\n if (use === 'passage')\n return 'passage';\n if (use === 'instructions')\n return 'instructions';\n return 'rubric';\n}\n","export function normalizeQtiViewTokens(view) {\n return (view ?? [])\n .flatMap((token) => token.split(/[\\s,]+/))\n .map((token) => token.trim())\n .filter(Boolean);\n}\nexport function isQtiViewVisibleForRole(view, role = 'candidate') {\n const tokens = normalizeQtiViewTokens(view);\n if (tokens.length === 0)\n return true;\n return tokens.includes(role);\n}\n","import { sanitizeResourceUrl } from '@pie-qti/item-player/security';\nimport { isQtiViewVisibleForRole } from '../visibility/role-view.js';\nfunction emptySharedContext() {\n return {\n passages: [],\n stimuli: [],\n rubricBlocks: [],\n testFeedback: [],\n stylesheets: [],\n catalogSources: [],\n assetDiagnostics: [],\n };\n}\nfunction resolveActiveIndex(options, diagnostics) {\n if (options.activeItemIdentifier) {\n const index = options.section.itemRefs.findIndex((item) => item.identifier === options.activeItemIdentifier);\n if (index >= 0)\n return index;\n diagnostics.push({\n severity: 'error',\n source: 'section-player',\n code: 'active-item-not-found',\n message: `Active item \"${options.activeItemIdentifier}\" was not found in section \"${options.section.identifier}\".`,\n });\n }\n if (typeof options.activeItemIndex === 'number' &&\n options.activeItemIndex >= 0 &&\n options.activeItemIndex < options.section.itemRefs.length) {\n return options.activeItemIndex;\n }\n return 0;\n}\nfunction resolveLayout(section, sharedContext) {\n if (section.layoutPreference === 'split-pane')\n return 'split-pane';\n if (section.layoutPreference === 'vertical')\n return 'vertical';\n return sharedContext.passages.length > 0 ? 'split-pane' : 'vertical';\n}\nfunction filterToolsForRole(tools, role) {\n const filtered = (tools ?? []).filter((tool) => tool.enabled !== false && isQtiViewVisibleForRole(tool.view, role ?? 'candidate'));\n return filtered.length > 0 ? filtered : undefined;\n}\nfunction resolveSharedHtmlBlockTools(block, role) {\n const tools = filterToolsForRole(block.tools, role);\n return tools === block.tools ? block : { ...block, tools };\n}\nfunction resolveItemTools(item, role) {\n const tools = filterToolsForRole(item.tools, role);\n return tools === item.tools ? item : { ...item, tools };\n}\nfunction sharedAssetDiagnostic(href, path) {\n return {\n severity: 'error',\n source: 'security',\n code: 'shared-asset-url-blocked',\n message: `Shared asset URL \"${href}\" was blocked by the section asset URL policy.`,\n path,\n };\n}\nfunction resolveSharedStylesheetRef(stylesheet, options, diagnostics, path, ownerHref) {\n const packageHref = stylesheet.resolvedHref ?? stylesheet.href;\n const preflightHref = sanitizeResourceUrl(packageHref, { ...(options.security?.urlPolicy ?? {}), assetBaseUrl: undefined }, 'link');\n const evidence = {\n ...stylesheet,\n resolvedHref: preflightHref ?? packageHref,\n };\n if (!preflightHref) {\n diagnostics.push(sharedAssetDiagnostic(packageHref, path));\n return evidence;\n }\n const resolvedBrowserHref = options.host?.resolvePackageUrl\n ? options.host.resolvePackageUrl(packageHref, {\n ownerHref,\n referenceKind: 'stylesheet',\n })\n : packageHref;\n if (!resolvedBrowserHref) {\n diagnostics.push(sharedAssetDiagnostic(packageHref, path));\n return evidence;\n }\n const browserHref = sanitizeResourceUrl(resolvedBrowserHref, options.security?.urlPolicy, 'link');\n if (!browserHref) {\n diagnostics.push(sharedAssetDiagnostic(resolvedBrowserHref, path));\n return evidence;\n }\n const hostSanitizedHref = options.host?.sanitizeAssetUrl\n ? options.host.sanitizeAssetUrl(browserHref, {\n source: stylesheet.source,\n kind: 'link',\n })\n : browserHref;\n if (!hostSanitizedHref) {\n diagnostics.push(sharedAssetDiagnostic(browserHref, path));\n return evidence;\n }\n const finalBrowserHref = sanitizeResourceUrl(hostSanitizedHref, options.security?.urlPolicy, 'link');\n if (!finalBrowserHref) {\n diagnostics.push(sharedAssetDiagnostic(hostSanitizedHref, path));\n return evidence;\n }\n return {\n ...evidence,\n renderHref: finalBrowserHref,\n browserHref: finalBrowserHref,\n };\n}\nfunction resolveStimulusStylesheets(stimulus, options, diagnostics, stimulusIndex) {\n if (!stimulus.stylesheets)\n return stimulus;\n return {\n ...stimulus,\n stylesheets: stimulus.stylesheets.map((stylesheet, stylesheetIndex) => resolveSharedStylesheetRef(stylesheet, options, diagnostics, `sharedContext.stimuli[${stimulusIndex}].stylesheets[${stylesheetIndex}].href`, stimulus.href ?? stimulus.source)),\n };\n}\nfunction resolveSharedContext(options, diagnostics) {\n const sharedContext = options.section.sharedContext ?? emptySharedContext();\n const role = options.section.role ?? 'candidate';\n const filterBlock = (block) => isQtiViewVisibleForRole(block.view, role);\n return {\n ...sharedContext,\n passages: sharedContext.passages.filter(filterBlock).map((block) => resolveSharedHtmlBlockTools(block, role)),\n stimuli: sharedContext.stimuli.map((stimulus, stimulusIndex) => resolveStimulusStylesheets(stimulus, options, diagnostics, stimulusIndex)),\n rubricBlocks: sharedContext.rubricBlocks.filter(filterBlock).map((block) => resolveSharedHtmlBlockTools(block, role)),\n testFeedback: sharedContext.testFeedback.filter(filterBlock).map((block) => resolveSharedHtmlBlockTools(block, role)),\n stylesheets: sharedContext.stylesheets.map((stylesheet, index) => resolveSharedStylesheetRef(stylesheet, options, diagnostics, `sharedContext.stylesheets[${index}].href`)),\n };\n}\nfunction resolveResponsesByItemIdentifier(options) {\n return Object.fromEntries(options.section.itemRefs.map((item) => [\n item.identifier,\n item.session\n ? item.session.state().responses\n : (options.responsesByItemIdentifier?.[item.identifier] ?? item.responses ?? {}),\n ]));\n}\nexport function resolveQtiSectionComposition(options) {\n const diagnostics = [...(options.section.diagnostics ?? [])];\n if (options.section.itemRefs.length === 0) {\n diagnostics.push({\n severity: 'error',\n source: 'section-player',\n code: 'empty-section',\n message: `Section \"${options.section.identifier}\" does not contain any item refs.`,\n });\n }\n const activeItemIndex = resolveActiveIndex(options, diagnostics);\n const role = options.section.role ?? 'candidate';\n const itemRefs = options.section.itemRefs.map((item) => resolveItemTools(item, role));\n const activeItem = itemRefs[activeItemIndex] ?? {\n identifier: '',\n itemXml: '',\n };\n const sharedContext = resolveSharedContext(options, diagnostics);\n const tools = filterToolsForRole(options.section.tools, role);\n const snapshot = {\n sectionIdentifier: options.section.identifier,\n activeItemIdentifier: activeItem.identifier,\n activeItemIndex,\n itemCount: itemRefs.length,\n responses: resolveResponsesByItemIdentifier(options),\n };\n return {\n section: {\n ...options.section,\n tools,\n itemRefs,\n sharedContext,\n },\n activeItem,\n activeItemIndex,\n sharedContext,\n layout: resolveLayout(options.section, sharedContext),\n canPrevious: options.canPrevious ?? activeItemIndex > 0,\n canNext: options.canNext ?? activeItemIndex < options.section.itemRefs.length - 1,\n snapshot,\n diagnostics: [...diagnostics, ...sharedContext.assetDiagnostics],\n security: options.security,\n host: options.host,\n };\n}\n","/**\n * English (United States) translations\n *\n * Guidelines for translators:\n * - Keep messages concise for UI constraints\n * - Use sentence case for labels, title case for buttons\n * - Maintain consistent terminology across interactions\n * - Variables in {curlyBraces} will be replaced with dynamic values\n */\nexport default {\n common: {\n loading: 'Loading...',\n error: 'Error',\n success: 'Success',\n cancel: 'Cancel',\n confirm: 'Confirm',\n close: 'Close',\n save: 'Save',\n delete: 'Delete',\n edit: 'Edit',\n remove: 'Remove',\n add: 'Add',\n search: 'Search',\n filter: 'Filter',\n reset: 'Reset',\n clear: 'Clear',\n clearAll: 'Clear All',\n submit: 'Submit',\n next: 'Next',\n previous: 'Previous',\n back: 'Back',\n continue: 'Continue',\n finish: 'Finish',\n complete: 'Complete',\n completed: 'Completed',\n status: 'Status',\n required: 'Required',\n review: 'Review',\n selected: 'Selected',\n available: 'Available',\n showDetails: 'Show details',\n hideDetails: 'Hide details',\n details: 'Details',\n deselected: '{item} deselected',\n selectionCancelled: 'Selection cancelled',\n question: 'Question',\n of: 'of',\n answered: 'answered',\n pleaseComplete: 'Please complete the required interactions',\n submitting: 'Submitting...',\n submitAnswer: 'Submit Answer',\n tryAgain: 'Try Again',\n errorNoData: 'No interaction data provided',\n },\n units: {\n bytes: '{count} bytes',\n kilobytes: '{count} KB',\n megabytes: '{count} MB',\n seconds: '{count} seconds',\n minutes: '{count} minutes',\n hours: '{count} hours',\n },\n // Pluralization examples\n // Use i18n.plural('plurals.items', { count: n }) to access these\n plurals: {\n items: {\n one: '{count} item',\n other: '{count} items',\n },\n files: {\n one: '{count} file selected',\n other: '{count} files selected',\n },\n questions: {\n one: '{count} question',\n other: '{count} questions',\n },\n answers: {\n one: '{count} answer',\n other: '{count} answers',\n },\n choices: {\n one: '{count} choice',\n other: '{count} choices',\n },\n attempts: {\n one: '{count} attempt remaining',\n other: '{count} attempts remaining',\n },\n minutesRemaining: {\n one: '{count} minute remaining',\n other: '{count} minutes remaining',\n },\n secondsRemaining: {\n one: '{count} second remaining',\n other: '{count} seconds remaining',\n },\n submitAnswer: {\n one: 'Submit Answer',\n other: 'Submit Answers',\n },\n },\n validation: {\n required: 'This field is required',\n invalidFormat: 'Invalid format',\n tooShort: 'Too short (minimum {min} characters)',\n tooLong: 'Too long (maximum {max} characters)',\n outOfRange: 'Value must be between {min} and {max}',\n },\n interactions: {\n choice: {\n selectOption: 'Select an option',\n selectMultiple: 'Select all that apply',\n selected: 'Selected',\n notSelected: 'Not selected',\n correct: 'Correct',\n },\n upload: {\n // Shown as label above file input\n label: 'Upload a file',\n selectFile: 'Choose file',\n dragDrop: 'or drag and drop',\n // Displayed before list of allowed file types\n allowedTypes: 'Allowed file types:',\n // Displayed when file is selected\n selectedFile: 'Selected:',\n // File size display - {size} will be replaced with numeric value\n fileSize: '{size} bytes',\n fileSizeKb: '{size} KB',\n fileSizeMb: '{size} MB',\n removeFile: 'Remove file',\n // Error shown when file type validation fails\n // {types} will be replaced with comma-separated list of allowed types\n errorInvalidType: 'File type not allowed. Allowed: {types}',\n errorReadFailed: 'Failed to read file',\n // {max} will be replaced with maximum size in MB\n errorTooLarge: 'File is too large (maximum {max} MB)',\n unknownType: 'Unknown file type',\n },\n drawing: {\n label: 'Draw your response',\n clear: 'Clear drawing',\n undo: 'Undo',\n redo: 'Redo',\n strokeColor: 'Stroke color',\n strokeWidth: 'Stroke width',\n tool: 'Tool',\n instructions: 'Draw with your mouse or touch. Use the Clear button to reset.',\n canvas: 'Drawing canvas',\n updated: 'Drawing updated.',\n cleared: 'Drawing cleared.',\n generated: 'Generated:',\n },\n extendedText: {\n placeholder: 'Type your response here...',\n characterCount: '{count} characters',\n characterLimit: '{count} / {max} characters',\n bold: 'Bold',\n italic: 'Italic',\n underline: 'Underline',\n bulletList: 'Bullet list',\n numberedList: 'Numbered list',\n insertMath: 'Insert math equation',\n insertInlineMath: 'Insert inline math',\n insertBlockMath: 'Insert block math',\n enterMathExpression: 'Enter your math expression:',\n latexSource: 'LaTeX source:',\n keyboard: 'Keyboard',\n update: 'Update',\n insert: 'Insert',\n },\n slider: {\n label: 'Slider',\n selectedValue: 'Selected value: {value}',\n min: 'Minimum: {min}',\n max: 'Maximum: {max}',\n step: 'Step: {step}',\n ariaLabel: 'Slider value from {lowerBound} to {upperBound}',\n statTitle: 'Selected Value',\n },\n hottext: {\n selected: 'Selected:',\n selectText: 'Select text from the passage',\n clearSelection: 'Clear Selection',\n ariaLabel: 'Text selection interaction',\n },\n hotspot: {\n selected: 'Selected:',\n selectArea: 'Select areas on the image',\n ariaLabel: 'Hotspot interaction',\n altText: 'Hotspot interaction',\n unknownImageDimensions: 'This hotspot cannot be shown: the size of its image is unknown, so the selectable regions cannot be placed. Add width and height to the image, or supply the asset dimensions.',\n },\n selectPoint: {\n instruction: 'Click on the image to select points',\n instructionAria: 'Click to select points on the image',\n maxPointsReached: 'Maximum points reached. Remove a point to add a new one.',\n point: 'Point {index}',\n removePoint: 'Remove point {index}',\n removePointTitle: 'Click to remove this point',\n removePointAt: 'Remove point {index} at coordinates {x}, {y}',\n removePointAtTitle: 'Click to remove this point ({x}, {y})',\n canvas: 'Selection canvas',\n noImage: 'No image provided',\n pointsSelected: 'Points selected:',\n minimumMet: '✓ Minimum met',\n selectAtLeast: 'Select at least {minChoices}',\n },\n match: {\n pointerInstructions: 'Select a source item, then select its target. You can also drag and drop.',\n selectTarget: 'Select to match',\n // Keyboard instruction for accessible drag-drop\n keyboardInstructions: 'Press Space or Enter to select a source item. Tab to navigate to targets. Press Space or Enter on a target to create a match. Press Escape to cancel selection.',\n dragInstruction: 'Press Space or Enter to match',\n dropTarget: 'Drop item here',\n matchedWith: 'Matched with {target}',\n selectedForMatching: 'Selected for matching',\n available: 'Available',\n availableForMatching: 'Available for matching',\n removeMatch: 'Remove match',\n clearMatch: 'Clear match for {source}',\n sourceItemsLabel: 'Source items to match',\n targetItemsLabel: 'Target items for matching',\n dragFromHere: 'Drag from here:',\n dropHere: 'Drop here:',\n deselected: '{item} deselected',\n selected: '{item} selected',\n navigateToTarget: 'Navigate to a target and press Space or Enter to match',\n selectionCancelled: 'Selection cancelled',\n matchCleared: 'Match cleared for {item}',\n },\n gapMatch: {\n filledGapAriaLabelWithHeld: 'Blank {gapId}, filled with {word}. Select to replace with {heldWord}.',\n blankGapAriaLabelWithHeld: 'Blank {gapId}. Select to place {heldWord} here.',\n placed: 'Placed {word} in blank {gapId}.',\n pointerInstructions: 'Select a word, then select a blank. You can also drag and drop.',\n instruction: 'Drag words to fill in the blanks',\n available: 'Available words',\n availableLabel: 'Available words to place',\n availableHeading: 'Available words:',\n removeWord: 'Remove word',\n // {word} will be replaced with the word being removed\n removeFromBlanks: 'Remove {word} from the blanks',\n selectPlaceholder: 'Select...',\n gapAriaLabel: 'Gap {gapId}',\n blankGapAriaLabel: 'Blank {gapId}. Drop an answer here.',\n filledGapAriaLabel: 'Blank {gapId}, filled with {word}. Click to clear.',\n },\n graphicGapMatch: {\n pointerInstructions: 'Select a label, then select a hotspot on the image. You can also drag and drop.',\n instruction: 'Place labels on the image hotspots',\n keyboardInstructions: 'Press Space or Enter to select a label. Tab to navigate to hotspots on the image. Press Space or Enter on a hotspot to place the label. Press Escape to cancel selection.',\n available: 'Available labels',\n availableLabel: 'Available labels to place',\n availableHeading: 'Available Labels:',\n alreadyPlaced: 'Already placed on hotspot',\n selectedForPlacement: 'Selected for placement',\n pressSpaceToSelect: 'Press Space to select',\n pressSpaceToPlace: 'Press Space or Enter to place label',\n removeLabel: 'Remove label',\n removeFromHotspot: 'Remove {label} from hotspot',\n labelPlaced: '{label} placed on hotspot {hotspot}',\n hotspot: 'Hotspot {number}',\n contains: 'Contains: {label}',\n },\n order: {\n moveEarlier: 'Move earlier',\n moveLater: 'Move later',\n instruction: 'Use the move buttons or drag items to reorder them.',\n keyboardInstructions: 'Press Space or Enter to grab an item. Use arrow keys to move the item. Press Space or Enter again to drop. Press Escape to cancel.',\n grabbed: 'Grabbed. Use arrow keys to move.',\n moveUp: 'Move up',\n moveDown: 'Move down',\n position: 'Position {current} of {total}',\n listLabel: 'Reorderable list of choices',\n confirmOrder: 'Confirm Order',\n confirmOrderNoChanges: 'Confirm Order (No Changes)',\n confirmAria: 'Confirm this order as your answer',\n itemGrabbed: '{item} grabbed. Current position {position} of {total}. Use arrow keys to move, Space or Enter to drop.',\n itemDropped: '{item} dropped at position {position} of {total}',\n itemMoved: '{item} moved to position {position} of {total}',\n selectionCancelled: '{item} selection cancelled',\n },\n associate: {\n instruction: 'Create associations between items',\n createPair: 'Create pair',\n removePair: 'Remove pair',\n removeAssociation: 'Remove association',\n diagramLabel: 'Association diagram',\n altText: 'Association diagram',\n hotspotConnections: '{label} ({usageCount}/{matchMax} connections)',\n selectAnother: 'Selected: <strong>{label}</strong>. Click another',\n selectAnotherHotspot: 'Selected: <strong>{label}</strong>. Click another hotspot to create an association.',\n minimumRequired: 'Minimum required: {minAssociations}',\n currentAssociations: 'Current Associations',\n correctAssociations: 'Correct Associations',\n clickToAssociate: 'Click two items to create an association between them',\n clickAnotherOrDeselect: 'Click another item to create an association (or click again to deselect)',\n associations: 'Associations',\n associationsCount: 'Associations ({count}/{max})',\n clickHotspotsToAssociate: 'Click two hotspots on the image to create an association.',\n clickAnotherHotspot: 'Selected: <strong>{label}</strong>. Click another hotspot to create an association.',\n },\n positionObject: {\n instruction: 'Drag objects onto the image',\n placeObject: 'Place {object} on image',\n removeObject: 'Remove {object}',\n objectAt: '{object} at position ({x}, {y})',\n canvasLabel: 'Positioning canvas',\n backgroundAlt: 'Positioning background',\n positioned: 'Positioned {label} at ({x}, {y})',\n minimumRequired: 'Minimum required: {minChoices}',\n maximumAllowed: 'Maximum: {maxChoices}',\n availableObjects: 'Available Objects',\n objectUsage: '{label} ({usageCount}/{matchMax} used)',\n availableObjectsCount: 'Available Objects ({count}/{max})',\n dragObjectsInstruction: 'Drag objects onto the canvas to position them.',\n used: '{usageCount}/{matchMax} used',\n },\n endAttempt: {\n buttonLabel: 'End Attempt',\n ended: 'Attempt Ended',\n requested: 'Requested',\n warningMessage: 'Your attempt has been ended and can no longer be modified.',\n confirmMessage: 'Are you sure you want to end your attempt? You will not be able to change your responses.',\n },\n media: {\n play: 'Play',\n pause: 'Pause',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n fullscreen: 'Fullscreen',\n exitFullscreen: 'Exit fullscreen',\n playbackSpeed: 'Playback speed',\n currentTime: '{current} / {duration}',\n loading: 'Loading media...',\n ariaLabel: 'Media content',\n maxPlayLimitReached: 'Maximum play limit reached',\n playCount: 'Play count:',\n remaining: 'Remaining:',\n requirementMet: '✓ Requirement met',\n playAtLeast: 'Play at least {minPlays} time',\n playAtLeastPlural: 'Play at least {minPlays} times',\n browserNoSupport: 'Your browser does not support this media type.',\n audioNoSupport: 'Your browser does not support the audio element.',\n videoNoSupport: 'Your browser does not support the video element.',\n objectDisabled: 'This item uses an embedded object type that is disabled by default for security.',\n },\n graphicOrder: {\n instruction: 'Click hotspots to order them',\n diagramLabel: 'Ordering diagram',\n altText: 'Ordering diagram',\n orderHeading: 'Order (drag to reorder)',\n itemLabel: 'Item {index}: {label}',\n confirmOrder: 'Confirm Order',\n confirmOrderNoChanges: 'Confirm Order (No Changes)',\n confirmAria: 'Confirm this order as your answer',\n },\n custom: {\n unsupported: 'Unsupported customInteraction',\n description: 'This item contains a vendor-specific interaction. This player does not execute custom interactions.',\n promptLabel: 'Prompt',\n manualResponse: 'Manual response (optional)',\n placeholder: 'Enter a manual response (fallback)',\n attributes: 'Attributes',\n xml: 'XML',\n },\n inline: {\n placeholder: '...',\n selectPlaceholder: 'Select...',\n },\n },\n item: {\n loading: 'Loading item...',\n loadingError: 'Failed to load item',\n loadError: 'Error loading item: {error}',\n parsingError: 'Failed to parse QTI XML',\n processingError: 'Failed to process responses',\n submit: 'Submit',\n complete: 'Complete',\n completed: 'Completed',\n attempt: 'Attempt {numAttempts}',\n },\n itemSession: {\n attempt: 'Attempt {numAttempts}',\n attemptsRemaining: '{attemptsRemaining} attempts remaining',\n maxAttempts: 'Max attempts: {maxAttempts}',\n },\n feedback: {\n close: 'Close feedback',\n closeFeedback: 'Dismiss feedback',\n testFeedback: 'Test feedback',\n },\n assessment: {\n title: 'Assessment',\n loading: 'Loading assessment...',\n loadingError: 'Timeout loading assessment. This assessment may be invalid or the player failed to initialize.',\n question: 'Question {current} of {total}',\n questionAnnouncement: 'Question {current} of {total}',\n section: 'Section {current} of {total}',\n sectionDefault: 'Section {number}',\n closeMenu: 'Close menu',\n readingPassage: 'Reading Passage',\n readingPassages: 'Reading passages',\n expandPassage: 'Expand passage',\n collapsePassage: 'Collapse passage',\n attempts: {\n remaining: '{count} attempts remaining',\n oneRemaining: '1 attempt remaining',\n noRemaining: 'No attempts remaining ({count} used)',\n used: 'Attempts: {count}',\n maxReached: 'Max attempts reached',\n required: 'Must answer before continuing',\n reviewNotAllowed: 'Not allowed once submitted',\n },\n navigation: {\n previous: 'Previous',\n next: 'Next',\n submit: 'Submit',\n jumpTo: 'Jump to question {number}',\n sectionMenu: 'Section menu',\n progress: 'Progress: {percent}%',\n },\n sections: {\n title: 'Sections',\n selectSection: 'Select section',\n },\n timer: {\n remaining: 'Time Remaining',\n elapsed: 'Time Elapsed',\n expired: 'Time Expired',\n timeRemaining: 'Time remaining: {time}',\n timeElapsed: 'Time elapsed: {time}',\n timeUp: \"Time's up!\",\n },\n feedback: {\n correct: 'Correct',\n incorrect: 'Incorrect',\n partiallyCorrect: 'Partially correct',\n unanswered: 'Unanswered',\n score: 'Score: {score} / {maxScore}',\n passed: 'Passed',\n failed: 'Failed',\n },\n completion: {\n title: 'Assessment Complete',\n message: 'You have completed the assessment.',\n score: 'Your score: {score} out of {maxScore}',\n percentage: 'Percentage: {percent}%',\n viewResults: 'View results',\n exit: 'Exit',\n },\n errors: {\n navigationFailed: 'Navigation failed. Please try again.',\n submitFailed: 'Failed to submit assessment. Please try again.',\n loadFailed: 'Failed to load question.',\n saveFailed: 'Failed to save response.',\n },\n },\n i18n: {\n selectLanguage: 'Language',\n selectLanguageAriaLabel: 'Select display language',\n },\n accessibility: {\n skipToContent: 'Skip to content',\n skipToNavigation: 'Skip to navigation',\n itemBody: 'Question content',\n navigationRegion: 'Assessment navigation',\n announcement: 'Announcement',\n newQuestion: 'New question loaded',\n answerRecorded: 'Answer recorded',\n resizer: 'Resize passage and question panels',\n },\n demo: {\n selectSampleItem: 'Select Sample Item',\n configurationPanel: 'Configuration Panel',\n viewingAs: 'Viewing as',\n role: 'Role',\n candidate: 'Candidate',\n author: 'Author',\n proctor: 'Proctor',\n scorer: 'Scorer',\n tutor: 'Tutor',\n showCorrectAnswers: 'Show correct answers',\n showFeedback: 'Show feedback',\n settings_aria: 'Open settings menu',\n xmlEditor: 'XML Editor',\n // Navigation\n appName: 'PIE QTI Player',\n home: 'Home',\n itemDemo: 'Item Demo',\n assessmentDemo: 'Assessment Demo',\n likertDemo: 'Likert Plugin Demo',\n iframeDemo: 'Iframe Demo',\n theme: 'Theme',\n // Home Page\n homeTitle: 'QTI Player',\n homeSubtitle: 'A modern, framework-agnostic player for QTI assessment items. Works 100% client-side by default, with optional server-side hooks for production use.',\n homeMetaDescription: 'Modern QTI player with optional backend integration',\n tryItems: 'Try Items',\n tryAssessments: 'Try Assessments',\n trySectionPlayer: 'Section Player',\n pluginDemo: 'Plugin Demo',\n dropQtiFile: 'Drop QTI XML file here',\n orClickToSelect: 'or click to select a file',\n selectFile: 'Select File',\n selectedFile: 'Selected:',\n loadInPlayer: 'Load in Player',\n footerTitle: 'QTI Player',\n footerLicense: 'MIT Licensed • Open Source',\n // Settings Panel\n settings: 'Settings',\n candidateStudent: 'Candidate (Student)',\n testConstructor: 'Test Constructor',\n controlsRubricVisibility: 'Controls rubric visibility and correct answer display',\n useBackendScoring: 'Use Backend Scoring',\n scoreOnServer: 'Score responses on the server instead of client-side',\n sessionManagement: 'Session Management',\n saving: 'Saving...',\n saveSession: 'Save Session',\n loadSession: 'Load Session',\n // Export & Template\n exportResponses: 'Export Responses',\n json: 'JSON',\n csv: 'CSV',\n templateProcessing: 'Template Processing',\n rerunTemplateProcessing: 'Re-run templateProcessing and reset the item session',\n regenerateVariant: 'Regenerate Variant',\n templateVariablesDebug: 'Template Variables (Debug)',\n variable: 'Variable',\n value: 'Value',\n // Keyboard Shortcuts\n keyboardShortcuts: 'Keyboard Shortcuts',\n submitAnswersShortcut: 'Submit answers',\n tryAgainShortcut: 'Try again',\n exportJsonShortcut: 'Export JSON',\n saveSessionShortcut: 'Save session',\n useCmdOnMacOS: 'Use <kbd class=\"kbd kbd-xs\">Cmd</kbd> on macOS',\n // Results Panel\n results: 'Results',\n score: 'Score',\n outcomeVariables: 'Outcome Variables',\n // Misc\n format: 'Format',\n selectItemOrPasteXml: 'Select a sample item or paste custom XML to get started.',\n pageTitle: 'Player Demo - PIE QTI Player',\n // Sample Item Descriptions\n sampleItemDescriptions: {\n '': 'Custom uploaded item',\n 'simple-choice': 'Basic subtraction word problem with plausible distractors',\n 'partial-credit': 'Multiple choice with partial credit using mapResponse',\n 'capital-cities': 'Geography question with shuffled choices',\n 'text-entry': 'Fill-in-the-blank question with case-insensitive matching',\n 'extended-text': 'Multi-line text response question',\n 'inline-choice': 'Dropdown menu embedded in text',\n 'order-interaction': 'Arrange items in correct sequence',\n 'match-interaction': 'Match items from two columns',\n 'associate-interaction': 'Create associations between items',\n 'gap-match': 'Drag words into gaps in text',\n 'graphic-gap-match-solar-system': 'Label the four inner planets of our solar system',\n 'slider': 'Select a value on a numerical slider',\n 'hotspot': 'Click on the Blue Planet in this astronomy question',\n 'hotspot-partial-credit': 'Identify planet with liquid water (partial credit for terrestrial planets)',\n 'template-variable-demo': 'templateProcessing generates values; responseProcessing scores against them',\n 'upload-interaction': 'Upload a file as the response (baseType=file)',\n 'drawing-interaction': 'Draw on a canvas (baseType=file, PNG dataUrl)',\n 'media-audio': 'Audio player with play count tracking and minPlays requirement',\n 'media-video': 'Video player with play count tracking and maxPlays limit',\n 'hottext-single': 'Click to select a single word within text (grammar question)',\n 'hottext-multiple': 'Click to select multiple text segments (reading comprehension)',\n 'select-point': 'Click on the image to select a point location (geography question)',\n 'graphic-order': 'Drag to reorder items on an image (geological layers)',\n 'graphic-associate': 'Click pairs of hotspots to create associations (organ matching)',\n 'position-object': 'Drag and position furniture objects on a room layout',\n 'end-attempt': 'Button to end the assessment attempt',\n 'custom-interaction': 'Shows a fallback UI for customInteraction and allows a manual response',\n 'choice-with-stimulus': 'Question with reading passage embedded inline',\n 'math-inline': 'Multiple choice with MathML inline math rendering',\n 'math-extended': 'Extended response with MathML and rich text editor for showing mathematical work',\n 'math-fractions': 'Fraction arithmetic with MathML block display',\n 'adaptive-capitals': 'Multi-attempt adaptive question with progressive feedback and hints',\n },\n },\n transform: {\n // App title and navigation\n appName: 'QTI Batch Processor',\n appDescription: 'Upload QTI packages to analyze structure, transform to PIE format, and preview results',\n home: 'Home',\n // Session management\n sessions: {\n title: 'Recent Sessions',\n session: 'Session',\n status: 'Status',\n packages: 'Packages',\n created: 'Created',\n createdAt: 'Created {date}',\n open: 'Open',\n delete: 'Delete',\n deleteTitle: 'Delete session',\n deleteConfirmTitle: 'Delete Session',\n deleteConfirmMessage: 'Are you sure you want to delete this session? This action cannot be undone and all files will be permanently removed.',\n deleted: 'Session deleted',\n notFound: 'Session Not Found',\n notFoundMessage: 'The requested session could not be found or does not exist.',\n },\n // Samples\n samples: {\n title: 'Sample QTI Packages',\n description: 'Try the processor with pre-loaded sample packages demonstrating various QTI interaction types.',\n itemCount: {\n one: '{count} item',\n other: '{count} items',\n },\n hasManifest: 'Manifest',\n load: 'Load Sample',\n loadSample: 'Load Sample',\n loaded: \"Sample '{id}' loaded successfully\",\n notFound: \"Sample package '{id}' not found\",\n loadFailed: 'Failed to load sample',\n },\n // Upload\n upload: {\n dropPrompt: 'Drop QTI ZIP files here',\n orClickToSelect: 'or click to select files',\n selectFiles: 'Select Files',\n processing: 'Processing...',\n invalidType: 'Only ZIP files are allowed',\n fileTooLarge: 'File too large: {filename}. Maximum size is {maxSize}MB.',\n noFiles: 'No files provided',\n uploadFailed: 'Upload failed',\n },\n // Session detail page\n detail: {\n uploadedPackages: 'Uploaded Packages',\n package: 'Package',\n type: 'Type',\n size: 'Size',\n uploaded: 'Uploaded',\n actions: 'Actions',\n analyzing: 'Package is being analyzed...',\n analysisComplete: 'Analysis complete. Review results below or proceed to transformation.',\n cannotConvert: 'Cannot Convert to PIE',\n unsupportedMessage: 'This package contains QTI interaction types that have no PIE equivalent. See issues below for details. Use the QTI player instead to preview these items.',\n transforming: 'Transforming...',\n transformToPie: 'Transform to PIE',\n analysisResults: 'Analysis Results',\n totalItems: 'Total Items',\n passages: 'Passages',\n tests: 'Tests',\n interactionTypesFound: 'Interaction Types Found',\n issuesFound: 'Issues Found',\n packageDetails: 'Package Details',\n noManifest: 'No Manifest',\n items: 'items',\n interactionTypes: 'Interaction Types',\n assessmentTests: 'Assessment Tests',\n file: 'File',\n pattern: 'Pattern',\n sampleItems: 'Sample Items by Interaction Type',\n issues: 'Issues',\n browseAssessments: 'Browse & Preview Assessment Tests',\n browseAssessmentsDescription: {\n one: 'Browse and preview {count} QTI assessment test found in this session',\n other: 'Browse and preview {count} QTI assessment tests found in this session',\n },\n individualItems: 'Individual Items',\n browseItems: 'Browse & Preview Items',\n browseItemsDescription: {\n one: 'Browse and preview {count} QTI item found in this session',\n other: 'Browse and preview {count} QTI items found in this session',\n },\n },\n // Analysis results\n analysis: {\n title: 'Analysis Results',\n totalItems: 'Total Items',\n passages: 'Passages',\n tests: 'Tests',\n packages: 'Packages',\n interactionTypesFound: 'Interaction Types Found',\n issuesFound: 'Issues Found ({count})',\n assessmentTests: 'Assessment Tests',\n individualItems: 'Individual Items',\n },\n // Items browser\n items: {\n title: 'Item Browser',\n description: 'Browse and preview {count} QTI assessment items',\n loading: 'Loading items...',\n notFound: 'No items found in this session.',\n itemsCount: 'Items ({count})',\n showCorrect: 'Show Correct',\n xmlNotAvailable: 'Item XML not available',\n noSelection: 'No item selected',\n notAvailable: 'Items Not Available',\n },\n // Assessments browser\n assessments: {\n title: 'Assessment Tests',\n loading: 'Loading assessment tests...',\n notFound: 'No assessment tests found in this session.',\n showCorrect: 'Show Correct',\n assessmentsCount: 'Assessments ({count})',\n selectPrompt: 'Select an assessment to preview',\n },\n // Transformation results\n transformed: {\n pageTitle: 'Transformation Results - Session {sessionId}',\n breadcrumb: 'Transformed',\n title: 'Transformation Results',\n // Two independent counts in one sentence, so the caller composes it:\n // plural('…summaryItems', { count: itemCount }) and, when there are\n // assessments, plural('…summaryAssessments', { count: assessmentCount }),\n // interpolated into summary or summaryWithAssessments along with duration.\n summary: '{items} transformed in {duration}',\n summaryWithAssessments: '{items} + {assessments} transformed in {duration}',\n summaryItems: {\n one: '{count} item',\n other: '{count} items',\n },\n summaryAssessments: {\n one: '{count} assessment',\n other: '{count} assessments',\n },\n backToSession: 'Back to Session',\n content: 'Transformed Content',\n items: 'Items',\n assessments: 'Assessments',\n errors: 'Errors',\n warnings: {\n one: '{count} warning',\n other: '{count} warnings',\n },\n transformationErrors: {\n one: '{count} Transformation Error',\n other: '{count} Transformation Errors',\n },\n noItems: 'No items transformed',\n selectPrompt: 'Select an item or assessment to preview',\n },\n // PIE Player controls\n player: {\n selectPlayerType: 'Select player type',\n iife: 'IIFE',\n esm: 'ESM',\n gather: 'Gather',\n view: 'View',\n evaluate: 'Evaluate',\n browse: 'Browse',\n student: 'Student',\n instructor: 'Instructor',\n notAvailable: 'PIE Players Not Available',\n debugConfig: 'Debug: config JSON',\n },\n // QTI Player controls\n qtiPlayer: {\n errorLoading: 'Error loading QTI player',\n loading: 'Loading QTI player...',\n waitingForData: 'Waiting for assessment data...',\n },\n // Assessment preview\n assessmentPreview: {\n totalItems: 'Total Items',\n sections: 'Sections',\n timeLimit: 'Time Limit',\n configuration: 'Configuration',\n navigation: 'Navigation:',\n submission: 'Submission:',\n },\n // Confirmation dialog\n dialog: {\n defaultTitle: 'Confirm Action',\n defaultConfirm: 'Confirm',\n defaultCancel: 'Cancel',\n close: 'close',\n },\n // API Error messages\n errors: {\n noContent: 'Please provide QTI XML content',\n invalidQti: 'The provided content does not appear to be valid QTI XML',\n transformFailed: 'Transformation failed',\n noItemsProduced: 'Transformation produced no items',\n transformError: 'Transformation error: {message}',\n sessionNotFound: 'Session not found',\n alreadyAnalyzed: 'Session already analyzed',\n noListSupport: 'Storage backend does not support listing files',\n noZipFiles: 'No ZIP files found and no extracted files available',\n extractFailed: 'Failed to extract {filename}',\n analysisComplete: 'Analysis complete',\n notAnalyzed: 'Session not analyzed yet',\n analysisFailed: 'Analysis failed',\n noTransformation: 'No transformation results found for session {sessionId}',\n getTransformationFailed: 'Failed to get transformation results',\n loadSamplesFailed: 'Failed to load samples',\n },\n // Badges\n badges: {\n qti: 'QTI',\n uploaded: 'Uploaded',\n },\n // Admin / Plugin Management\n admin: {\n plugins: {\n title: 'Plugin Management',\n subtitle: 'View installed plugins and available extension points',\n totalPlugins: 'Total Plugins',\n activePlugins: 'All plugins active',\n vendorExtensions: 'Vendor Extensions',\n extensionsRegistered: 'Registered',\n storageBackend: 'Storage Backend',\n installedPlugins: 'Installed Transform Plugins',\n pluginsDescription: 'These plugins handle transformations between different formats',\n pluginName: 'Plugin Name',\n format: 'Format',\n priority: 'Priority',\n version: 'Version',\n status: 'Status',\n active: 'Active',\n vendorExtensionPoints: 'Vendor Extension Points',\n extensionsDescription: 'Vendor-specific extensions registered in plugins',\n noExtensions: 'No extensions',\n extensionsActive: '{count} active',\n availableExtensionPoints: 'Available Extension Points',\n configureExtensions: 'Configure these via config.json or environment variables',\n storageBackends: 'Storage Backends',\n storageDescription: 'Choose where to store sessions and transformed content',\n transformFormats: 'Transform Formats',\n formatsDescription: 'Supported input and output formats for transformations',\n vendorExtensionTypes: 'Vendor Extension Types',\n vendorTypesDescription: 'Customize transformation behavior for specific vendors',\n uiThemes: 'UI Themes',\n themesDescription: 'Customize the application appearance',\n locales: 'Locales',\n localesDescription: 'Add translations for different languages',\n howToConfigure: 'How to Configure',\n configureVia: 'Configure plugins and extensions through these methods:',\n envVar: 'Environment variable',\n configFile: 'Config file',\n seeExample: 'See',\n forStructure: 'for structure',\n directCode: 'Direct code',\n registerIn: 'Register in',\n },\n },\n },\n}; // 'as const' for strict type inference\n//# sourceMappingURL=en-US.js.map","/**\n * Default I18n provider implementation\n *\n * This is the framework's default implementation of the I18nProvider interface.\n * It uses standard dynamic imports for lazy locale loading and provides simple\n * interpolation and pluralization support.\n */\nimport enUS from '../locales/en-US.js';\n/**\n * Lazy loaders for the framework locales.\n *\n * An explicit static map rather than a bundler macro: `tsc` emits these\n * `import()` calls verbatim, so the published package evaluates anywhere ESM\n * does — webpack, esbuild, Rollup, Node, or a browser loading the files\n * directly. Every bundler still sees the specifiers statically, so each locale\n * remains its own chunk and a host that only renders English never fetches the\n * others. Adding a locale means adding a line here alongside the file.\n *\n * en-US is a plain static import because it is the fallback for every missing\n * key in every other locale, so it must be resolvable synchronously in the\n * constructor.\n */\nconst localeLoaders = {\n 'en-US': () => Promise.resolve({ default: enUS }),\n 'ar-SA': () => import('../locales/ar-SA.js'),\n 'es-ES': () => import('../locales/es-ES.js'),\n 'fr-FR': () => import('../locales/fr-FR.js'),\n 'nl-NL': () => import('../locales/nl-NL.js'),\n 'ro-RO': () => import('../locales/ro-RO.js'),\n 'th-TH': () => import('../locales/th-TH.js'),\n 'zh-CN': () => import('../locales/zh-CN.js'),\n};\n/**\n * Whether to log missing-translation warnings.\n *\n * `process` does not exist in a plain browser, so the read is guarded rather\n * than bare: an unguarded `process.env.NODE_ENV` throws a ReferenceError on the\n * missing-key path for any consumer that is not running the code through a\n * bundler that substitutes it.\n */\nconst isDevelopment = typeof process !== 'undefined' && process.env?.NODE_ENV === 'development';\n/**\n * Right-to-left primary language subtags.\n *\n * Only consulted when `Intl.Locale.prototype.textInfo` is unavailable — it is the\n * authoritative source but shipped late in Safari, and an assessment rendered\n * left-to-right for an Arabic reader is not a graceful degradation.\n */\nconst RTL_LANGUAGES = new Set([\n 'ar', // Arabic\n 'ckb', // Central Kurdish\n 'dv', // Dhivehi\n 'fa', // Persian\n 'he',\n 'iw', // Hebrew (current and legacy subtags)\n 'ks', // Kashmiri\n 'ku', // Kurdish\n 'nqo', // N'Ko\n 'ps', // Pashto\n 'sd', // Sindhi\n 'syr', // Syriac\n 'ug', // Uyghur\n 'ur', // Urdu\n 'yi', // Yiddish\n]);\nexport class DefaultI18nProvider {\n /** Shared across instances: constructing Intl.PluralRules is not cheap */\n static pluralRules = new Map();\n currentLocale;\n messages;\n customMessages; // Client-provided translations\n fallbackLocale = 'en-US';\n loadedLocales = new Set();\n constructor(locale = 'en-US', customMessages) {\n // Read persisted locale from localStorage if available\n // This allows locale changes to persist across page reloads\n const storedLocale = typeof localStorage !== 'undefined'\n ? localStorage.getItem('pie-qti-locale')\n : null;\n this.currentLocale = storedLocale || locale;\n this.messages = {};\n this.customMessages = customMessages || {};\n // en-US is the fallback for every other locale, so it is always present\n this.messages['en-US'] = enUS;\n this.loadedLocales.add('en-US');\n }\n /**\n * Load locale messages dynamically (framework locales only)\n * For custom locales, use the customMessages parameter in the constructor or addCustomMessages()\n */\n async loadLocale(locale) {\n if (this.loadedLocales.has(locale)) {\n return; // Already loaded\n }\n try {\n const loader = localeLoaders[locale];\n if (!loader) {\n throw new Error(`Locale '${locale}' is not a framework locale`);\n }\n const module = await loader();\n this.messages[locale] = module.default;\n this.loadedLocales.add(locale);\n }\n catch (error) {\n console.error(`[i18n] Failed to load locale '${locale}':`, error);\n throw error;\n }\n }\n /**\n * Set current locale\n * For framework locales, loadLocale() should be called first.\n * For custom locales, translations should be provided via customMessages.\n */\n setLocale(locale) {\n // Allow setting custom locales even if not in loadedLocales\n // They will use customMessages + fallback to en-US\n if (!this.loadedLocales.has(locale) && !this.customMessages[locale]) {\n console.warn(`[i18n] Locale '${locale}' not loaded and no custom messages provided. Using fallback locale.`);\n }\n this.currentLocale = locale;\n }\n /**\n * Get current locale\n */\n getLocale() {\n return this.currentLocale;\n }\n /**\n * Translate message key with optional default and/or interpolation\n * @example t('upload.label') => \"Upload a file\"\n * @example t('upload.label', 'Upload') => translated or \"Upload\" if missing\n * @example t('upload.selected', { name: 'file.pdf' }) => \"Selected: file.pdf\"\n */\n t(key, defaultOrValues, values) {\n const message = this.getMessage(key);\n const interpolationValues = typeof defaultOrValues === 'object' && defaultOrValues !== null\n ? defaultOrValues\n : values;\n const defaultStr = typeof defaultOrValues === 'string' ? defaultOrValues : undefined;\n if (!message) {\n if (isDevelopment) {\n console.warn(`[i18n] Missing translation: ${key} (locale: ${this.currentLocale})`);\n }\n return defaultStr ?? key;\n }\n if (!interpolationValues)\n return message;\n // Simple interpolation: replace {key} with values[key]\n return message.replace(/\\{(\\w+)\\}/g, (match, k) => {\n return String(interpolationValues[k] ?? match);\n });\n }\n /**\n * Pluralization support\n *\n * The plural category comes from `Intl.PluralRules` for the active locale, so\n * locales with more than two forms resolve correctly: Arabic selects between\n * zero/one/two/few/many/other, Romanian between one/few/other. A locale whose\n * catalog does not carry the selected category falls back to `.other`.\n *\n * @example plural('plurals.files', { count: 1 }) => \"1 file selected\"\n * @example plural('plurals.files', { count: 5 }) => \"5 files selected\"\n */\n plural(key, options) {\n const { count } = options;\n const category = this.selectPluralCategory(count);\n const categoryKey = `${key}.${category}`;\n const pluralKey = this.getMessage(categoryKey) !== undefined ? categoryKey : `${key}.other`;\n return this.t(pluralKey, options);\n }\n /**\n * Select the CLDR plural category for a count in the active locale\n *\n * Falls back to the English one/other split if the locale tag is not one\n * `Intl.PluralRules` accepts — a host may set an arbitrary custom locale code.\n */\n selectPluralCategory(count) {\n let rules = DefaultI18nProvider.pluralRules.get(this.currentLocale);\n if (!rules) {\n try {\n rules = new Intl.PluralRules(this.currentLocale);\n }\n catch {\n return count === 1 ? 'one' : 'other';\n }\n DefaultI18nProvider.pluralRules.set(this.currentLocale, rules);\n }\n return rules.select(count);\n }\n /**\n * Writing direction of the current locale\n *\n * @example getDirection() => 'rtl' for ar-SA, 'ltr' for en-US\n */\n getDirection() {\n try {\n // textInfo is the authoritative CLDR answer where the engine has it\n const textInfo = new Intl.Locale(this.currentLocale)\n .textInfo;\n if (textInfo?.direction === 'rtl' || textInfo?.direction === 'ltr') {\n return textInfo.direction;\n }\n }\n catch {\n // Not a tag Intl.Locale accepts; the subtag check below still works\n }\n const language = this.currentLocale.toLowerCase().split(/[-_]/)[0] ?? '';\n return RTL_LANGUAGES.has(language) ? 'rtl' : 'ltr';\n }\n /**\n * A view of this provider fixed to another locale\n *\n * Catalogs, loaded-locale bookkeeping and custom messages are shared by\n * reference, so `loadLocale()` through either side is visible to both and no\n * catalog is parsed twice. This is what lets two players on one page render\n * different locales from one provider: the locale is per-view, the catalogs\n * are per-provider.\n */\n withLocale(locale) {\n if (locale === this.currentLocale)\n return this;\n const view = new DefaultI18nProvider(locale, this.customMessages);\n // The constructor prefers a persisted locale; an explicit view must not.\n view.currentLocale = locale;\n view.messages = this.messages;\n view.loadedLocales = this.loadedLocales;\n return view;\n }\n /**\n * Format number according to locale\n */\n formatNumber(value, options) {\n return new Intl.NumberFormat(this.currentLocale, options).format(value);\n }\n /**\n * Format date according to locale\n */\n formatDate(date, options) {\n return new Intl.DateTimeFormat(this.currentLocale, options).format(date);\n }\n /**\n * Get nested message by dot notation key\n * Priority: custom messages > current locale > fallback locale\n */\n getMessage(key) {\n // 1. Try custom messages first (client overrides)\n const customMessage = this.getMessageFromObject(key, this.customMessages[this.currentLocale]);\n if (customMessage !== undefined)\n return customMessage;\n // 2. Try current locale from framework defaults\n const messages = this.messages[this.currentLocale];\n if (messages) {\n const message = this.getMessageFromObject(key, messages);\n if (message !== undefined)\n return message;\n }\n // 3. Try custom fallback locale\n const customFallback = this.getMessageFromObject(key, this.customMessages[this.fallbackLocale]);\n if (customFallback !== undefined)\n return customFallback;\n // 4. Try framework fallback locale\n return this.getMessageFromFallback(key);\n }\n /**\n * Get message from a specific messages object\n *\n * Resolves to a string or nothing. A key that lands on a namespace branch\n * (`t('common')`) or on a plural sub-object (`t('plurals.items')`) is a miss,\n * not a hit: returning the branch would put an object where the caller\n * expects a string, and interpolating one throws.\n */\n getMessageFromObject(key, messages) {\n if (!messages)\n return undefined;\n const parts = key.split('.');\n let current = messages;\n for (const part of parts) {\n if (current === null || typeof current !== 'object')\n return undefined;\n current = current[part];\n if (current === undefined)\n return undefined;\n }\n return typeof current === 'string' ? current : undefined;\n }\n /**\n * Get message from fallback locale (framework defaults)\n */\n getMessageFromFallback(key) {\n const messages = this.messages[this.fallbackLocale];\n return this.getMessageFromObject(key, messages);\n }\n /**\n * Add or update custom messages for a locale\n * This allows clients to provide their own translations or override defaults\n */\n addCustomMessages(locale, messages) {\n this.customMessages[locale] = this.deepMerge(this.customMessages[locale] || {}, messages);\n }\n /**\n * Deep merge two objects (for merging translation objects)\n */\n deepMerge(target, source) {\n const result = { ...target };\n for (const key in source) {\n if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {\n result[key] = this.deepMerge(result[key] || {}, source[key]);\n }\n else {\n result[key] = source[key];\n }\n }\n return result;\n }\n}\n/**\n * Factory function to create a default i18n provider instance\n * @param locale - Initial locale code (default: 'en-US')\n * @param customMessages - Optional custom translations to add or override framework defaults\n * @returns DefaultI18nProvider instance\n */\nexport function createDefaultI18nProvider(locale = 'en-US', customMessages) {\n return new DefaultI18nProvider(locale, customMessages);\n}\n//# sourceMappingURL=I18n.js.map","import type { QtiSectionRole } from '../contracts/index.js';\n\nexport function normalizeQtiViewTokens(view: string[] | undefined): string[] {\n return (view ?? [])\n .flatMap((token) => token.split(/[\\s,]+/))\n .map((token) => token.trim())\n .filter(Boolean);\n}\n\nexport function isQtiViewVisibleForRole(view: string[] | undefined, role: QtiSectionRole = 'candidate'): boolean {\n const tokens = normalizeQtiViewTokens(view);\n if (tokens.length === 0) return true;\n return tokens.includes(role);\n}\n","/**\n * Tool Context Types\n *\n * Defines the context types passed to tools for making visibility and behavior decisions.\n * Each context level provides increasingly specific information about where the tool is being used.\n */\n/**\n * Type guard to check if context is at assessment level\n */\nexport function isAssessmentContext(context) {\n return context.level === \"assessment\";\n}\n/**\n * Type guard to check if context is at section level\n */\nexport function isSectionContext(context) {\n return context.level === \"section\";\n}\n/**\n * Type guard to check if context is at item level\n */\nexport function isItemContext(context) {\n return context.level === \"item\";\n}\n/**\n * Type guard to check if context is at passage level\n */\nexport function isPassageContext(context) {\n return context.level === \"passage\";\n}\n/**\n * Type guard to check if context is at rubric level\n */\nexport function isRubricContext(context) {\n return context.level === \"rubric\";\n}\n/**\n * Type guard to check if context is at element level\n */\nexport function isElementContext(context) {\n return context.level === \"element\";\n}\nconst stripHtml = (value) => value.replace(/<[^>]*>/g, \" \").trim();\n/**\n * A config's `models` as a list, whether it was authored as an array or as a\n * record keyed by element id. Both forms are in the wild.\n */\nfunction normalizeModels(modelsRaw) {\n if (Array.isArray(modelsRaw))\n return modelsRaw;\n if (modelsRaw && typeof modelsRaw === \"object\") {\n return Object.values(modelsRaw);\n }\n return [];\n}\n/**\n * Push every string a model carries, one level into its arrays of objects.\n *\n * The depth is deliberate rather than a full walk: math and prose live in a\n * model's own fields (`prompt`, `label`) and in its choice/row arrays, which is\n * one level down. Recursing further would pull in ids, keys and config flags.\n */\nfunction collectModelText(model, push) {\n if (!model || typeof model !== \"object\")\n return;\n for (const value of Object.values(model)) {\n if (typeof value === \"string\")\n push(value);\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (entry && typeof entry === \"object\") {\n for (const nested of Object.values(entry)) {\n if (typeof nested === \"string\")\n push(nested);\n }\n }\n }\n }\n }\n}\n/** Push the markup of every element snippet in a config's `elements` map. */\nfunction collectElementsText(elements, push) {\n if (!elements || typeof elements !== \"object\")\n return;\n for (const elementMarkup of Object.values(elements)) {\n if (typeof elementMarkup === \"string\")\n push(elementMarkup);\n }\n}\n/**\n * The authored content a context carries, for the content heuristics below.\n *\n * Each level differs only in which fields it reads: an element reads its own\n * markup snippet and the one model bearing its id, an item and a passage read\n * their whole config and every model. The traversal itself is shared, so a new\n * place content can hide is added once.\n *\n * `transform` decides what the caller gets. {@link extractTextContent} strips\n * tags, which is right for prose keyword matching and wrong for structural\n * matching: a MathML item's only math signal *is* the `<math>` tag, and stripping\n * first left `hasMathContent`'s MathML pattern unreachable.\n */\nfunction extractContent(context, transform) {\n const textChunks = [];\n const push = (text) => {\n textChunks.push(transform(text));\n };\n const joined = () => textChunks.filter(Boolean).join(\" \").trim();\n if (isElementContext(context)) {\n const config = context.item.config;\n if (!config)\n return \"\";\n const elementMarkup = config.elements?.[context.elementId];\n if (typeof elementMarkup === \"string\")\n push(elementMarkup);\n // Model data keyed by this element id: in many items the math is in\n // `model.prompt`/labels rather than in `elements[elementId]`.\n const model = normalizeModels(config.models).find((candidate) => !!candidate &&\n typeof candidate === \"object\" &&\n candidate.id === context.elementId);\n collectModelText(model, push);\n return joined();\n }\n if (isItemContext(context)) {\n const config = context.item?.config;\n if (!config)\n return \"\";\n if (typeof config.markup === \"string\")\n push(config.markup);\n collectElementsText(config.elements, push);\n for (const model of normalizeModels(config.models)) {\n collectModelText(model, push);\n }\n return joined();\n }\n if (isPassageContext(context)) {\n const config = context.passage?.config;\n if (!config)\n return \"\";\n for (const field of [\"markup\", \"content\", \"prompt\"]) {\n const value = config[field];\n if (typeof value === \"string\")\n push(value);\n }\n collectElementsText(config.elements, push);\n for (const model of normalizeModels(config.models)) {\n collectModelText(model, push);\n }\n return joined();\n }\n if (isRubricContext(context)) {\n // No model walk: a rubric block is authored prose, so its text is one\n // string — the embedded passage's markup when it has one, else its content.\n const rubric = context.rubricBlock;\n if (rubric.passage?.config) {\n return transform(rubric.passage.config.markup || \"\");\n }\n return transform(rubric.content || \"\");\n }\n return \"\";\n}\n/** The plain text a context carries, tags removed. */\nexport function extractTextContent(context) {\n return extractContent(context, stripHtml);\n}\n/**\n * The authored markup a context carries, tags intact.\n *\n * For indicators that live in the markup rather than in the prose — `<math>`\n * above all, whose whole signal is the element name.\n */\nexport function extractMarkupContent(context) {\n return extractContent(context, (value) => value);\n}\n/**\n * Helper to check if context contains mathematical content\n * (Basic heuristic - can be overridden by tools)\n */\n/**\n * Chemical element symbols.\n *\n * A real set rather than `[A-Z][a-z]?`: that shape matches \"It\", \"In\", \"He\" and\n * \"A\", which is why the science gate used to answer `true` for any prose that\n * began a sentence.\n */\nconst ELEMENT_SYMBOLS = new Set([\n \"H\", \"He\", \"Li\", \"Be\", \"B\", \"C\", \"N\", \"O\", \"F\", \"Ne\", \"Na\", \"Mg\", \"Al\", \"Si\",\n \"P\", \"S\", \"Cl\", \"Ar\", \"K\", \"Ca\", \"Sc\", \"Ti\", \"V\", \"Cr\", \"Mn\", \"Fe\", \"Co\",\n \"Ni\", \"Cu\", \"Zn\", \"Ga\", \"Ge\", \"As\", \"Se\", \"Br\", \"Kr\", \"Rb\", \"Sr\", \"Y\", \"Zr\",\n \"Nb\", \"Mo\", \"Tc\", \"Ru\", \"Rh\", \"Pd\", \"Ag\", \"Cd\", \"In\", \"Sn\", \"Sb\", \"Te\", \"I\",\n \"Xe\", \"Cs\", \"Ba\", \"La\", \"Ce\", \"Pr\", \"Nd\", \"Pm\", \"Sm\", \"Eu\", \"Gd\", \"Tb\", \"Dy\",\n \"Ho\", \"Er\", \"Tm\", \"Yb\", \"Lu\", \"Hf\", \"Ta\", \"W\", \"Re\", \"Os\", \"Ir\", \"Pt\", \"Au\",\n \"Hg\", \"Tl\", \"Pb\", \"Bi\", \"Po\", \"At\", \"Rn\", \"Fr\", \"Ra\", \"Ac\", \"Th\", \"Pa\", \"U\",\n \"Np\", \"Pu\", \"Am\", \"Cm\", \"Bk\", \"Cf\", \"Es\", \"Fm\", \"Md\", \"No\", \"Lr\",\n]);\n/** A word that could be a formula: capitalised groups with optional counts. */\nconst FORMULA_CANDIDATE = /\\b[A-Z][A-Za-z]*\\d*(?:[A-Z][A-Za-z]*\\d*)*\\b/g;\nconst FORMULA_GROUP = /([A-Z][a-z]?)(\\d*)/g;\n/**\n * Whether the text contains something only a chemical formula looks like.\n *\n * A token qualifies when every one of its groups is a real element symbol *and*\n * it either names two or more of them or carries a count — `NaCl`, `CO2`, `H2O`,\n * `C6H12O6`. A lone symbol never qualifies: \"In\", \"He\", \"As\" and \"At\" are\n * ordinary English words, and a single-letter \"I\" or \"A\" more so.\n */\nfunction hasChemicalFormula(text) {\n for (const candidate of text.match(FORMULA_CANDIDATE) ?? []) {\n FORMULA_GROUP.lastIndex = 0;\n let groups = 0;\n let hasCount = false;\n let consumed = 0;\n let valid = true;\n let match = FORMULA_GROUP.exec(candidate);\n while (match !== null) {\n if (match[0] === \"\")\n break;\n if (!ELEMENT_SYMBOLS.has(match[1])) {\n valid = false;\n break;\n }\n groups += 1;\n if (match[2])\n hasCount = true;\n consumed += match[0].length;\n match = FORMULA_GROUP.exec(candidate);\n }\n // Every character has to belong to a group, or the token was only\n // formula-shaped at its start (\"Hello\" -> \"He\" + \"llo\").\n if (valid && consumed === candidate.length && (groups > 1 || hasCount)) {\n return true;\n }\n }\n return false;\n}\nexport function hasMathContent(context) {\n // Structural signals live in the markup: stripping tags first is what left the\n // MathML pattern unable to match anything at all.\n const markup = extractMarkupContent(context);\n const structuralIndicators = [\n /<math[>\\s]/i, // MathML\n /\\\\\\[([^\\]]+)\\\\\\]/, // LaTeX display math\n /\\$\\$[^$]+\\$\\$/, // LaTeX display math ($$...$$)\n /\\\\\\(/, // LaTeX inline math\n ];\n if (structuralIndicators.some((pattern) => pattern.test(markup)))\n return true;\n const text = extractTextContent(context);\n // No bare-operator pattern. `/[+\\-*/=<>≤≥∑∫√π]/` matched any hyphen or slash,\n // so \"well-known\" and \"and/or\" made every item mathematical and this predicate\n // answered `true` for essentially all content — a gate that does not gate. An\n // operator counts only with operands around it, or when the character has no\n // prose reading at all.\n const textIndicators = [\n /[≤≥≠±×÷∑∫√∞π]/, // Symbols with no prose reading\n /\\d+\\s*[+\\-*/×÷=]\\s*\\d+/, // Simple arithmetic\n /\\d\\s*[<>]\\s*\\d/, // Numeric comparison\n /\\b\\d+\\s*\\/\\s*\\d+\\b/, // Fractions\n /\\b\\d+(?:\\.\\d+)?\\s*%/, // Percentages\n /\\^\\s*\\d/, // Exponents\n ];\n return textIndicators.some((pattern) => pattern.test(text));\n}\n/**\n * Helper to check if context contains choice-based interactions\n */\nexport function hasChoiceInteraction(context) {\n const interactionTypes = [\n \"pie-multiple-choice\",\n \"pie-inline-choice\",\n \"pie-select-text\",\n \"pie-ebsr\",\n \"multiple-choice\",\n \"inline-choice\",\n \"select-text\",\n \"ebsr\",\n ];\n if (isElementContext(context)) {\n const config = context.item.config;\n if (!config?.models)\n return false;\n // Find model for this element\n const models = Array.isArray(config.models)\n ? config.models\n : Object.values(config.models);\n const model = models.find((m) => m && typeof m === \"object\" && m.id === context.elementId);\n if (!model)\n return false;\n const type = model.element || \"\";\n return interactionTypes.includes(type);\n }\n if (isItemContext(context)) {\n const modelsRaw = context.item.config?.models;\n const models = Array.isArray(modelsRaw)\n ? modelsRaw\n : modelsRaw && typeof modelsRaw === \"object\"\n ? Object.values(modelsRaw)\n : [];\n return models.some((m) => {\n if (!m || typeof m !== \"object\")\n return false;\n const type = m.element || \"\";\n // A model that names its element has answered the question, whichever way\n // the answer falls. `choices` is carried by interactions that are not\n // choice interactions at all — `placement-ordering`, `categorize` and\n // `drag-in-the-blank` each hold their draggables there — so reading it on\n // a named model showed the answer eliminator on items where the tool does\n // nothing. The heuristic remains for configs that name no element.\n if (type)\n return interactionTypes.includes(type);\n return Array.isArray(m.choices) && m.choices.length > 0;\n });\n }\n return false;\n}\n/**\n * Helper to check if context contains text that can be read aloud\n */\nexport function hasReadableText(context) {\n const text = extractTextContent(context);\n // Must have at least 10 characters of text (arbitrary threshold)\n return text.trim().length >= 10;\n}\n/**\n * Helper to check if context contains science content\n * (Basic heuristic - can be overridden by tools)\n */\nexport function hasScienceContent(context) {\n const text = extractTextContent(context);\n // The element-symbol pattern used to be `/\\b[A-Z][a-z]?\\d*\\b/`, which matches\n // any one- or two-letter capitalised word: \"It\", \"In\", \"A\", \"No\". Every item\n // beginning a sentence with one read as science.\n if (hasChemicalFormula(text))\n return true;\n if (/[A-Z][a-z]?[\\u2080-\\u2089]/.test(text))\n return true; // Subscripted: H₂O, CO₂\n const scienceIndicators = [\n /chemistry|chemical|molecule|compound|periodic\\s+table/i,\n /\\bchemical\\s+element\\b|\\belement\\s+symbol\\b/i,\n /biology|organism|\\bDNA\\b|\\bRNA\\b|protein|photosynthesis|ecosystem/i,\n /physics|\\bforce\\b|\\benergy\\b|velocity|acceleration|momentum/i,\n ];\n return scienceIndicators.some((pattern) => pattern.test(text));\n}\n","import { validateCustomElementTag } from \"@pie-players/pie-players-shared/pie/tag-names\";\n/**\n * Resolve the element tag for a tool from the overrides in play.\n *\n * There is no built-in map to fall back to. One lived here, naming eleven\n * capabilities, and a core module holding that catalogue is why a host could not\n * add a twelfth without editing this package — the map was overridable, but the\n * default was core-resident. The packaged map is `PACKAGED_TOOL_TAG_MAP` in\n * `@pie-players/pie-default-tool-loaders`, installed onto a registry through\n * `ToolRegistry.setComponentOverrides`.\n *\n * An unmapped toolId falls through to itself, which is only a valid tag if the\n * host's tool id already looks like one. Every packaged id is a single camelCase\n * word, so in practice an unmapped packaged tool throws here rather than\n * rendering a bogus element — the failure names the missing mapping, because\n * \"custom element names must include a hyphen\" is a true statement about the\n * wrong thing.\n */\nexport const resolveToolTag = (toolId, overrides) => {\n const mapped = overrides?.toolTagMap?.[toolId];\n if (mapped === undefined && !toolId.includes(\"-\")) {\n throw new Error(`No element tag is mapped for tool \"${toolId}\". Install a tag map on the registry via setComponentOverrides({ toolTagMap }) — for the packaged capabilities, PACKAGED_TOOL_TAG_MAP from \"@pie-players/pie-default-tool-loaders\".`);\n }\n return validateCustomElementTag(mapped ?? toolId, `tool component tag for \"${toolId}\"`);\n};\nconst createDefaultToolElement = (tagName) => document.createElement(tagName);\nexport const createToolElement = (toolId, context, toolbarContext, overrides) => {\n const tagName = resolveToolTag(toolId, overrides);\n const factoryForTool = overrides?.toolComponentFactories?.[toolId];\n const factory = factoryForTool ?? overrides?.toolComponentFactory;\n return factory\n ? factory({ toolId, tagName, context, toolbarContext })\n : createDefaultToolElement(tagName);\n};\nexport const toToolIdFromTag = (tagName, overrides) => {\n const validTag = validateCustomElementTag(tagName, \"tool component tag\");\n const map = overrides?.toolTagMap ?? {};\n return Object.entries(map).find(([, tag]) => tag === validTag)?.[0];\n};\n","/** Desmos calculator adapter for the generic tool-provider registry. */\nimport { LazyCalculatorToolProvider, } from \"./LazyCalculatorToolProvider.js\";\nexport class DesmosToolProvider extends LazyCalculatorToolProvider {\n providerId = \"desmos-calculator\";\n providerName = \"Desmos Calculator\";\n version = \"1.12\";\n requiresAuth = true;\n getDefinition() {\n return {\n backend: \"desmos\",\n moduleImportOperation: \"desmos-provider-module-import\",\n loadProvider: async () => {\n const module = await import(\"@pie-players/pie-calculator-desmos\");\n return module.DesmosCalculatorProvider;\n },\n initializationErrorMessage: \"Failed to initialize Desmos calculator provider. Check the application key, preloaded API, runtime endpoint, or network access.\",\n };\n }\n getCapabilities() {\n return {\n supportsOffline: false,\n requiresAuth: true,\n maxInstances: null,\n features: {\n basic: true,\n scientific: true,\n graphing: true,\n fourFunction: true,\n },\n };\n }\n}\n","/**\n * TTS Tool Provider\n *\n * Unified provider for all TTS backends:\n * - Browser Web Speech API (no auth)\n * - AWS Polly (requires auth via server proxy)\n * - Google Cloud TTS (requires auth via server proxy)\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { BrowserTTSProvider } from \"../../services/tts/browser-provider.js\";\n/**\n * TTS Tool Provider\n *\n * Wraps TTS providers (Browser, Polly, Google) with the ToolProviderApi interface\n * for use in the ToolProviderRegistry.\n *\n * @example Browser TTS (no auth)\n * ```typescript\n * const provider = new TTSToolProvider();\n * await provider.initialize({ backend: 'browser' });\n * const ttsProvider = await provider.createInstance();\n * ```\n *\n * @example Server TTS (with auth)\n * ```typescript\n * const provider = new TTSToolProvider();\n * await provider.initialize({\n * backend: 'polly',\n * apiEndpoint: '/api/tts/synthesize',\n * authToken: 'bearer-token', // Fetched via authFetcher\n * });\n * const ttsProvider = await provider.createInstance();\n * ```\n */\nexport class TTSToolProvider {\n providerId = \"tts-service\";\n providerName = \"Text-to-Speech\";\n category = \"tts\";\n version = \"1.0\";\n requiresAuth;\n ttsProvider = null;\n config = null;\n async emitTelemetry(eventName, payload) {\n try {\n await this.config?.onTelemetry?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[TTSToolProvider] telemetry callback failed:\", error);\n }\n }\n /**\n * Create TTS tool provider\n *\n * @param backend TTS backend to use (default: 'browser')\n */\n constructor(backend = \"browser\") {\n this.requiresAuth = backend !== \"browser\";\n }\n /**\n * Initialize TTS provider\n *\n * Sets up the appropriate TTS backend.\n *\n * @param config Configuration with backend type and credentials\n * @throws Error if initialization fails or required config missing\n */\n async initialize(config) {\n if (this.ttsProvider) {\n console.warn(\"[TTSToolProvider] Already initialized, skipping reinitialization\");\n return;\n }\n this.config = config;\n switch (config.backend) {\n case \"browser\":\n await this._initializeBrowserTTS(config);\n break;\n case \"polly\":\n case \"google\":\n case \"server\":\n await this._initializeServerTTS(config);\n break;\n default:\n throw new Error(`[TTSToolProvider] Unknown backend: ${config.backend}`);\n }\n console.log(`[TTSToolProvider] Initialized successfully (backend: ${config.backend})`);\n }\n /**\n * Initialize browser TTS (Web Speech API)\n */\n async _initializeBrowserTTS(config) {\n // Check if Web Speech API is available\n if (typeof window === \"undefined\" || !(\"speechSynthesis\" in window)) {\n throw new Error(\"[TTSToolProvider] Browser TTS not supported (Web Speech API not available)\");\n }\n this.ttsProvider = new BrowserTTSProvider();\n console.log(\"[TTSToolProvider] Browser TTS initialized (Web Speech API)\");\n }\n /**\n * Initialize server-based TTS (Polly, Google)\n */\n async _initializeServerTTS(config) {\n if (!config.apiEndpoint) {\n throw new Error(\"[TTSToolProvider] apiEndpoint required for server-based TTS backends\");\n }\n // Server backends are optional; load implementation only when requested.\n const moduleLoadStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-library-load-start\", {\n toolId: \"textToSpeech\",\n operation: \"server-provider-module-import\",\n backend: config.serverProvider || config.backend,\n });\n const serverModule = await (async () => {\n try {\n const loaded = (await import(\"@pie-players/tts-client-server\"));\n await this.emitTelemetry(\"pie-tool-library-load-success\", {\n toolId: \"textToSpeech\",\n operation: \"server-provider-module-import\",\n backend: config.serverProvider || config.backend,\n duration: Date.now() - moduleLoadStartedAt,\n });\n return loaded;\n }\n catch (error) {\n await this.emitTelemetry(\"pie-tool-library-load-error\", {\n toolId: \"textToSpeech\",\n operation: \"server-provider-module-import\",\n backend: config.serverProvider || config.backend,\n duration: Date.now() - moduleLoadStartedAt,\n errorType: \"ToolLibraryLoadError\",\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n })();\n this.ttsProvider = new serverModule.ServerTTSProvider();\n console.log(`[TTSToolProvider] Server TTS initialized (provider: ${config.serverProvider || config.backend})`);\n }\n /**\n * Create a TTS provider instance\n *\n * Returns the initialized TTS provider.\n *\n * @param config Optional instance-specific configuration (currently unused)\n * @returns TTS provider\n * @throws Error if provider not initialized\n */\n async createInstance(config) {\n if (!this.ttsProvider) {\n throw new Error(\"[TTSToolProvider] Provider not initialized. Call initialize() first.\");\n }\n return this.ttsProvider;\n }\n /**\n * Get provider capabilities\n *\n * @returns TTS capabilities based on backend\n */\n getCapabilities() {\n const isBrowser = this.config?.backend === \"browser\";\n return {\n supportsOffline: isBrowser,\n requiresAuth: !isBrowser,\n maxInstances: 1, // Single TTS instance (playback is sequential)\n features: {\n wordBoundary: true, // All backends support word highlighting\n pause: true,\n resume: true,\n rateControl: true,\n pitchControl: isBrowser, // Only browser supports pitch\n voiceSelection: true,\n },\n };\n }\n /**\n * Check if provider is ready\n *\n * @returns true if provider is initialized\n */\n isReady() {\n return this.ttsProvider !== null;\n }\n /**\n * Clean up provider resources\n *\n * Destroys the TTS provider and releases resources.\n */\n destroy() {\n if (this.ttsProvider) {\n this.ttsProvider.destroy();\n this.ttsProvider = null;\n }\n this.config = null;\n console.log(\"[TTSToolProvider] Destroyed\");\n }\n}\n","/**\n * Calculator Tool Registration\n *\n * Registers the calculator tool with support for multiple calculator types\n * (basic, scientific, graphing) through a host-selected provider.\n *\n * Maps to QTI 3.0 standard access features:\n * - calculator (cognitive support)\n * - graphingCalculator (assessment tool)\n */\nimport { hasMathContent } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { createScopedToolId } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { DesmosToolProvider } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { CortexToolProvider } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { GeoGebraToolProvider } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { createToolElement } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nexport const DEFAULT_CALCULATOR_PROVIDER_ID = \"calculator-desmos\";\nexport function resolveCalculatorProviderId(config) {\n const configured = config?.provider?.id;\n if (configured === undefined || configured === \"\") {\n return DEFAULT_CALCULATOR_PROVIDER_ID;\n }\n if (configured === \"calculator-desmos\" ||\n configured === \"calculator-geogebra\" ||\n configured === \"calculator-cortex\") {\n return configured;\n }\n throw new Error(`Unsupported calculator provider \"${String(configured)}\". Expected \"calculator-desmos\", \"calculator-geogebra\", or \"calculator-cortex\".`);\n}\nfunction createCalculatorToolProvider(config) {\n switch (resolveCalculatorProviderId(config)) {\n case \"calculator-cortex\":\n return new CortexToolProvider();\n case \"calculator-geogebra\":\n return new GeoGebraToolProvider();\n default:\n return new DesmosToolProvider();\n }\n}\nfunction getCalculatorInstanceConfig(config) {\n const theme = config?.theme;\n return {\n settings: config?.settings && typeof config.settings === \"object\"\n ? { ...config.settings }\n : {},\n restrictedMode: config?.restrictedMode === true,\n locale: typeof config?.locale === \"string\" ? config.locale : undefined,\n theme: theme === \"light\" || theme === \"dark\" || theme === \"auto\"\n ? theme\n : undefined,\n };\n}\n// The toolbar parent re-derives `renderedTools` whenever item state changes\n// (e.g. the learner answers a question and `effectiveItem`/`renderContext`\n// recompute). Calculator initialization is expensive (Desmos boot, container\n// mount), so we cache the overlay element by coordinator + scoped tool id.\n// Reusing the same element keeps `mountContent` a no-op and avoids tearing\n// down and re-initializing the calculator on every re-render.\nconst overlayElementCache = new WeakMap();\nfunction getCachedOverlay(coordinator, fullToolId) {\n if (!coordinator)\n return null;\n const scoped = overlayElementCache.get(coordinator);\n const element = scoped?.get(fullToolId);\n if (!element)\n return null;\n // Svelte custom elements destroy their component when disconnected.\n // A detached cached element is a dead instance — drop it and recreate.\n if (!element.isConnected) {\n scoped?.delete(fullToolId);\n return null;\n }\n return element;\n}\nfunction setCachedOverlay(coordinator, fullToolId, element) {\n if (!coordinator)\n return;\n let scoped = overlayElementCache.get(coordinator);\n if (!scoped) {\n scoped = new Map();\n overlayElementCache.set(coordinator, scoped);\n }\n scoped.set(fullToolId, element);\n}\nfunction normalizeCalculatorType(value) {\n return value === \"basic\" || value === \"scientific\" || value === \"graphing\"\n ? value\n : null;\n}\nfunction getCalculatorRenderParams(toolbarContext) {\n const params = toolbarContext.getToolRenderParams?.(\"calculator\") ?? {};\n const calculatorType = normalizeCalculatorType(params.calculatorType);\n const availableTypesRaw = params.availableTypes;\n const availableTypes = Array.isArray(availableTypesRaw)\n ? availableTypesRaw\n .map((value) => normalizeCalculatorType(value))\n .filter((value) => value !== null)\n : calculatorType\n ? [calculatorType]\n : null;\n return {\n calculatorType,\n availableTypes,\n displayName: toolbarContext.i18n.t(CALCULATOR_NAME_KEYS[calculatorType ?? \"untyped\"]),\n };\n}\n/**\n * The calculator's displayed name, per host-declared type.\n *\n * `untyped` keeps the pre-adoption behaviour of naming the scientific\n * calculator, which is what the toolbar has always announced when the host\n * declares no type.\n */\nconst CALCULATOR_NAME_KEYS = {\n basic: \"tools.calculator.nameBasic\",\n scientific: \"tools.calculator.nameScientific\",\n graphing: \"tools.calculator.nameGraphing\",\n untyped: \"tools.calculator.name\",\n};\nfunction applyCalculatorParamsToElement(element, calculatorType, availableTypes, providerId, calculatorConfig) {\n const calculatorElement = element;\n calculatorElement.providerId = providerId;\n calculatorElement.calculatorConfig = calculatorConfig;\n element.setAttribute(\"provider-id\", providerId);\n if (calculatorType) {\n calculatorElement.calculatorType = calculatorType;\n element.setAttribute(\"calculator-type\", calculatorType);\n }\n else {\n delete calculatorElement.calculatorType;\n element.removeAttribute(\"calculator-type\");\n }\n if (availableTypes && availableTypes.length > 0) {\n calculatorElement.availableTypes = availableTypes;\n }\n else {\n delete calculatorElement.availableTypes;\n }\n}\n/**\n * Calculator tool registration\n *\n * Supports:\n * - Basic, scientific, and graphing calculators through Desmos, GeoGebra, or Cortex\n * - Context-aware visibility (shows only when math content is detected)\n * - Item level only\n */\nexport const calculatorToolRegistration = {\n toolId: \"calculator\",\n name: \"Calculator\",\n description: \"Multi-type calculator (basic, scientific, graphing)\",\n nameKey: \"tools.calculator.name\",\n descriptionKey: \"tools.calculator.description\",\n icon: \"calculator\",\n provider: {\n getProviderId: resolveCalculatorProviderId,\n createProvider: createCalculatorToolProvider,\n getInitConfig: (config) => config?.provider?.init ?? {},\n getAuthFetcher: (config) => {\n const runtimeAuthFetcher = config?.provider?.runtime?.authFetcher;\n return typeof runtimeAuthFetcher === \"function\"\n ? runtimeAuthFetcher\n : undefined;\n },\n lazy: true,\n },\n // Calculator is item-level in this player architecture.\n supportedLevels: [\"item\"],\n // PNP support IDs that enable this tool\n // Maps to QTI 3.0 standard features: calculator, graphingCalculator\n // A type is not a feature id: `calculatorType` arrives through the host's\n // render params, so `basicCalculator` / `scientificCalculator` granted the\n // same untyped calculator these two do and only looked like they selected a\n // variant.\n pnpSupportIds: [\n \"calculator\", // QTI 3.0 standard (cognitive.calculator)\n \"graphingCalculator\", // QTI 3.0 standard (assessment.graphingCalculator)\n ],\n /**\n * Pass 2: Determine if calculator is relevant in this context\n *\n * Calculator is relevant when context contains mathematical content\n * (MathML, LaTeX, arithmetic markers).\n */\n isVisibleInContext(context) {\n // Show only when math is present in item content.\n return hasMathContent(context);\n },\n renderToolbar(context, toolbarContext) {\n const { calculatorType, availableTypes, displayName } = getCalculatorRenderParams(toolbarContext);\n const calculatorToolConfig = toolbarContext.toolkitCoordinator?.config.tools?.providers?.calculator;\n const providerId = resolveCalculatorProviderId(calculatorToolConfig);\n const calculatorConfig = getCalculatorInstanceConfig(calculatorToolConfig);\n const fullToolId = createScopedToolId(this.toolId, toolbarContext.scope.level, toolbarContext.scope.scopeId);\n const componentOverrides = toolbarContext.componentOverrides;\n const cachedOverlay = getCachedOverlay(toolbarContext.toolCoordinator, fullToolId);\n const overlay = (cachedOverlay ??\n createToolElement(this.toolId, context, toolbarContext, componentOverrides));\n if (!cachedOverlay) {\n setCachedOverlay(toolbarContext.toolCoordinator, fullToolId, overlay);\n }\n overlay.setAttribute(\"tool-id\", fullToolId);\n overlay.toolkitCoordinator = toolbarContext.toolkitCoordinator;\n applyCalculatorParamsToElement(overlay, calculatorType, availableTypes, providerId, calculatorConfig);\n const button = {\n toolId: this.toolId,\n label: displayName,\n icon: typeof this.icon === \"function\" ? this.icon(context) : this.icon,\n // Routes this button through <nds-icon-button> where the host enables NDS\n // icons. Declared here because which capabilities render in the host's\n // design system is a composition decision; the toolbar used to map it from\n // the `calculator` toolId, which put a capability name in the generic core.\n faIconName: \"calculator\",\n disabled: false,\n // The name stays put across open and closed. The toolbar mirrors\n // `active` onto the button as `aria-pressed`, so the state is already\n // exposed; a name that also swapped to \"Close …\" would contradict it.\n ariaLabel: displayName,\n tooltip: displayName,\n onClick: () => toolbarContext.toggleTool(this.toolId),\n active: toolbarContext.isToolVisible(fullToolId),\n };\n let lastVisibleState = button.active;\n if (overlay.visible !== button.active) {\n overlay.visible = button.active;\n }\n return {\n toolId: this.toolId,\n elements: [\n {\n element: overlay,\n mount: \"after-buttons\",\n shell: {\n // The variant name the button already carries — \"Basic Calculator\",\n // not the registration's generic one.\n title: displayName,\n draggable: true,\n resizable: true,\n closeable: true,\n /*\n * Sized per type from what each layout measures, rather than one\n * size for all three. A shell subtracts ~74px of header from the\n * height it is given, and the numbers below are the content each\n * type needs plus room for its history tape:\n *\n * - basic: strip, display, edit row and a four-row keypad measure\n * 398px. 560 left ~90px of blank above the entry line, which is\n * the gap that made the panel look mis-sized.\n * - scientific: the same plus a keypad layer tab row.\n * - graphing: the expression rail beside the plot, whose column\n * wants 486px on its own — viewport controls, a 14rem board floor\n * and the readout that *is* the graph for assistive technology,\n * since the board itself is `aria-hidden`. At 620 that column was\n * 12px short and the readout's last line was cut off.\n *\n * The minimums stay shared across types and providers. This\n * registration serves Desmos, GeoGebra and Cortex alike, so a\n * graphing-only floor would move the resize limit under two vendors\n * whose layouts were never measured for it. Cortex below 42rem\n * stacks the rail above the plot and needs 701px there, which no\n * spacing tier closes — it scrolls its own content instead of\n * clipping it, which is the contract every size below the opening\n * one already relies on.\n */\n initialWidth: calculatorType === \"graphing\" ? 720 : 380,\n initialHeight: calculatorType === \"graphing\"\n ? 660\n : calculatorType === \"basic\"\n ? 500\n : 560,\n minWidth: 380,\n minHeight: 480,\n /*\n * `bottom-right` put a 560-620px-tall shell over the items\n * column it shares the viewport with — tall enough, at\n * ordinary viewport heights, to sit on top of a sibling\n * item's own toolbar row and block its button from mouse\n * and touch input. `bottom-left` keeps the same footprint\n * over the passage column instead, which carries no\n * per-item controls to collide with.\n */\n initialAlign: \"bottom-left\",\n initialMargin: 16,\n // Header controls in the host's design system, and the layout that\n // goes with them.\n ndsHeaderControls: true,\n // A learner reads the question while using the calculator, so Tab and\n // Shift+Tab cross between the page and the shell instead of cycling\n // inside it.\n pageTabOrder: true,\n content: {\n overflowY: \"auto\",\n preserveMinHeight: true,\n },\n },\n },\n ],\n button,\n sync: () => {\n const active = toolbarContext.isToolVisible(fullToolId);\n button.active = active;\n button.label = displayName;\n // Static across the toggle. The previous `Close ${name.toLowerCase()}`\n // was a hardcoded English template built by lowercasing a localized\n // noun — \"Close rekenmachine\" under nl-NL — and it is the state\n // `aria-pressed` already carries.\n button.ariaLabel = displayName;\n button.tooltip = displayName;\n if (lastVisibleState !== active) {\n overlay.visible = active;\n lastVisibleState = active;\n }\n if (overlay.toolkitCoordinator !== toolbarContext.toolkitCoordinator) {\n overlay.toolkitCoordinator = toolbarContext.toolkitCoordinator;\n }\n applyCalculatorParamsToElement(overlay, calculatorType, availableTypes, providerId, calculatorConfig);\n },\n subscribeActive: (callback) => {\n if (!toolbarContext.subscribeVisibility)\n return () => { };\n return toolbarContext.subscribeVisibility(() => {\n callback(toolbarContext.isToolVisible(fullToolId));\n });\n },\n };\n },\n};\n","/**\n * Text-to-Speech (TTS) Tool Registration\n *\n * Registers the TTS tool for reading content aloud.\n *\n * Maps to QTI 3.0 standard access features:\n * - textToSpeech (auditory support)\n * - readAloud (auditory support)\n */\nimport { hasReadableText } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { createScopedToolId } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { buildRuntimeTTSConfig, normalizeTTSLayoutMode, normalizeTTSSpeedControlOptions, resolveTTSHostToolbarLayout, resolveTTSLayoutMode, resolveTTSBackend, resolveTTSRuntimeSettings, resolveRuntimeProvider, resolveTransportMode, } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nimport { TTSToolProvider } from \"@pie-players/pie-assessment-toolkit/tools/internal\";\nconst inlineTTSControls = new Map();\nexport const TOOL_ELEMENT_UNMOUNT_CALLBACK_PROP = \"__pieToolElementUnmount\";\nexport const TOOL_ACTIVE_CHANGE_EVENT = \"pie-tool-active-change\";\n/**\n * Text-to-Speech tool registration\n *\n * Supports:\n * - Reading content aloud using browser TTS or external providers\n * - Context-aware visibility (shows when readable text is available)\n * - All levels except assessment and element\n */\nexport const ttsToolRegistration = {\n toolId: \"textToSpeech\",\n name: \"Text to Speech\",\n description: \"Read content aloud\",\n nameKey: \"tools.textToSpeech.name\",\n descriptionKey: \"tools.textToSpeech.description\",\n icon: \"volume-up\",\n provider: {\n getProviderId: () => \"tts\",\n createProvider: (config) => {\n const settings = resolveTTSRuntimeSettings(config);\n return new TTSToolProvider(resolveTTSBackend(settings));\n },\n getInitConfig: (config) => {\n const settings = resolveTTSRuntimeSettings(config);\n const backend = resolveTTSBackend(settings);\n const serverProvider = resolveRuntimeProvider(settings, backend);\n const transportMode = resolveTransportMode(settings, serverProvider);\n return {\n backend,\n serverProvider,\n transportMode,\n ...buildRuntimeTTSConfig(settings),\n };\n },\n getAuthFetcher: (config) => {\n const runtimeAuthFetcher = config?.provider?.runtime?.authFetcher;\n return typeof runtimeAuthFetcher === \"function\"\n ? runtimeAuthFetcher\n : undefined;\n },\n sanitizeConfig: (config) => {\n const settings = config.settings && typeof config.settings === \"object\"\n ? { ...config.settings }\n : undefined;\n if (settings && \"layoutMode\" in settings) {\n settings.layoutMode = normalizeTTSLayoutMode(settings.layoutMode);\n }\n if (settings && \"speedOptions\" in settings) {\n settings.speedOptions = normalizeTTSSpeedControlOptions(settings.speedOptions);\n }\n const normalizedConfig = {\n ...config,\n };\n if (\"layoutMode\" in normalizedConfig) {\n normalizedConfig.layoutMode = normalizeTTSLayoutMode(normalizedConfig.layoutMode);\n }\n if (\"speedOptions\" in normalizedConfig) {\n normalizedConfig.speedOptions = normalizeTTSSpeedControlOptions(normalizedConfig.speedOptions);\n }\n if (settings) {\n normalizedConfig.settings = settings;\n }\n return normalizedConfig;\n },\n lazy: true,\n },\n // TTS is inline-only and scoped to item/passage contexts.\n supportedLevels: [\"item\", \"passage\"],\n // PNP support IDs that enable this tool\n // Maps to QTI 3.0 standard features: textToSpeech, readAloud\n pnpSupportIds: [\n \"textToSpeech\", // QTI 3.0 standard (auditory.textToSpeech)\n \"readAloud\", // QTI 3.0 standard (auditory.readAloud)\n ],\n /**\n * Pass 2: Determine if TTS is relevant in this context\n *\n * TTS is relevant when:\n * - Context contains readable text (at least 10 characters)\n */\n isVisibleInContext(context) {\n return hasReadableText(context);\n },\n renderToolbar(_context, toolbarContext) {\n const resolveRuntimeSettings = () => resolveTTSRuntimeSettings(toolbarContext.toolkitCoordinator?.getToolConfig(this.toolId) ||\n undefined);\n const resolveElementSpeedOptions = () => {\n const runtimeSettings = resolveRuntimeSettings();\n return normalizeTTSSpeedControlOptions(runtimeSettings.speedOptions);\n };\n const resolveLayoutMode = () => resolveTTSLayoutMode(resolveRuntimeSettings());\n const resolveHostLayout = () => resolveTTSHostToolbarLayout(resolveRuntimeSettings());\n const fullToolId = createScopedToolId(this.toolId, toolbarContext.scope.level, toolbarContext.scope.scopeId);\n const resolveControlSize = () => {\n const raw = toolbarContext.ui?.size;\n return raw === \"sm\" || raw === \"lg\" ? raw : \"md\";\n };\n const ensureElement = () => {\n let element = inlineTTSControls.get(fullToolId);\n if (element &&\n typeof element.isConnected ===\n \"boolean\" &&\n !element.isConnected) {\n inlineTTSControls.delete(fullToolId);\n element = undefined;\n }\n if (!element) {\n element = document.createElement(\"pie-tool-tts-inline\");\n element[TOOL_ELEMENT_UNMOUNT_CALLBACK_PROP] = () => {\n if (inlineTTSControls.get(fullToolId) === element) {\n inlineTTSControls.delete(fullToolId);\n }\n };\n inlineTTSControls.set(fullToolId, element);\n }\n element.setAttribute(\"tool-id\", fullToolId);\n element.setAttribute(\"catalog-id\", toolbarContext.catalogId || toolbarContext.itemId);\n element.setAttribute(\"language\", toolbarContext.language || \"en-US\");\n element.setAttribute(\"size\", resolveControlSize());\n element.setAttribute(\"layout-mode\", resolveLayoutMode());\n element.speedOptions = resolveElementSpeedOptions();\n element.showSingleSpeedOption =\n resolveRuntimeSettings().showSingleSpeedOption === true;\n return element;\n };\n const hostLayout = resolveHostLayout();\n return {\n toolId: this.toolId,\n button: null,\n elements: [\n {\n element: ensureElement(),\n mount: hostLayout.mount,\n layoutHints: {\n controlsRow: {\n reserveSpace: hostLayout.controlsRow.reserveSpace,\n showWhenToolActive: hostLayout.controlsRow.expandWhenToolActive,\n },\n headerOverlay: {\n showWhenToolActive: hostLayout.headerOverlay.expandWhenToolActive,\n },\n },\n },\n ],\n subscribeActive: (callback) => {\n const element = ensureElement();\n const handler = (event) => {\n const detail = event.detail;\n callback(detail?.active === true);\n };\n element.addEventListener(TOOL_ACTIVE_CHANGE_EVENT, handler);\n return () => {\n element.removeEventListener(TOOL_ACTIVE_CHANGE_EVENT, handler);\n };\n },\n sync: () => {\n const element = ensureElement();\n element.setAttribute(\"tool-id\", fullToolId);\n element.setAttribute(\"catalog-id\", toolbarContext.catalogId || toolbarContext.itemId);\n element.setAttribute(\"language\", toolbarContext.language || \"en-US\");\n element.setAttribute(\"size\", resolveControlSize());\n element.setAttribute(\"layout-mode\", resolveLayoutMode());\n element.speedOptions = resolveElementSpeedOptions();\n element.showSingleSpeedOption =\n resolveRuntimeSettings().showSingleSpeedOption === true;\n },\n };\n },\n};\n","const defaultTtsSettings = {\n\tlayoutMode: 'expanding-row',\n};\n\nexport const defaultSectionTtsProviderConfig = {\n\tprovider: 'polly',\n\tserverProvider: 'polly',\n\ttransportMode: 'pie',\n\tendpointMode: 'synthesizePath',\n\tapiEndpoint: '/api/tts',\n\tdefaultVoice: 'Joanna',\n\tengine: 'standard',\n\tformat: 'mp3',\n\tspeechMarksMode: 'word',\n\tvalidateEndpoint: false,\n\tsettings: defaultTtsSettings,\n};\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n\treturn value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\nexport function resolveSectionTtsProviderConfig(provider: Record<string, unknown> = {}) {\n\tconst providerSettings = asRecord(provider.settings);\n\n\treturn {\n\t\t...defaultSectionTtsProviderConfig,\n\t\t...provider,\n\t\tsettings: {\n\t\t\t...defaultTtsSettings,\n\t\t\t...providerSettings,\n\t\t},\n\t};\n}\n","<script lang=\"ts\">\n\timport {\n\t\tassessmentToolkitRegionScopeContext,\n\t\tassessmentToolkitShellContext,\n\t\tToolkitCoordinator,\n\t\tToolRegistry,\n\t\ttype AssessmentToolkitRegionScopeContext,\n\t\ttype AssessmentToolkitShellContext,\n\t} from '@pie-players/pie-assessment-toolkit';\n\t// pie-assessment-toolkit 0.3.65 moved the concrete tool registrations out of the\n\t// toolkit core, so a host composes the capabilities it wants. The two\n\t// registrations are imported individually rather than through\n\t// createPackagedToolRegistry(), whose PACKAGED_TOOL_REGISTRATIONS statically\n\t// references all eleven packaged tools and so drags every one into the bundle.\n\timport {\n\t\tcalculatorToolRegistration,\n\t\tttsToolRegistration,\n\t} from '@pie-players/pie-default-tool-loaders';\n\timport { ContextProvider, ContextRoot } from '@pie-players/pie-context';\n\timport type { QtiSectionToolConfig } from '../contracts/index.js';\n\timport { resolveSectionTtsProviderConfig } from '../tools/section-tool-config.js';\n\n\tinterface Props {\n\t\ttools?: QtiSectionToolConfig[];\n\t\tscopeId: string;\n\t\tscopeLabel: string;\n\t\tsourceText?: string;\n\t\tsourceXml?: string;\n\t\tscopeElement?: HTMLElement | null;\n\t}\n\n\ttype TtsHighlightContext = {\n\t\tscopeElement?: HTMLElement | null;\n\t};\n\n\ttype TtsHighlightTargetResolver = {\n\t\tresolveWordRange?: (range: Range, context: TtsHighlightContext) => Range | null | undefined;\n\t\tresolveSentenceRanges?: (ranges: Range[], context: TtsHighlightContext) => Array<Range | HTMLElement> | null | undefined;\n\t};\n\n\ttype QtiRegionScopeContext = AssessmentToolkitRegionScopeContext & {\n\t\tttsHighlightTargetResolver?: TtsHighlightTargetResolver | null;\n\t};\n\n\tconst { tools = [], scopeId, scopeLabel, sourceText = '', sourceXml = '', scopeElement = null }: Props = $props();\n\n\tlet shellHost = $state<HTMLElement | null>(null);\n\tlet shellProvider: ContextProvider<typeof assessmentToolkitShellContext> | null = null;\n\tlet shellContextRoot: ContextRoot | null = null;\n\tlet regionScopeProvider: ContextProvider<typeof assessmentToolkitRegionScopeContext> | null = null;\n\tlet regionScopeRoot: ContextRoot | null = null;\n\tlet toolkitElement = $state<HTMLElement | null>(null);\n\tlet toolkitCoordinator = $state<ToolkitCoordinator | null>(null);\n\tlet toolkitElementsReady = $state(false);\n\tconst visibleTools = $derived(tools.filter((tool) => tool.enabled !== false));\n\tconst hasTts = $derived(visibleTools.some((tool) => tool.toolId === 'textToSpeech'));\n\tconst calculatorTool = $derived(visibleTools.find((tool) => tool.toolId === 'calculator'));\n\tconst toolbarTools = $derived(\n\t\t[\n\t\t\thasTts ? 'textToSpeech' : '',\n\t\t\tcalculatorTool ? 'calculator' : '',\n\t\t]\n\t\t\t.filter(Boolean)\n\t\t\t.join(','),\n\t);\n\tconst contentKind = $derived(scopeLabel === 'passage' ? 'rubric-block-stimulus' : 'assessment-item');\n\tconst level = $derived(scopeLabel === 'passage' ? 'passage' : 'item');\n\tconst sourceMarkup = $derived(sourceXml.trim() || sourceText.trim());\n\t// The toolkit core no longer ships a default tag map either, for the same reason:\n\t// a map names capabilities, so it belongs to whoever decides which exist. These\n\t// two entries mirror PACKAGED_TOOL_TAG_MAP.\n\tconst toolRegistry = (() => {\n\t\tconst registry = new ToolRegistry();\n\t\tregistry.register(ttsToolRegistration);\n\t\tregistry.register(calculatorToolRegistration);\n\t\tregistry.setComponentOverrides({\n\t\t\ttoolTagMap: {\n\t\t\t\ttextToSpeech: 'pie-tool-text-to-speech',\n\t\t\t\tcalculator: 'pie-tool-calculator',\n\t\t\t},\n\t\t});\n\t\tregistry.setToolModuleLoaders({\n\t\t\ttextToSpeech: () => import('@pie-players/pie-tool-tts-inline'),\n\t\t\tcalculator: () => import('@pie-players/pie-tool-calculator-desmos'),\n\t\t});\n\t\treturn registry;\n\t})();\n\tconst ttsProvider = $derived(visibleTools.find((tool) => tool.toolId === 'textToSpeech')?.provider ?? {});\n\tconst calculatorParams = $derived(calculatorTool?.renderParams ?? {});\n\tconst toolsConfig = $derived({\n\t\tpnpEnforcement: 'off',\n\t\tpolicy: {\n\t\t\tallowed: visibleTools.map((tool) => String(tool.toolId)),\n\t\t\tblocked: [],\n\t\t},\n\t\tplacement: {\n\t\t\tsection: [],\n\t\t\titem: level === 'item' ? visibleTools.map((tool) => String(tool.toolId)) : [],\n\t\t\tpassage: level === 'passage' ? visibleTools.map((tool) => String(tool.toolId)) : [],\n\t\t},\n\t\tproviders: {\n\t\t\ttextToSpeech: resolveSectionTtsProviderConfig(ttsProvider),\n\t\t\tcalculator: {\n\t\t\t\tprovider: {\n\t\t\t\t\tid: 'calculator-desmos',\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t});\n\tconst toolEntity = $derived({\n\t\tid: scopeId,\n\t\tconfig: {\n\t\t\tmarkup: sourceMarkup,\n\t\t\tcontent: sourceMarkup,\n\t\t\telements: {\n\t\t\t\t[scopeId]: sourceMarkup,\n\t\t\t},\n\t\t\tmodels: [\n\t\t\t\t{\n\t\t\t\t\tid: scopeId,\n\t\t\t\t\tprompt: sourceMarkup,\n\t\t\t\t\tmarkup: sourceMarkup,\n\t\t\t\t\t...calculatorParams,\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t});\n\tconst effectiveScopeElement = $derived(scopeElement || shellHost);\n\tconst readableTrackingSelector =\n\t\t'p,h1,h2,h3,h4,h5,h6,li,label,td,th,blockquote,figcaption,[role=\"heading\"],[role=\"listitem\"],[role=\"radio\"],.qti-choice-prompt,.qti-choice-text';\n\tconst shellContextValue = $derived.by((): AssessmentToolkitShellContext | null => {\n\t\tif (!effectiveScopeElement) return null;\n\t\treturn {\n\t\t\tkind: level === 'passage' ? 'passage' : 'item',\n\t\t\titemId: scopeId,\n\t\t\tcanonicalItemId: scopeId,\n\t\t\tcontentKind,\n\t\t\tregionPolicy: 'default',\n\t\t\tscopeElement: effectiveScopeElement,\n\t\t\titem: toolEntity,\n\t\t\tcontextVersion: Date.now(),\n\t\t};\n\t});\n\tconst ttsHighlightTargetResolver: TtsHighlightTargetResolver = {\n\t\tresolveWordRange: (range, context) => {\n\t\t\tconst scope = context.scopeElement ?? effectiveScopeElement;\n\t\t\tif (!scope) return range;\n\t\t\treturn resolveVisibleTrackingRange(range, scope);\n\t\t},\n\t\tresolveSentenceRanges: (ranges, context) => {\n\t\t\tconst scope = context.scopeElement ?? effectiveScopeElement;\n\t\t\tif (!scope) return ranges;\n\t\t\tconst targets = ranges\n\t\t\t\t.map((range) => resolveVisibleTrackingBlock(range, scope))\n\t\t\t\t.filter((target): target is HTMLElement => target instanceof HTMLElement);\n\t\t\treturn targets.length > 0 ? targets : ranges;\n\t\t},\n\t};\n\n\t$effect(() => {\n\t\tif (visibleTools.length === 0 || toolkitElementsReady) return;\n\t\tlet cancelled = false;\n\t\tvoid Promise.all([\n\t\t\timport('@pie-players/pie-assessment-toolkit/components/item-toolbar-element'),\n\t\t\timport('@pie-players/pie-assessment-toolkit/components/pie-assessment-toolkit-element'),\n\t\t])\n\t\t\t.then(() => {\n\t\t\t\tif (!cancelled) toolkitElementsReady = true;\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (!cancelled) console.error('Unable to load assessment toolkit elements:', error);\n\t\t\t});\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t});\n\tconst regionScopeValue = $derived.by((): QtiRegionScopeContext | null => {\n\t\tif (!effectiveScopeElement) return null;\n\t\treturn {\n\t\t\tscopeElement: effectiveScopeElement,\n\t\t\tttsHighlightTargetResolver,\n\t\t};\n\t});\n\n\ttype TextPosition = { node: Text; offset: number };\n\n\tfunction normalizeTrackingText(value: string) {\n\t\treturn value.replace(/\\s+/g, ' ').trim();\n\t}\n\n\tfunction isVisibleTrackingElement(element: Element) {\n\t\tconst rect = element.getBoundingClientRect();\n\t\tconst style = window.getComputedStyle(element);\n\t\treturn rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && rect.x >= 0 && rect.y >= 0;\n\t}\n\n\tfunction isProjectionElement(element: Element | null) {\n\t\treturn !!element?.closest('[data-qti-tts-readable-projection]');\n\t}\n\n\tfunction nearestReadableBlock(node: Node | null, scope: HTMLElement): HTMLElement | null {\n\t\tconst start = node?.nodeType === Node.ELEMENT_NODE ? (node as Element) : node?.parentElement;\n\t\tconst block = start?.closest?.(readableTrackingSelector);\n\t\treturn block instanceof HTMLElement && scope.contains(block) ? block : scope;\n\t}\n\n\tfunction findVisibleTrackingBlock(sourceBlock: HTMLElement, scope: HTMLElement) {\n\t\tconst sourceText = normalizeTrackingText(sourceBlock.textContent ?? '');\n\t\tif (!sourceText) return null;\n\t\tconst candidates = queryElementsIncludingOpenShadowRoots(scope, readableTrackingSelector).filter(\n\t\t\t(candidate): candidate is HTMLElement =>\n\t\t\t\tcandidate instanceof HTMLElement &&\n\t\t\t\t!isProjectionElement(candidate) &&\n\t\t\t\tisVisibleTrackingElement(candidate) &&\n\t\t\t\tnormalizeTrackingText(candidate.textContent ?? '') === sourceText,\n\t\t);\n\t\treturn candidates\n\t\t\t.sort((left, right) => {\n\t\t\t\tconst leftRect = left.getBoundingClientRect();\n\t\t\t\tconst rightRect = right.getBoundingClientRect();\n\t\t\t\treturn leftRect.width * leftRect.height - rightRect.width * rightRect.height;\n\t\t\t})[0] ?? null;\n\t}\n\n\tfunction resolveVisibleTrackingBlock(range: Range, scope: HTMLElement) {\n\t\tconst sourceBlock = nearestReadableBlock(range.startContainer, scope);\n\t\tif (!sourceBlock) return null;\n\t\tif (!isProjectionElement(sourceBlock)) return sourceBlock;\n\t\treturn findVisibleTrackingBlock(sourceBlock, scope);\n\t}\n\n\tfunction collectNormalizedTextMap(root: Element) {\n\t\tconst text: string[] = [];\n\t\tconst positions: TextPosition[] = [];\n\t\tlet lastWasWhitespace = true;\n\t\tconst walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n\t\tlet node = walker.nextNode();\n\n\t\twhile (node) {\n\t\t\tconst textNode = node as Text;\n\t\t\tconst raw = textNode.textContent ?? '';\n\t\t\tfor (let offset = 0; offset < raw.length; offset += 1) {\n\t\t\t\tconst char = raw[offset];\n\t\t\t\tif (/\\s/.test(char)) {\n\t\t\t\t\tif (!lastWasWhitespace) {\n\t\t\t\t\t\ttext.push(' ');\n\t\t\t\t\t\tpositions.push({ node: textNode, offset });\n\t\t\t\t\t\tlastWasWhitespace = true;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttext.push(char);\n\t\t\t\tpositions.push({ node: textNode, offset });\n\t\t\t\tlastWasWhitespace = false;\n\t\t\t}\n\t\t\tnode = walker.nextNode();\n\t\t}\n\n\t\twhile (text[text.length - 1] === ' ') {\n\t\t\ttext.pop();\n\t\t\tpositions.pop();\n\t\t}\n\n\t\treturn { text: text.join(''), positions };\n\t}\n\n\tfunction findNormalizedPosition(positions: TextPosition[], node: Node, offset: number) {\n\t\treturn positions.findIndex((position) => position.node === node && position.offset === offset);\n\t}\n\n\tfunction createRangeFromNormalizedSpan(map: { positions: TextPosition[] }, startIndex: number, endIndex: number) {\n\t\tconst start = map.positions[startIndex];\n\t\tconst end = map.positions[endIndex - 1];\n\t\tif (!start || !end) return null;\n\t\tconst range = document.createRange();\n\t\trange.setStart(start.node, start.offset);\n\t\trange.setEnd(end.node, end.offset + 1);\n\t\treturn range;\n\t}\n\n\tfunction mapProjectionRangeToVisibleRange(range: Range, sourceBlock: HTMLElement, visibleBlock: HTMLElement) {\n\t\tconst sourceMap = collectNormalizedTextMap(sourceBlock);\n\t\tconst visibleMap = collectNormalizedTextMap(visibleBlock);\n\t\tif (sourceMap.text !== visibleMap.text) return null;\n\n\t\tconst startIndex = findNormalizedPosition(sourceMap.positions, range.startContainer, range.startOffset);\n\t\tconst endIndex = findNormalizedPosition(sourceMap.positions, range.endContainer, Math.max(range.endOffset - 1, 0));\n\t\tif (startIndex < 0 || endIndex < startIndex) return null;\n\t\treturn createRangeFromNormalizedSpan(visibleMap, startIndex, endIndex + 1);\n\t}\n\n\tfunction resolveVisibleTrackingRange(range: Range, scope: HTMLElement) {\n\t\tconst sourceBlock = nearestReadableBlock(range.startContainer, scope);\n\t\tif (!sourceBlock || !isProjectionElement(sourceBlock)) return range;\n\t\tconst visibleBlock = findVisibleTrackingBlock(sourceBlock, scope);\n\t\tif (!visibleBlock) return null;\n\t\treturn mapProjectionRangeToVisibleRange(range, sourceBlock, visibleBlock);\n\t}\n\n\t/**\n\t * Stop pie-assessment-toolkit from injecting FontAwesome into this page.\n\t *\n\t * Its ItemToolBar appends FontAwesome Free from jsDelivr plus host-relative\n\t * /_fa-pro/*.min.css links at import time, expecting the embedding app to serve\n\t * FontAwesome Pro — Quiz Engine does; this repo does not, so those requests 404.\n\t * The injection is skipped when a stylesheet whose href matches\n\t * /font.?awesome|fa-?pro/i is already present, so a dummy data: URL suppresses it.\n\t *\n\t * This runs regardless of the `ndsIcons` opt-in: the toolkit injects on import, not\n\t * on the decision to render vendored icon buttons. Removing it brings the 404s back,\n\t * which apps/demo/tests/playwright/section-player.pw.ts asserts against.\n\t */\n\tfunction ensureFontAwesomeFallbackMarker() {\n\t\tif (typeof document === 'undefined') return;\n\t\tconst hasFontAwesomeLink = Array.from(document.querySelectorAll('link[rel=\"stylesheet\"][href]')).some((link) =>\n\t\t\t/font.?awesome|fa-?pro/i.test((link as HTMLLinkElement).href),\n\t\t);\n\t\tif (hasFontAwesomeLink) return;\n\t\tconst link = document.createElement('link');\n\t\tlink.rel = 'stylesheet';\n\t\tlink.href = 'data:text/css;charset=utf-8,/*fontawesome-pie-qti-fallback*/';\n\t\tdocument.head.appendChild(link);\n\t}\n\n\tensureFontAwesomeFallbackMarker();\n\n\tfunction collectQueryableRoots(root: ParentNode, roots: ParentNode[] = [], seen = new WeakSet<object>()) {\n\t\tif (seen.has(root)) return roots;\n\t\tseen.add(root);\n\t\troots.push(root);\n\n\t\tconst elements: Element[] = [];\n\t\tif (root instanceof Element) elements.push(root);\n\t\telements.push(...Array.from(root.querySelectorAll('*')));\n\n\t\tfor (const element of elements) {\n\t\t\tif (element.shadowRoot) {\n\t\t\t\tcollectQueryableRoots(element.shadowRoot, roots, seen);\n\t\t\t}\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\tfunction queryElementsIncludingOpenShadowRoots(root: ParentNode, selector: string) {\n\t\tconst elements: Element[] = [];\n\t\tfor (const queryRoot of collectQueryableRoots(root)) {\n\t\t\tif (queryRoot instanceof Element && queryRoot.matches(selector)) {\n\t\t\t\telements.push(queryRoot);\n\t\t\t}\n\t\t\telements.push(...Array.from(queryRoot.querySelectorAll(selector)));\n\t\t}\n\t\treturn elements;\n\t}\n\n\t$effect(() => {\n\t\tif (toolkitCoordinator) return;\n\t\ttoolkitCoordinator = new ToolkitCoordinator({\n\t\t\tassessmentId: `qti-section-demo-${scopeId}`,\n\t\t\tlazyInit: false,\n\t\t\ttoolConfigStrictness: 'off',\n\t\t\ttools: toolsConfig as any,\n\t\t\ttoolRegistry,\n\t\t});\n\t});\n\n\t$effect(() => {\n\t\tif (!shellHost || !shellContextValue) return;\n\t\tshellProvider = new ContextProvider(shellHost, {\n\t\t\tcontext: assessmentToolkitShellContext,\n\t\t\tinitialValue: shellContextValue,\n\t\t});\n\t\tshellProvider.connect();\n\t\tshellContextRoot = new ContextRoot(shellHost);\n\t\tshellContextRoot.attach();\n\n\t\treturn () => {\n\t\t\tshellContextRoot?.detach();\n\t\t\tshellContextRoot = null;\n\t\t\tshellProvider?.disconnect();\n\t\t\tshellProvider = null;\n\t\t};\n\t});\n\n\t$effect(() => {\n\t\tif (!shellContextValue) return;\n\t\tshellProvider?.setValue(shellContextValue);\n\t});\n\n\t$effect(() => {\n\t\tif (!shellHost || !regionScopeValue) return;\n\t\tregionScopeProvider = new ContextProvider(shellHost, {\n\t\t\tcontext: assessmentToolkitRegionScopeContext,\n\t\t\tinitialValue: regionScopeValue,\n\t\t});\n\t\tregionScopeProvider.connect();\n\t\tregionScopeRoot = new ContextRoot(shellHost);\n\t\tregionScopeRoot.attach();\n\n\t\treturn () => {\n\t\t\tregionScopeRoot?.detach();\n\t\t\tregionScopeRoot = null;\n\t\t\tregionScopeProvider?.disconnect();\n\t\t\tregionScopeProvider = null;\n\t\t};\n\t});\n\n\t$effect(() => {\n\t\tif (!regionScopeValue) return;\n\t\tregionScopeProvider?.setValue(regionScopeValue);\n\t});\n\n\t$effect(() => {\n\t\tif (!toolkitCoordinator) return;\n\t\ttoolkitElement?.dispatchEvent(\n\t\t\tnew CustomEvent('qti-toolkit-coordinator-ready', {\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t\tdetail: {\n\t\t\t\t\tscopeId,\n\t\t\t\t\tlevel,\n\t\t\t\t\tcoordinator: toolkitCoordinator,\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t});\n</script>\n\n{#if visibleTools.length > 0 && toolkitElementsReady}\n\t<span bind:this={shellHost} class=\"qti-pie-tool-shell\">\n\t\t{#if toolkitCoordinator}\n\t\t\t<pie-assessment-toolkit\n\t\t\t\tbind:this={toolkitElement}\n\t\t\t\tassessment-id=\"qti-section-demo\"\n\t\t\t\tsection-id={`section-${scopeId}`}\n\t\t\t\ttools={toolsConfig}\n\t\t\t\t{toolRegistry}\n\t\t\t\tcoordinator={toolkitCoordinator}\n\t\t\t\tlazy-init={false}\n\t\t\t>\n\t\t\t\t<pie-item-toolbar\n\t\t\t\t\t{level}\n\t\t\t\t\tscope-id={scopeId}\n\t\t\t\t\titem-id={scopeId}\n\t\t\t\t\tcatalog-id={scopeId}\n\t\t\t\t\ttools={toolbarTools}\n\t\t\t\t\t{contentKind}\n\t\t\t\t\tsize=\"md\"\n\t\t\t\t\tlanguage=\"en-US\"\n\t\t\t\t\tscopeElement={effectiveScopeElement}\n\t\t\t\t\t{toolRegistry}\n\t\t\t\t\titem={toolEntity}\n\t\t\t\t></pie-item-toolbar>\n\t\t\t</pie-assessment-toolkit>\n\t\t{/if}\n\t</span>\n{/if}\n\n<style>\n\t.qti-pie-tool-shell {\n\t\tdisplay: inline-flex;\n\t\tmargin-left: auto;\n\t}\n\n\tpie-assessment-toolkit {\n\t\tdisplay: inline-flex;\n\t}\n</style>\n","/// <reference lib=\"dom\" />\n/**\n * Generic Svelte action that calls `params.typeset(node)` initially and on DOM updates.\n *\n * This is intentionally dependency-free so the player/components can be used\n * outside the example app without pulling in a math engine.\n *\n * If typeset is undefined, the action becomes a no-op (returns immediately).\n */\nexport function typesetAction(node, params) {\n // No-op if no typeset function provided\n if (!params?.typeset) {\n return { update() { }, destroy() { } };\n }\n const isBrowser = typeof window !== 'undefined' && typeof MutationObserver !== 'undefined';\n if (!isBrowser)\n return { update() { }, destroy() { } };\n let disposed = false;\n let scheduled = false;\n let observer = null;\n let current = params;\n const schedule = () => {\n if (disposed || scheduled || !current.typeset)\n return;\n scheduled = true;\n requestAnimationFrame(async () => {\n scheduled = false;\n if (disposed || !current.typeset)\n return;\n try {\n await current.typeset(node);\n }\n catch {\n // ignore typesetting errors; keep raw text\n }\n });\n };\n const startObserver = () => {\n if (observer)\n return;\n observer = new MutationObserver(() => schedule());\n observer.observe(node, { childList: true, subtree: true, characterData: true });\n };\n const stopObserver = () => {\n observer?.disconnect();\n observer = null;\n };\n // initial\n schedule();\n if (current.observe !== false)\n startObserver();\n return {\n update(next) {\n if (!next?.typeset) {\n stopObserver();\n return;\n }\n current = next;\n if (current.observe === false)\n stopObserver();\n else\n startObserver();\n schedule();\n },\n destroy() {\n disposed = true;\n stopObserver();\n },\n };\n}\n//# sourceMappingURL=typesetAction.js.map","import { sanitizeSharedHtml as sanitizeItemPlayerSharedHtml } from '@pie-qti/item-player/security';\nimport type { HtmlContent, PlayerSecurityConfig } from '@pie-qti/item-player';\nimport type { QtiSectionRuntimeHostContract, QtiSharedHtmlSanitizeContext } from '../contracts/index.js';\n\nexport function sanitizeSectionSharedHtml(\n\thtml: string,\n\tsecurity: PlayerSecurityConfig | undefined,\n\tcontext: QtiSharedHtmlSanitizeContext,\n\thost?: QtiSectionRuntimeHostContract\n): HtmlContent {\n\tconst hostResult = host?.sanitizeSharedHtml?.(html, context);\n\treturn sanitizeItemPlayerSharedHtml(hostResult ?? html, security, {\n\t\tsanitizeUrl: (href, kind) => {\n\t\t\tif (!host?.sanitizeAssetUrl) return href;\n\t\t\treturn host.sanitizeAssetUrl(href, { source: context.source, kind });\n\t\t},\n\t});\n}\n","<script lang=\"ts\">\n\timport { typesetAction } from '@pie-qti/default-components/shared';\n\timport { htmlToString } from '@pie-qti/item-player/security';\n\timport type { HtmlContent, PlayerSecurityConfig } from '@pie-qti/item-player';\n\timport type { QtiSectionRuntimeHostContract, QtiSharedHtmlSanitizeContext } from '../contracts/index.js';\n\timport { sanitizeSectionSharedHtml } from '../security/sanitizeSharedHtml.js';\n\n\tinterface Props {\n\t\thtml?: HtmlContent;\n\t\trawHtml?: string;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\thost?: QtiSectionRuntimeHostContract;\n\t\tsanitizeContext: QtiSharedHtmlSanitizeContext;\n\t\tclass?: string;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t}\n\n\tconst {\n\t\thtml,\n\t\trawHtml = '',\n\t\tsecurity,\n\t\thost,\n\t\tsanitizeContext,\n\t\tclass: className = '',\n\t\ttypeset,\n\t}: Props = $props();\n\n\tconst unsafeHtml = $derived(html === undefined ? rawHtml : htmlToString(html));\n\tconst content = $derived(sanitizeSectionSharedHtml(unsafeHtml, security, sanitizeContext, host));\n</script>\n\n<div use:typesetAction={{ typeset }} class={className}>\n\t{@html content}\n</div>\n","<script lang=\"ts\">\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\timport type { PlayerSecurityConfig } from '@pie-qti/item-player';\n\timport type {\n\t\tQtiSectionRole,\n\t\tQtiSectionRuntimeHostContract,\n\t\tQtiSharedHtmlBlock,\n\t\tQtiSharedHtmlSanitizeContext,\n\t} from '../contracts/index.js';\n\timport { isQtiViewVisibleForRole } from '../visibility/role-view.js';\n\timport QtiToolButtonBar from './QtiToolButtonBar.svelte';\n\timport SanitizedHtml from './SanitizedHtml.svelte';\n\n\tinterface Props {\n\t\tpassages?: QtiSharedHtmlBlock[];\n\t\trubricBlocks?: QtiSharedHtmlBlock[];\n\t\trole?: QtiSectionRole;\n\t\tcollapsed?: boolean;\n\t\ti18n?: I18nProvider;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\thost?: QtiSectionRuntimeHostContract;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t}\n\n\tconst {\n\t\tpassages = [],\n\t\trubricBlocks = [],\n\t\trole = 'candidate',\n\t\tcollapsed = false,\n\t\ti18n,\n\t\tsecurity,\n\t\thost,\n\t\ttypeset,\n\t}: Props = $props();\n\n\tlet isCollapsed = $state(false);\n\tlet passageScopeElements = $state<Record<string, HTMLElement>>({});\n\n\tconst isVisibleForRole = (block: QtiSharedHtmlBlock) => isQtiViewVisibleForRole(block.view, role);\n\tconst visiblePassages = $derived(passages.filter(isVisibleForRole));\n\tconst visibleRubricBlocks = $derived(rubricBlocks.filter(isVisibleForRole));\n\tconst visibleInstructions = $derived(visibleRubricBlocks.filter((block) => block.kind === 'instructions'));\n\tconst visibleRubrics = $derived(visibleRubricBlocks.filter((block) => block.kind !== 'instructions'));\n\n\t$effect(() => {\n\t\tisCollapsed = collapsed;\n\t});\n\n\tfunction toggleCollapse() {\n\t\tisCollapsed = !isCollapsed;\n\t}\n\n\tfunction passageScope(node: HTMLElement, identifier: string) {\n\t\tpassageScopeElements = { ...passageScopeElements, [identifier]: node };\n\t\treturn {\n\t\t\tdestroy() {\n\t\t\t\tconst next = { ...passageScopeElements };\n\t\t\t\tdelete next[identifier];\n\t\t\t\tpassageScopeElements = next;\n\t\t\t},\n\t\t};\n\t}\n\n\tfunction sanitizeKind(block: QtiSharedHtmlBlock): QtiSharedHtmlSanitizeContext['kind'] {\n\t\treturn block.kind === 'stimulus' || block.kind === 'test-feedback' ? block.kind : block.kind === 'instructions' ? 'instructions' : 'rubric';\n\t}\n</script>\n\n{#if visiblePassages.length > 0 || visibleRubricBlocks.length > 0}\n\t<div class=\"rubric-container\">\n\t\t{#if visiblePassages.length > 0}\n\t\t\t<section class=\"passage-section\" aria-label={i18n?.t('assessment.readingPassages') ?? 'Reading passages'}>\n\t\t\t\t{#each visiblePassages as passage, index (passage.identifier)}\n\t\t\t\t\t<article class=\"passage\" aria-labelledby={`passage-heading-${index}`}>\n\t\t\t\t\t\t<div class=\"passage-header\">\n\t\t\t\t\t\t\t<h4 id={`passage-heading-${index}`} class=\"font-semibold text-base\">\n\t\t\t\t\t\t\t\t{i18n?.t('assessment.readingPassage') ?? 'Reading Passage'}\n\t\t\t\t\t\t\t</h4>\n\t\t\t\t\t\t\t<div class=\"passage-header-actions\">\n\t\t\t\t\t\t\t\t<QtiToolButtonBar\n\t\t\t\t\t\t\t\t\ttools={passage.tools}\n\t\t\t\t\t\t\t\t\tscopeId={passage.identifier}\n\t\t\t\t\t\t\t\t\tscopeLabel=\"passage\"\n\t\t\t\t\t\t\t\t\tsourceText={passage.rawHtml}\n\t\t\t\t\t\t\t\t\tscopeElement={passageScopeElements[passage.identifier] ?? null}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\tclass=\"btn btn-ghost btn-sm passage-toggle\"\n\t\t\t\t\t\t\t\t\tonclick={toggleCollapse}\n\t\t\t\t\t\t\t\t\taria-expanded={!isCollapsed}\n\t\t\t\t\t\t\t\t\taria-label={isCollapsed ? (i18n?.t('assessment.expandPassage') ?? 'Expand passage') : (i18n?.t('assessment.collapsePassage') ?? 'Collapse passage')}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#if isCollapsed}\n\t\t\t\t\t\t\t\t\t\t<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"h-5 w-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" aria-hidden=\"true\">\n\t\t\t\t\t\t\t\t\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M19 9l-7 7-7-7\" />\n\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"h-5 w-5\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" aria-hidden=\"true\">\n\t\t\t\t\t\t\t\t\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M5 15l7-7 7 7\" />\n\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t{#if !isCollapsed}\n\t\t\t\t\t\t\t<div use:passageScope={passage.identifier}>\n\t\t\t\t\t\t\t\t<SanitizedHtml\n\t\t\t\t\t\t\t\t\trawHtml={passage.rawHtml}\n\t\t\t\t\t\t\t\t\thtml={passage.html}\n\t\t\t\t\t\t\t\t\t{security}\n\t\t\t\t\t\t\t\t\t{host}\n\t\t\t\t\t\t\t\t\tsanitizeContext={{ kind: 'passage', source: passage.source }}\n\t\t\t\t\t\t\t\t\tclass=\"passage-content prose max-w-none\"\n\t\t\t\t\t\t\t\t\t{typeset}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</article>\n\t\t\t\t{/each}\n\t\t\t</section>\n\t\t{/if}\n\n\t\t{#if visibleInstructions.length > 0}\n\t\t\t<section class=\"instructions-section\" aria-label={i18n?.t('assessment.instructions') ?? 'Instructions'}>\n\t\t\t\t{#each visibleInstructions as instruction (instruction.identifier)}\n\t\t\t\t\t<div class=\"alert alert-info\">\n\t\t\t\t\t\t<svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" class=\"stroke-current shrink-0 w-6 h-6\" aria-hidden=\"true\">\n\t\t\t\t\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\"></path>\n\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t<SanitizedHtml\n\t\t\t\t\t\t\trawHtml={instruction.rawHtml}\n\t\t\t\t\t\t\thtml={instruction.html}\n\t\t\t\t\t\t\t{security}\n\t\t\t\t\t\t\t{host}\n\t\t\t\t\t\t\tsanitizeContext={{ kind: 'instructions', source: instruction.source }}\n\t\t\t\t\t\t\tclass=\"instructions-content\"\n\t\t\t\t\t\t\t{typeset}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t{/each}\n\t\t\t</section>\n\t\t{/if}\n\n\t\t{#if visibleRubrics.length > 0}\n\t\t\t<section class=\"rubric-section\" aria-label={i18n?.t('assessment.rubrics') ?? 'Rubrics'}>\n\t\t\t\t{#each visibleRubrics as rubric (rubric.identifier)}\n\t\t\t\t\t<SanitizedHtml\n\t\t\t\t\t\trawHtml={rubric.rawHtml}\n\t\t\t\t\t\thtml={rubric.html}\n\t\t\t\t\t\t{security}\n\t\t\t\t\t\t{host}\n\t\t\t\t\t\tsanitizeContext={{ kind: sanitizeKind(rubric), source: rubric.source }}\n\t\t\t\t\t\tclass=\"rubric-block\"\n\t\t\t\t\t\t{typeset}\n\t\t\t\t\t/>\n\t\t\t\t{/each}\n\t\t\t</section>\n\t\t{/if}\n\t</div>\n{/if}\n\n<style>\n\t.rubric-container {\n\t\tmargin-bottom: 2rem;\n\t}\n\n\t.passage-section {\n\t\tmargin-bottom: 1.5rem;\n\t}\n\n\t.passage {\n\t\tborder: 1px solid var(--color-base-300);\n\t\tborder-radius: 0.5rem;\n\t\tpadding: 1rem;\n\t\tbackground: var(--color-base-200);\n\t}\n\n\t.passage-header {\n\t\tdisplay: flex;\n\t\tjustify-content: space-between;\n\t\talign-items: center;\n\t\tgap: 1rem;\n\t\tmargin-bottom: 0.5rem;\n\t}\n\n\t.passage-header-actions {\n\t\tdisplay: inline-flex;\n\t\talign-items: center;\n\t\tgap: 0.5rem;\n\t}\n\n\t.passage-toggle {\n\t\tmin-width: 44px;\n\t\tmin-height: 44px;\n\t}\n\n\t.passage-toggle:focus-visible {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: 2px;\n\t}\n\n\t:global(.passage-content) {\n\t\tpadding: 1rem 0;\n\t\tline-height: 1.6;\n\t}\n\n\t.instructions-section {\n\t\tmargin-bottom: 1.5rem;\n\t}\n\n\t:global(.instructions-content) {\n\t\tline-height: 1.6;\n\t}\n\n\t.rubric-section {\n\t\tmargin-bottom: 1.5rem;\n\t}\n\n\t:global(.rubric-block) {\n\t\tpadding: 1rem;\n\t\tbackground: var(--color-base-200);\n\t\tborder-radius: 0.5rem;\n\t\tmargin-bottom: 1rem;\n\t}\n\n\t:global(.passage-content p) {\n\t\tmargin-bottom: 1rem;\n\t}\n\n\t:global(.passage-content p:last-child) {\n\t\tmargin-bottom: 0;\n\t}\n</style>\n","import type {\n QtiSectionFrameworkError,\n QtiSectionResponseDeltaEvent,\n ResolvedQtiSectionComposition,\n} from '../contracts/index.js';\n\nexport function notifyResponseDelta(\n composition: ResolvedQtiSectionComposition,\n itemIdentifier: string,\n responseIdentifier: string,\n value: unknown\n): QtiSectionResponseDeltaEvent {\n const event: QtiSectionResponseDeltaEvent = {\n sectionIdentifier: composition.section.identifier,\n itemIdentifier,\n responseIdentifier,\n value,\n };\n composition.host?.onResponseDelta?.(event);\n return event;\n}\n\nexport function notifyActiveItemChange(composition: ResolvedQtiSectionComposition) {\n composition.host?.onActiveItemChange?.({\n sectionIdentifier: composition.section.identifier,\n itemIdentifier: composition.activeItem.identifier,\n itemIndex: composition.activeItemIndex,\n itemCount: composition.section.itemRefs.length,\n });\n}\n\nexport function notifySnapshotChange(composition: ResolvedQtiSectionComposition) {\n composition.host?.onSnapshotChange?.(composition.snapshot);\n}\n\nexport function notifyFrameworkError(\n composition: ResolvedQtiSectionComposition,\n error: QtiSectionFrameworkError\n): QtiSectionFrameworkError {\n const event: QtiSectionFrameworkError = {\n ...error,\n sectionIdentifier: error.sectionIdentifier ?? composition.section.identifier,\n itemIdentifier: error.itemIdentifier ?? composition.activeItem.identifier,\n };\n composition.host?.onFrameworkError?.(event);\n return event;\n}\n","/// <reference lib=\"dom\" />\n\nimport { enforceItemXmlLimits, sanitizeHtml } from '@pie-qti/item-player/security';\nimport type { PlayerSecurityConfig } from '@pie-qti/item-player';\n\ntype DOMParserConstructor = new () => {\n\tparseFromString(xml: string, mimeType: string): Document;\n};\n\ntype XMLSerializerLike = {\n\tserializeToString(node: Node): string;\n};\n\ninterface ReadableProjectionOptions {\n\tDOMParserImpl?: DOMParserConstructor;\n\tXMLSerializerImpl?: new () => XMLSerializerLike;\n\tsecurity?: PlayerSecurityConfig;\n}\n\nconst interactionElementNames = new Set([\n\t'associateInteraction',\n\t'choiceInteraction',\n\t'customInteraction',\n\t'drawingInteraction',\n\t'endAttemptInteraction',\n\t'extendedTextInteraction',\n\t'gapMatchInteraction',\n\t'graphicAssociateInteraction',\n\t'graphicGapMatchInteraction',\n\t'graphicOrderInteraction',\n\t'hotspotInteraction',\n\t'hottextInteraction',\n\t'inlineChoiceInteraction',\n\t'matchInteraction',\n\t'mediaInteraction',\n\t'orderInteraction',\n\t'positionObjectInteraction',\n\t'selectPointInteraction',\n\t'sliderInteraction',\n\t'textEntryInteraction',\n\t'uploadInteraction',\n]);\n\nconst readableChildNames = new Set([\n\t'gapText',\n\t'hottext',\n\t'inlineChoice',\n\t'object',\n\t'prompt',\n\t'simpleAssociableChoice',\n\t'simpleChoice',\n]);\n\nconst optionLikeNames = new Set(['gapText', 'hottext', 'inlineChoice', 'simpleAssociableChoice', 'simpleChoice']);\n\nfunction escapeHtml(value: string) {\n\treturn value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nfunction getParser(options: ReadableProjectionOptions) {\n\treturn options.DOMParserImpl ?? (typeof DOMParser !== 'undefined' ? DOMParser : null);\n}\n\nfunction getSerializer(options: ReadableProjectionOptions) {\n\tconst XMLSerializerImpl = options.XMLSerializerImpl ?? (typeof XMLSerializer !== 'undefined' ? XMLSerializer : null);\n\treturn XMLSerializerImpl ? new XMLSerializerImpl() : null;\n}\n\nfunction isElement(node: Node): node is Element {\n\treturn node.nodeType === 1;\n}\n\nfunction serializeReadableNode(\n\tnode: Node,\n\tserializer: XMLSerializerLike | null,\n\toptions: ReadableProjectionOptions,\n): string {\n\tif (node.nodeType === 3) return escapeHtml(node.textContent ?? '');\n\tif (!isElement(node)) return '';\n\n\tconst localName = node.localName.toLowerCase();\n\tif (localName === 'object' || localName === 'img') {\n\t\tconst label = node.getAttribute('aria-label') || node.getAttribute('alt') || node.getAttribute('title');\n\t\treturn label?.trim() ? escapeHtml(label.trim()) : '';\n\t}\n\tif (localName === 'br') return '<br>';\n\tif (localName === 'math') {\n\t\tconst markup = serializer\n\t\t\t? serializer.serializeToString(node)\n\t\t\t: (node as Element & { outerHTML?: string }).outerHTML ?? escapeHtml(node.textContent ?? '');\n\t\treturn sanitizeHtml(markup, { security: options.security });\n\t}\n\n\t// The projection exists only to expose readable content to TTS. Do not copy\n\t// arbitrary authored elements or attributes into the host document: recurse\n\t// into their text instead, retaining only sanitized MathML and line breaks.\n\treturn Array.from(node.childNodes)\n\t\t.map((child) => serializeReadableNode(child, serializer, options))\n\t\t.join('');\n}\n\nfunction serializeChildren(\n\telement: Element,\n\tserializer: XMLSerializerLike | null,\n\toptions: ReadableProjectionOptions,\n) {\n\treturn Array.from(element.childNodes)\n\t\t.map((node) => serializeReadableNode(node, serializer, options))\n\t\t.join('')\n\t\t.trim();\n}\n\nfunction childElementsByLocalName(element: Element, localName: string) {\n\treturn Array.from(element.children).filter((child) => child.localName === localName);\n}\n\nfunction allElements(root: ParentNode) {\n\treturn Array.from(root.querySelectorAll('*'));\n}\n\nfunction descendantElementsByLocalNames(element: Element, localNames: Set<string>) {\n\treturn allElements(element).filter((child) => localNames.has(child.localName));\n}\n\nfunction paragraph(markup: string, source: string) {\n\treturn markup ? `<p data-qti-readable-source=\"${escapeHtml(source)}\">${markup}</p>` : '';\n}\n\nfunction readableMarkupForElement(\n\telement: Element,\n\tserializer: XMLSerializerLike | null,\n\toptions: ReadableProjectionOptions,\n) {\n\tif (element.localName === 'object') {\n\t\tconst label = element.getAttribute('aria-label') || element.getAttribute('alt') || element.getAttribute('title');\n\t\tif (label?.trim()) return escapeHtml(label.trim());\n\t}\n\n\treturn serializeChildren(element, serializer, options);\n}\n\nfunction extractInteractionChunks(\n\tinteraction: Element,\n\tserializer: XMLSerializerLike | null,\n\toptions: ReadableProjectionOptions,\n) {\n\tconst chunks: string[] = [];\n\n\tfor (const prompt of childElementsByLocalName(interaction, 'prompt')) {\n\t\tconst markup = readableMarkupForElement(prompt, serializer, options);\n\t\tif (markup) chunks.push(paragraph(markup, 'prompt'));\n\t}\n\n\tconst optionElements = descendantElementsByLocalNames(interaction, optionLikeNames);\n\tfor (const option of optionElements) {\n\t\tconst markup = readableMarkupForElement(option, serializer, options);\n\t\tif (markup) chunks.push(paragraph(markup, option.localName));\n\t}\n\n\tif (chunks.length === 0) {\n\t\tfor (const readable of descendantElementsByLocalNames(interaction, readableChildNames)) {\n\t\t\tconst markup = readableMarkupForElement(readable, serializer, options);\n\t\t\tif (markup) chunks.push(paragraph(markup, readable.localName));\n\t\t}\n\t}\n\n\treturn chunks;\n}\n\nexport function extractReadableInteractionSpeechHtml(itemXml?: string, options: ReadableProjectionOptions = {}) {\n\tif (!itemXml) return '';\n\tenforceItemXmlLimits(itemXml, options.security);\n\n\tconst DOMParserImpl = getParser(options);\n\tif (!DOMParserImpl) return '';\n\n\tconst document = new DOMParserImpl().parseFromString(itemXml, 'application/xml');\n\tif (document.getElementsByTagName('parsererror').length > 0) return '';\n\n\tconst serializer = getSerializer(options);\n\tconst interactions = allElements(document).filter((element) => interactionElementNames.has(element.localName));\n\tconst chunks = interactions.flatMap((interaction) => extractInteractionChunks(interaction, serializer, options));\n\n\treturn chunks.join('');\n}\n","<script lang=\"ts\">\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\timport type { PciConfiguration, PlayerSecurityConfig, PnpProfile } from '@pie-qti/item-player';\n\timport { assignProps } from '@pie-qti/qti-common';\n\timport { onMount } from 'svelte';\n\timport type { QtiSectionFrameworkError, QtiSectionItemRef, QtiSectionRole } from '../contracts/index.js';\n\timport { extractReadableInteractionSpeechHtml } from '../tts/readable-interaction-projection.js';\n\timport QtiToolButtonBar from './QtiToolButtonBar.svelte';\n\n\ttype ItemPlayerResponseChangeEvent = CustomEvent<{ responseId: string; value: unknown }>;\n\n\tinterface Props {\n\t\titemRef: QtiSectionItemRef;\n\t\tresponses?: Record<string, unknown>;\n\t\trole?: QtiSectionRole;\n\t\tdisabled?: boolean;\n\t\ti18n?: I18nProvider;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\tpci?: PciConfiguration;\n\t\tpnp?: PnpProfile;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t\tonResponseChange?: (itemIdentifier: string, responseIdentifier: string, value: unknown) => void;\n\t\tonFrameworkError?: (error: QtiSectionFrameworkError) => void;\n\t}\n\n\tconst {\n\t\titemRef,\n\t\tresponses,\n\t\trole = 'candidate',\n\t\tdisabled = false,\n\t\ti18n,\n\t\tsecurity,\n\t\tpci,\n\t\tpnp,\n\t\ttypeset,\n\t\tonResponseChange,\n\t\tonFrameworkError,\n\t}: Props = $props();\n\n\tlet playerLoaded = $state(false);\n\tlet errorMessage = $state<string | null>(null);\n\tlet itemScopeElement = $state<HTMLElement | null>(null);\n\tconst itemTitle = $derived(itemRef.title ?? 'Question');\n\tconst hasHeaderTools = $derived((itemRef.tools?.length ?? 0) > 0);\n\tconst interactionSpeechHtml = $derived(\n\t\textractReadableInteractionSpeechHtml(itemRef.itemXml, { security }),\n\t);\n\n\tasync function loadItemPlayerElement() {\n\t\tif (!customElements.get('pie-qti-item-player')) {\n\t\t\tawait import('@pie-qti/item-player/element');\n\t\t}\n\t\tawait customElements.whenDefined('pie-qti-item-player');\n\t}\n\n\tonMount(() => {\n\t\tlet cancelled = false;\n\t\tvoid loadItemPlayerElement()\n\t\t\t.then(() => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tplayerLoaded = true;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : 'Unable to load the QTI item player.';\n\t\t\t\t\terrorMessage = message;\n\t\t\t\t\tonFrameworkError?.({\n\t\t\t\t\t\titemIdentifier: itemRef.identifier,\n\t\t\t\t\t\tcode: 'item-player-load-failed',\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t});\n\n\tfunction handleResponseChange(responseIdentifier: string, value: unknown) {\n\t\tonResponseChange?.(itemRef.identifier, responseIdentifier, value);\n\t}\n\n\tfunction itemPlayerProps(node: HTMLElement, props: Record<string, unknown>) {\n\t\tconst handleItemPlayerResponseChange = (event: Event) => {\n\t\t\tconst { responseId, value } = (event as ItemPlayerResponseChangeEvent).detail;\n\t\t\thandleResponseChange(responseId, value);\n\t\t};\n\n\t\tnode.addEventListener('response-change', handleItemPlayerResponseChange);\n\t\tassignProps(node, props);\n\n\t\treturn {\n\t\t\tupdate(next: Record<string, unknown>) {\n\t\t\t\tassignProps(node, next);\n\t\t\t},\n\t\t\tdestroy() {\n\t\t\t\tnode.removeEventListener('response-change', handleItemPlayerResponseChange);\n\t\t\t},\n\t\t};\n\t}\n\n</script>\n\n{#if errorMessage}\n\t<div class=\"alert alert-error\" role=\"alert\">\n\t\t<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"stroke-current shrink-0 h-6 w-6\" fill=\"none\" viewBox=\"0 0 24 24\" aria-hidden=\"true\">\n\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z\" />\n\t\t</svg>\n\t\t<span>{i18n?.t('item.loadError', 'Error loading item: {error}', { error: errorMessage })}</span>\n\t</div>\n{:else if !itemRef.itemXml}\n\t<div class=\"alert alert-error\" role=\"alert\">\n\t\t<span>{i18n?.t('item.loadingError') ?? 'No item XML provided'}</span>\n\t</div>\n{:else if !playerLoaded}\n\t<div class=\"flex items-center justify-center p-8\" role=\"status\">\n\t\t<span class=\"loading loading-spinner loading-lg\" aria-hidden=\"true\"></span>\n\t\t<span class=\"ml-4\">{i18n?.t('item.loading', 'Loading item...')}</span>\n\t</div>\n{:else}\n\t<article class=\"item-container\" aria-labelledby={itemRef.title || hasHeaderTools ? `section-item-title-${itemRef.identifier}` : undefined}>\n\t\t{#if itemRef.title || hasHeaderTools}\n\t\t\t<header class=\"item-header\">\n\t\t\t\t<h3 id={`section-item-title-${itemRef.identifier}`} class=\"text-lg font-semibold\">{itemTitle}</h3>\n\t\t\t\t<QtiToolButtonBar\n\t\t\t\t\ttools={itemRef.tools}\n\t\t\t\t\tscopeId={itemRef.identifier}\n\t\t\t\t\tscopeLabel=\"question\"\n\t\t\t\t\tsourceXml={itemRef.itemXml}\n\t\t\t\t\tscopeElement={itemScopeElement}\n\t\t\t\t/>\n\t\t\t</header>\n\t\t{/if}\n\n\t\t<div class=\"item-content\" bind:this={itemScopeElement}>\n\t\t\t<pie-qti-item-player\n\t\t\t\tuse:itemPlayerProps={{\n\t\t\t\t\tsession: itemRef.session,\n\t\t\t\t\tresponses: itemRef.session ? undefined : (responses ?? itemRef.responses ?? {}),\n\t\t\t\t\tdeliveryContext: itemRef.deliveryContext,\n\t\t\t\t\titemXml: itemRef.itemXml,\n\t\t\t\t\tsecurity,\n\t\t\t\t\tpci,\n\t\t\t\t\tpnp,\n\t\t\t\t\trole,\n\t\t\t\t\tdisabled,\n\t\t\t\t\ttypeset,\n\t\t\t\t\ti18n,\n\t\t\t\t}}\n\t\t\t></pie-qti-item-player>\n\t\t\t{#if interactionSpeechHtml}\n\t\t\t\t<div class=\"qti-tts-interaction-projection\" data-qti-tts-readable-projection>\n\t\t\t\t\t{@html interactionSpeechHtml}\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t</div>\n\t</article>\n{/if}\n\n<style>\n\t.item-container {\n\t\twidth: 100%;\n\t\tpadding: 1rem;\n\t}\n\n\t.item-header {\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tjustify-content: space-between;\n\t\tgap: 1rem;\n\t\tmargin-bottom: 1rem;\n\t}\n\n\t.item-content {\n\t\twidth: 100%;\n\t\tposition: relative;\n\t}\n\n\t.qti-tts-interaction-projection {\n\t\tposition: absolute;\n\t\tleft: -10000px;\n\t\ttop: 0;\n\t\twidth: 1px;\n\t\topacity: 0.01;\n\t\tpointer-events: none;\n\t}\n</style>\n","<script lang=\"ts\">\n\timport { onMount, type Snippet } from 'svelte';\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\n\tinterface Props {\n\t\ti18n?: I18nProvider;\n\t\tstorageKey?: string;\n\t\tleftPane?: Snippet;\n\t\tchildren?: Snippet;\n\t\tonRightPaneReady?: (element: HTMLElement) => void;\n\t}\n\n\tconst {\n\t\ti18n,\n\t\tstorageKey = 'pie-qti22-assessment-player.splitLeftPct',\n\t\tleftPane,\n\t\tchildren,\n\t\tonRightPaneReady,\n\t}: Props = $props();\n\n\tconst minLeftPct = 25;\n\tconst maxLeftPct = 75;\n\tconst initialSplitPct = 50;\n\n\tlet splitContainerEl = $state<HTMLDivElement | null>(null);\n\tlet rightPaneEl = $state<HTMLElement | null>(null);\n\tlet reportedRightPaneEl = $state<HTMLElement | null>(null);\n\tlet splitLeftPct = $state<number>(50);\n\tlet isResizing = $state(false);\n\tlet hasInitializedFromProps = $state(false);\n\n\tfunction clampPct(pct: number) {\n\t\treturn Math.min(maxLeftPct, Math.max(minLeftPct, pct));\n\t}\n\n\tfunction saveSplitPct(pct: number) {\n\t\ttry {\n\t\t\tif (typeof window === 'undefined') return;\n\t\t\twindow.localStorage.setItem(storageKey, String(pct));\n\t\t} catch {\n\t\t\t// Ignore persistence failures in restricted browser contexts.\n\t\t}\n\t}\n\n\tfunction loadSplitPct() {\n\t\ttry {\n\t\t\tif (typeof window === 'undefined') return null;\n\t\t\tconst raw = window.localStorage.getItem(storageKey);\n\t\t\tif (!raw) return null;\n\t\t\tconst n = Number(raw);\n\t\t\tif (!Number.isFinite(n)) return null;\n\t\t\treturn clampPct(n);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tfunction updateSplitFromClientX(clientX: number) {\n\t\tif (!splitContainerEl) return;\n\t\tconst rect = splitContainerEl.getBoundingClientRect();\n\t\tif (rect.width <= 0) return;\n\t\tconst x = clientX - rect.left;\n\t\tconst pct = (x / rect.width) * 100;\n\t\tsplitLeftPct = clampPct(pct);\n\t}\n\n\tfunction onSplitterPointerDown(e: PointerEvent) {\n\t\tif (!splitContainerEl) return;\n\t\tisResizing = true;\n\t\t(e.currentTarget as HTMLElement | null)?.setPointerCapture?.(e.pointerId);\n\t\tupdateSplitFromClientX(e.clientX);\n\n\t\tconst move = (ev: PointerEvent) => updateSplitFromClientX(ev.clientX);\n\t\tconst up = () => {\n\t\t\tisResizing = false;\n\t\t\twindow.removeEventListener('pointermove', move);\n\t\t\twindow.removeEventListener('pointerup', up);\n\t\t\twindow.removeEventListener('pointercancel', up);\n\t\t\tsaveSplitPct(splitLeftPct);\n\t\t};\n\n\t\twindow.addEventListener('pointermove', move);\n\t\twindow.addEventListener('pointerup', up, { once: true });\n\t\twindow.addEventListener('pointercancel', up, { once: true });\n\t}\n\n\tfunction onSplitterKeyDown(e: KeyboardEvent) {\n\t\tif (e.key === 'ArrowLeft') {\n\t\t\te.preventDefault();\n\t\t\tsplitLeftPct = clampPct(splitLeftPct - 2);\n\t\t\tsaveSplitPct(splitLeftPct);\n\t\t} else if (e.key === 'ArrowRight') {\n\t\t\te.preventDefault();\n\t\t\tsplitLeftPct = clampPct(splitLeftPct + 2);\n\t\t\tsaveSplitPct(splitLeftPct);\n\t\t} else if (e.key === 'Home') {\n\t\t\te.preventDefault();\n\t\t\tsplitLeftPct = minLeftPct;\n\t\t\tsaveSplitPct(splitLeftPct);\n\t\t} else if (e.key === 'End') {\n\t\t\te.preventDefault();\n\t\t\tsplitLeftPct = maxLeftPct;\n\t\t\tsaveSplitPct(splitLeftPct);\n\t\t}\n\t}\n\n\tfunction splitterInteractions(node: HTMLElement) {\n\t\tconst pointerDown = (e: PointerEvent) => onSplitterPointerDown(e);\n\t\tconst keyDown = (e: KeyboardEvent) => onSplitterKeyDown(e);\n\n\t\tnode.addEventListener('pointerdown', pointerDown);\n\t\tnode.addEventListener('keydown', keyDown);\n\n\t\treturn {\n\t\t\tdestroy() {\n\t\t\t\tnode.removeEventListener('pointerdown', pointerDown);\n\t\t\t\tnode.removeEventListener('keydown', keyDown);\n\t\t\t},\n\t\t};\n\t}\n\n\tonMount(() => {\n\t\tconst loaded = loadSplitPct();\n\t\tif (loaded !== null) splitLeftPct = loaded;\n\t});\n\n\t$effect(() => {\n\t\tif (hasInitializedFromProps) return;\n\t\tsplitLeftPct = clampPct(initialSplitPct);\n\t\thasInitializedFromProps = true;\n\t});\n\n\t$effect(() => {\n\t\tif (rightPaneEl && rightPaneEl !== reportedRightPaneEl) {\n\t\t\treportedRightPaneEl = rightPaneEl;\n\t\t\tonRightPaneReady?.(rightPaneEl);\n\t\t}\n\t});\n</script>\n\n<div\n\tclass:resizing={isResizing}\n\tclass=\"split-layout\"\n\tbind:this={splitContainerEl}\n\tstyle={`--split-left: ${splitLeftPct}%;`}\n>\n\t<section id=\"section-player-left-pane\" class=\"pane pane-left\" aria-label={i18n?.t('sectionPlayer.sharedContext', 'Shared context') ?? 'Shared context'}>\n\t\t{#if leftPane}\n\t\t\t{@render leftPane()}\n\t\t{/if}\n\t</section>\n\n\t<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n\t<div\n\t\tclass=\"splitter\"\n\t\trole=\"separator\"\n\t\taria-orientation=\"vertical\"\n\t\taria-label={i18n?.t('accessibility.resizer', 'Resize passage and question panels')}\n\t\taria-controls=\"section-player-left-pane section-player-right-pane\"\n\t\taria-valuemin={minLeftPct}\n\t\taria-valuemax={maxLeftPct}\n\t\taria-valuenow={Math.round(splitLeftPct)}\n\t\ttabindex=\"0\"\n\t\tuse:splitterInteractions\n\t>\n\t\t<div class=\"splitter-grip\" aria-hidden=\"true\"></div>\n\t</div>\n\n\t<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n\t<section\n\t\tid=\"section-player-right-pane\"\n\t\tclass=\"pane pane-right\"\n\t\ttabindex=\"-1\"\n\t\tbind:this={rightPaneEl}\n\t\taria-label={i18n?.t('sectionPlayer.itemPane', 'Item pane') ?? 'Item pane'}\n\t>\n\t\t{#if children}\n\t\t\t{@render children()}\n\t\t{/if}\n\t</section>\n</div>\n\n<style>\n\t.split-layout {\n\t\tdisplay: grid;\n\t\t--splitter-size: 24px;\n\t\tgrid-template-columns: minmax(320px, var(--split-left)) var(--splitter-size) minmax(320px, 1fr);\n\t\tgap: 0;\n\t\theight: 100%;\n\t\tpadding: 2rem;\n\t\tmax-width: 1400px;\n\t\tmargin: 0 auto;\n\t}\n\n\t.pane {\n\t\tmin-height: 0;\n\t\toverflow: auto;\n\t\tpadding: 0 1rem;\n\t}\n\n\t.pane-right:focus-visible {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: -2px;\n\t}\n\n\t.splitter {\n\t\twidth: var(--splitter-size);\n\t\tcursor: col-resize;\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tjustify-content: center;\n\t\talign-self: stretch;\n\t\tmin-height: 44px;\n\t\theight: 100%;\n\t\tbackground: var(--color-base-200);\n\t\tborder-left: 1px solid var(--color-base-300);\n\t\tborder-right: 1px solid var(--color-base-300);\n\t\tuser-select: none;\n\t\ttouch-action: none;\n\t\tposition: relative;\n\t}\n\n\t.splitter:hover {\n\t\tbackground: var(--color-base-300);\n\t\tborder-left-color: var(--color-base-300);\n\t\tborder-right-color: var(--color-base-300);\n\t}\n\n\t.splitter:focus-visible {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: 2px;\n\t}\n\n\t.splitter::before {\n\t\tcontent: '';\n\t\tposition: absolute;\n\t\ttop: 0;\n\t\tbottom: 0;\n\t\tleft: 50%;\n\t\twidth: 2px;\n\t\ttransform: translateX(-50%);\n\t\tbackground: color-mix(in oklab, var(--color-base-content) 55%, transparent);\n\t}\n\n\t.splitter-grip {\n\t\twidth: 6px;\n\t\theight: 72px;\n\t\tborder-radius: 999px;\n\t\tbackground: linear-gradient(\n\t\t\tto bottom,\n\t\t\tcolor-mix(in oklab, var(--color-base-content) 15%, transparent),\n\t\t\tcolor-mix(in oklab, var(--color-base-content) 55%, transparent),\n\t\t\tcolor-mix(in oklab, var(--color-base-content) 15%, transparent)\n\t\t);\n\t}\n\n\t.split-layout.resizing .splitter {\n\t\tbackground: color-mix(in oklab, var(--color-primary) 14%, transparent);\n\t\tborder-left-color: color-mix(in oklab, var(--color-primary) 60%, transparent);\n\t\tborder-right-color: color-mix(in oklab, var(--color-primary) 60%, transparent);\n\t}\n\n\t.split-layout.resizing {\n\t\tuser-select: none;\n\t}\n\n\t.split-layout :global(.rubric-container) {\n\t\tmargin-bottom: 0;\n\t}\n\n\t@media (max-width: 768px) {\n\t\t.split-layout {\n\t\t\tgrid-template-columns: 1fr;\n\t\t\tpadding: 1rem;\n\t\t}\n\n\t\t.splitter {\n\t\t\tdisplay: none;\n\t\t}\n\n\t\t.pane-left {\n\t\t\tmax-height: 40vh;\n\t\t}\n\t}\n</style>\n","<script lang=\"ts\">\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\timport type { PciConfiguration, PlayerSecurityConfig, PnpProfile } from '@pie-qti/item-player';\n\timport type { QtiSectionFrameworkError, ResolvedQtiSectionComposition } from '../contracts/index.js';\n\timport {\n\t\tnotifyActiveItemChange,\n\t\tnotifyFrameworkError,\n\t\tnotifyResponseDelta,\n\t\tnotifySnapshotChange,\n\t} from '../runtime/notifyRuntimeHost.js';\n\timport ItemRenderer from './ItemRenderer.svelte';\n\timport RubricDisplay from './RubricDisplay.svelte';\n\timport SplitPaneResizer from './SplitPaneResizer.svelte';\n\n\tinterface Props {\n\t\tcomposition: ResolvedQtiSectionComposition;\n\t\ti18n?: I18nProvider;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\tpci?: PciConfiguration;\n\t\tpnp?: PnpProfile;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t\tonResponseChange?: (itemIdentifier: string, responseIdentifier: string, value: unknown) => void;\n\t\tonItemPaneReady?: (element: HTMLElement) => void;\n\t\tonFrameworkError?: (error: QtiSectionFrameworkError) => void;\n\t}\n\n\tconst {\n\t\tcomposition,\n\t\ti18n,\n\t\tsecurity,\n\t\tpci,\n\t\tpnp,\n\t\ttypeset,\n\t\tonResponseChange,\n\t\tonItemPaneReady,\n\t\tonFrameworkError,\n\t}: Props = $props();\n\n\tconst role = $derived(composition.section.role ?? 'candidate');\n\tconst effectiveSecurity = $derived(security ?? composition.security);\n\tconst activeResponses = $derived(\n\t\tcomposition.snapshot.responses[composition.activeItem.identifier] ?? {}\n\t);\n\n\tlet reportedActiveItemKey: string | null = null;\n\tlet reportedSnapshot: ResolvedQtiSectionComposition['snapshot'] | null = null;\n\n\t$effect(() => {\n\t\tconst activeItemKey = `${composition.section.identifier}:${composition.activeItem.identifier}:${composition.activeItemIndex}:${composition.section.itemRefs.length}`;\n\t\tif (activeItemKey !== reportedActiveItemKey) {\n\t\t\treportedActiveItemKey = activeItemKey;\n\t\t\tnotifyActiveItemChange(composition);\n\t\t}\n\t});\n\n\t$effect(() => {\n\t\tif (composition.snapshot !== reportedSnapshot) {\n\t\t\treportedSnapshot = composition.snapshot;\n\t\t\tnotifySnapshotChange(composition);\n\t\t}\n\t});\n\n\tfunction handleResponseChange(itemIdentifier: string, responseIdentifier: string, value: unknown) {\n\t\tnotifyResponseDelta(composition, itemIdentifier, responseIdentifier, value);\n\t\tonResponseChange?.(itemIdentifier, responseIdentifier, value);\n\t}\n\n\tfunction handleFrameworkError(error: QtiSectionFrameworkError) {\n\t\tconst event = notifyFrameworkError(composition, error);\n\t\tonFrameworkError?.(event);\n\t}\n</script>\n\n<SplitPaneResizer storageKey=\"pie-qti22-assessment-player.splitLeftPct\" {i18n} onRightPaneReady={onItemPaneReady}>\n\t{#snippet leftPane()}\n\t\t<RubricDisplay\n\t\t\tpassages={composition.sharedContext.passages}\n\t\t\t{role}\n\t\t\t{i18n}\n\t\t\tsecurity={effectiveSecurity}\n\t\t\thost={composition.host}\n\t\t\t{typeset}\n\t\t/>\n\t{/snippet}\n\n\t<div\n\t\tclass=\"section-player-right-pane\"\n\t\trole=\"region\"\n\t\taria-label={i18n?.t('sectionPlayer.activeItem', 'Active item') ?? 'Active item'}\n\t>\n\t\t<RubricDisplay\n\t\t\trubricBlocks={composition.sharedContext.rubricBlocks}\n\t\t\t{role}\n\t\t\t{i18n}\n\t\t\tsecurity={effectiveSecurity}\n\t\t\thost={composition.host}\n\t\t\t{typeset}\n\t\t/>\n\t\t<ItemRenderer\n\t\t\titemRef={composition.activeItem}\n\t\t\tresponses={activeResponses}\n\t\t\t{role}\n\t\t\tdisabled={role !== 'candidate'}\n\t\t\t{i18n}\n\t\t\tsecurity={effectiveSecurity}\n\t\t\t{pci}\n\t\t\t{pnp}\n\t\t\t{typeset}\n\t\t\tonResponseChange={handleResponseChange}\n\t\t\tonFrameworkError={handleFrameworkError}\n\t\t/>\n\t</div>\n</SplitPaneResizer>\n\n<style>\n\t.section-player-right-pane {\n\t\tmin-height: 100%;\n\t\toutline: none;\n\t}\n\n\t.section-player-right-pane:focus-visible {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: 2px;\n\t}\n</style>\n","<script lang=\"ts\">\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\timport type { PciConfiguration, PlayerSecurityConfig, PnpProfile } from '@pie-qti/item-player';\n\timport type { QtiSectionFrameworkError, ResolvedQtiSectionComposition } from '../contracts/index.js';\n\timport {\n\t\tnotifyActiveItemChange,\n\t\tnotifyFrameworkError,\n\t\tnotifyResponseDelta,\n\t\tnotifySnapshotChange,\n\t} from '../runtime/notifyRuntimeHost.js';\n\timport ItemRenderer from './ItemRenderer.svelte';\n\timport RubricDisplay from './RubricDisplay.svelte';\n\n\tinterface Props {\n\t\tcomposition: ResolvedQtiSectionComposition;\n\t\ti18n?: I18nProvider;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\tpci?: PciConfiguration;\n\t\tpnp?: PnpProfile;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t\tonResponseChange?: (itemIdentifier: string, responseIdentifier: string, value: unknown) => void;\n\t\tonItemPaneReady?: (element: HTMLElement) => void;\n\t\tonFrameworkError?: (error: QtiSectionFrameworkError) => void;\n\t}\n\n\tconst {\n\t\tcomposition,\n\t\ti18n,\n\t\tsecurity,\n\t\tpci,\n\t\tpnp,\n\t\ttypeset,\n\t\tonResponseChange,\n\t\tonItemPaneReady,\n\t\tonFrameworkError,\n\t}: Props = $props();\n\n\tconst role = $derived(composition.section.role ?? 'candidate');\n\tconst effectiveSecurity = $derived(security ?? composition.security);\n\tconst activeResponses = $derived(\n\t\tcomposition.snapshot.responses[composition.activeItem.identifier] ?? {}\n\t);\n\n\tlet itemPaneElement = $state<HTMLElement | null>(null);\n\tlet reportedItemPaneElement: HTMLElement | null = null;\n\tlet reportedActiveItemKey: string | null = null;\n\tlet reportedSnapshot: ResolvedQtiSectionComposition['snapshot'] | null = null;\n\n\t$effect(() => {\n\t\tif (itemPaneElement && itemPaneElement !== reportedItemPaneElement) {\n\t\t\treportedItemPaneElement = itemPaneElement;\n\t\t\tonItemPaneReady?.(itemPaneElement);\n\t\t}\n\t});\n\n\t$effect(() => {\n\t\tconst activeItemKey = `${composition.section.identifier}:${composition.activeItem.identifier}:${composition.activeItemIndex}:${composition.section.itemRefs.length}`;\n\t\tif (activeItemKey !== reportedActiveItemKey) {\n\t\t\treportedActiveItemKey = activeItemKey;\n\t\t\tnotifyActiveItemChange(composition);\n\t\t}\n\t});\n\n\t$effect(() => {\n\t\tif (composition.snapshot !== reportedSnapshot) {\n\t\t\treportedSnapshot = composition.snapshot;\n\t\t\tnotifySnapshotChange(composition);\n\t\t}\n\t});\n\n\tfunction handleResponseChange(itemIdentifier: string, responseIdentifier: string, value: unknown) {\n\t\tnotifyResponseDelta(composition, itemIdentifier, responseIdentifier, value);\n\t\tonResponseChange?.(itemIdentifier, responseIdentifier, value);\n\t}\n\n\tfunction handleFrameworkError(error: QtiSectionFrameworkError) {\n\t\tconst event = notifyFrameworkError(composition, error);\n\t\tonFrameworkError?.(event);\n\t}\n</script>\n\n<div class=\"section-player-vertical\">\n\t<RubricDisplay\n\t\tpassages={composition.sharedContext.passages}\n\t\t{role}\n\t\t{i18n}\n\t\tsecurity={effectiveSecurity}\n\t\thost={composition.host}\n\t\t{typeset}\n\t/>\n\n\t<div\n\t\tclass=\"section-player-item-pane\"\n\t\ttabindex=\"-1\"\n\t\tbind:this={itemPaneElement}\n\t\trole=\"region\"\n\t\taria-label={i18n?.t('sectionPlayer.activeItem', 'Active item') ?? 'Active item'}\n\t>\n\t\t<RubricDisplay\n\t\t\trubricBlocks={composition.sharedContext.rubricBlocks}\n\t\t\t{role}\n\t\t\t{i18n}\n\t\t\tsecurity={effectiveSecurity}\n\t\t\thost={composition.host}\n\t\t\t{typeset}\n\t\t/>\n\t\t<ItemRenderer\n\t\t\titemRef={composition.activeItem}\n\t\t\tresponses={activeResponses}\n\t\t\t{role}\n\t\t\tdisabled={role !== 'candidate'}\n\t\t\t{i18n}\n\t\t\tsecurity={effectiveSecurity}\n\t\t\t{pci}\n\t\t\t{pnp}\n\t\t\t{typeset}\n\t\t\tonResponseChange={handleResponseChange}\n\t\t\tonFrameworkError={handleFrameworkError}\n\t\t/>\n\t</div>\n</div>\n\n<style>\n\t.section-player-vertical {\n\t\twidth: 100%;\n\t\tmax-width: 960px;\n\t\tmargin: 0 auto;\n\t\tpadding: 2rem;\n\t}\n\n\t.section-player-item-pane {\n\t\toutline: none;\n\t}\n\n\t.section-player-item-pane:focus-visible {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: 2px;\n\t}\n\n\t@media (max-width: 768px) {\n\t\t.section-player-vertical {\n\t\t\tpadding: 1rem;\n\t\t}\n\t}\n</style>\n","<script lang=\"ts\">\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\timport type { PlayerSecurityConfig } from '@pie-qti/item-player';\n\timport type { QtiSectionRole, QtiSectionRuntimeHostContract, QtiSharedHtmlBlock } from '../contracts/index.js';\n\timport { isQtiViewVisibleForRole } from '../visibility/role-view.js';\n\timport SanitizedHtml from './SanitizedHtml.svelte';\n\n\tinterface Props {\n\t\tfeedback?: QtiSharedHtmlBlock[];\n\t\trole?: QtiSectionRole;\n\t\ti18n?: I18nProvider;\n\t\tsecurity?: PlayerSecurityConfig;\n\t\thost?: QtiSectionRuntimeHostContract;\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t}\n\n\tconst { feedback = [], role = 'candidate', i18n, security, host, typeset }: Props = $props();\n\tconst visibleFeedback = $derived(feedback.filter((item) => isQtiViewVisibleForRole(item.view, role)));\n</script>\n\n{#if visibleFeedback.length > 0}\n\t<section class=\"test-feedback\" aria-live=\"polite\" aria-label={i18n?.t('feedback.testFeedback') ?? 'Test feedback'}>\n\t\t{#each visibleFeedback as item (item.identifier)}\n\t\t\t<SanitizedHtml\n\t\t\t\trawHtml={item.rawHtml}\n\t\t\t\thtml={item.html}\n\t\t\t\t{security}\n\t\t\t\t{host}\n\t\t\t\tsanitizeContext={{ kind: 'test-feedback', source: item.source }}\n\t\t\t\tclass=\"test-feedback-content\"\n\t\t\t\t{typeset}\n\t\t\t/>\n\t\t{/each}\n\t</section>\n{/if}\n\n<style>\n\t.test-feedback {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 1rem;\n\t\tmargin: 1rem 0;\n\t}\n\n\t:global(.test-feedback-content) {\n\t\tpadding: 1rem;\n\t\tborder-radius: 0.5rem;\n\t\tbackground-color: var(--feedback-bg, #f0f9ff);\n\t\tborder: 1px solid var(--feedback-border, #0ea5e9);\n\t\tcolor: var(--feedback-text, #0c4a6e);\n\t\tline-height: 1.6;\n\t\tbox-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);\n\t}\n\n\t:global(.test-feedback-content p) {\n\t\tmargin: 0 0 0.5rem 0;\n\t}\n\n\t:global(.test-feedback-content p:last-child) {\n\t\tmargin-bottom: 0;\n\t}\n</style>\n","/**\n * ItemSessionController\n *\n * Manages QTI itemSessionControl rules for individual items.\n * Enforces attempt limits, feedback visibility, review/skip controls, and validation.\n *\n * QTI 2.2 itemSessionControl attributes:\n * - maxAttempts: Maximum number of submission attempts (0 = unlimited)\n * - showFeedback: Whether to show feedback after responses\n * - showSolution: Whether to show correct answers\n * - allowReview: Allow returning to already-answered items\n * - allowSkipping: Allow skipping items without answering\n * - validateResponses: Require valid responses before moving on\n * - allowComment: Allow candidate comments (not implemented yet)\n */\n\nexport interface ItemSessionControlSettings {\n\tmaxAttempts?: number; // 0 = unlimited\n\tshowFeedback?: boolean;\n\tallowReview?: boolean;\n\tshowSolution?: boolean;\n\tallowComment?: boolean;\n\tallowSkipping?: boolean;\n\tvalidateResponses?: boolean;\n}\n\nexport interface ItemSessionState {\n\titemIdentifier: string;\n\tattemptCount: number;\n\tisAnswered: boolean;\n\tisSubmitted: boolean;\n\tlastSubmissionTime?: number;\n}\n\nexport class ItemSessionController {\n\tprivate settings: ItemSessionControlSettings;\n\tprivate sessionStates: Map<string, ItemSessionState> = new Map();\n\n\tconstructor(settings: ItemSessionControlSettings = {}) {\n\t\t// Apply defaults per QTI 2.2 spec\n\t\tthis.settings = {\n\t\t\tmaxAttempts: settings.maxAttempts ?? 0, // 0 = unlimited\n\t\t\tshowFeedback: settings.showFeedback ?? false,\n\t\t\tallowReview: settings.allowReview ?? true,\n\t\t\tshowSolution: settings.showSolution ?? false,\n\t\t\tallowComment: settings.allowComment ?? false,\n\t\t\tallowSkipping: settings.allowSkipping ?? true,\n\t\t\tvalidateResponses: settings.validateResponses ?? false,\n\t\t};\n\t}\n\n\t/**\n\t * Initialize session state for an item\n\t */\n\tinitializeItem(itemIdentifier: string): void {\n\t\tif (!this.sessionStates.has(itemIdentifier)) {\n\t\t\tthis.sessionStates.set(itemIdentifier, {\n\t\t\t\titemIdentifier,\n\t\t\t\tattemptCount: 0,\n\t\t\t\tisAnswered: false,\n\t\t\t\tisSubmitted: false,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Get session state for an item\n\t */\n\tgetItemState(itemIdentifier: string): ItemSessionState | null {\n\t\treturn this.sessionStates.get(itemIdentifier) ?? null;\n\t}\n\n\t/**\n\t * Record a submission attempt for an item\n\t */\n\trecordAttempt(itemIdentifier: string): void {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state) {\n\t\t\tthrow new Error(`Item session not initialized: ${itemIdentifier}`);\n\t\t}\n\n\t\tstate.attemptCount++;\n\t\tstate.isSubmitted = true;\n\t\tstate.lastSubmissionTime = Date.now();\n\t}\n\n\t/**\n\t * Mark item as answered (has responses)\n\t */\n\tmarkAnswered(itemIdentifier: string, hasResponses: boolean): void {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (state) {\n\t\t\tstate.isAnswered = hasResponses;\n\t\t}\n\t}\n\n\t/**\n\t * Check if item can be submitted\n\t */\n\tcanSubmit(itemIdentifier: string): boolean {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Check maxAttempts\n\t\tconst maxAttempts = this.settings.maxAttempts ?? 0;\n\t\tif (maxAttempts > 0 && state.attemptCount >= maxAttempts) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Get remaining attempts for an item\n\t */\n\tgetRemainingAttempts(itemIdentifier: string): number | null {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst maxAttempts = this.settings.maxAttempts ?? 0;\n\t\tif (maxAttempts === 0) {\n\t\t\treturn null; // Unlimited\n\t\t}\n\n\t\treturn Math.max(0, maxAttempts - state.attemptCount);\n\t}\n\n\t/**\n\t * Check if feedback should be shown for an item\n\t */\n\tshouldShowFeedback(itemIdentifier: string): boolean {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state || !state.isSubmitted) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.settings.showFeedback ?? false;\n\t}\n\n\t/**\n\t * Check if solution should be shown for an item\n\t */\n\tshouldShowSolution(itemIdentifier: string): boolean {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state || !state.isSubmitted) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.settings.showSolution ?? false;\n\t}\n\n\t/**\n\t * Check if candidate can navigate to a previously answered item\n\t */\n\tcanReview(itemIdentifier: string): boolean {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state || !state.isSubmitted) {\n\t\t\treturn true; // Can always navigate to unsubmitted items\n\t\t}\n\n\t\treturn this.settings.allowReview ?? true;\n\t}\n\n\t/**\n\t * Check if candidate can skip an item without answering\n\t */\n\tcanSkip(_itemIdentifier: string): boolean {\n\t\treturn this.settings.allowSkipping ?? true;\n\t}\n\n\t/**\n\t * Check if responses must be validated before navigation\n\t */\n\tmustValidateResponses(): boolean {\n\t\treturn this.settings.validateResponses ?? false;\n\t}\n\n\t/**\n\t * Validate that an item has valid responses (if validation is required)\n\t */\n\tvalidateItem(itemIdentifier: string, hasValidResponses: boolean): {\n\t\tisValid: boolean;\n\t\terror?: string;\n\t} {\n\t\tif (!this.mustValidateResponses()) {\n\t\t\treturn { isValid: true };\n\t\t}\n\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state) {\n\t\t\treturn { isValid: true };\n\t\t}\n\n\t\t// If item is required and has no valid responses, fail validation\n\t\tif (!hasValidResponses) {\n\t\t\treturn {\n\t\t\t\tisValid: false,\n\t\t\t\terror: 'This item requires a valid response before continuing.',\n\t\t\t};\n\t\t}\n\n\t\treturn { isValid: true };\n\t}\n\n\t/**\n\t * Check if navigation away from current item is allowed\n\t */\n\tcanNavigateAway(itemIdentifier: string, hasValidResponses: boolean): {\n\t\tallowed: boolean;\n\t\treason?: string;\n\t} {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (!state) {\n\t\t\treturn { allowed: true };\n\t\t}\n\n\t\t// Check if skipping is allowed when item is unanswered\n\t\tif (!state.isAnswered && !this.canSkip(itemIdentifier)) {\n\t\t\treturn {\n\t\t\t\tallowed: false,\n\t\t\t\treason: 'You must answer this item before continuing.',\n\t\t\t};\n\t\t}\n\n\t\t// Check validation requirements\n\t\tif (this.mustValidateResponses() && state.isAnswered && !hasValidResponses) {\n\t\t\treturn {\n\t\t\t\tallowed: false,\n\t\t\t\treason: 'Please provide valid responses before continuing.',\n\t\t\t};\n\t\t}\n\n\t\treturn { allowed: true };\n\t}\n\n\t/**\n\t * Get full settings\n\t */\n\tgetSettings(): ItemSessionControlSettings {\n\t\treturn { ...this.settings };\n\t}\n\n\t/**\n\t * Update settings (useful for different sections with different controls)\n\t */\n\tupdateSettings(settings: Partial<ItemSessionControlSettings>): void {\n\t\tthis.settings = { ...this.settings, ...settings };\n\t}\n\n\t/**\n\t * Get all session states (for persistence)\n\t */\n\tgetAllStates(): Map<string, ItemSessionState> {\n\t\treturn new Map(this.sessionStates);\n\t}\n\n\t/**\n\t * Restore session states (from persistence)\n\t */\n\trestoreStates(states: Map<string, ItemSessionState>): void {\n\t\tthis.sessionStates = new Map(states);\n\t}\n\n\t/**\n\t * Reset session state for an item (useful for practice/retry scenarios)\n\t */\n\tresetItem(itemIdentifier: string): void {\n\t\tconst state = this.sessionStates.get(itemIdentifier);\n\t\tif (state) {\n\t\t\tstate.attemptCount = 0;\n\t\t\tstate.isAnswered = false;\n\t\t\tstate.isSubmitted = false;\n\t\t\tstate.lastSubmissionTime = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Clear all session states\n\t */\n\tclear(): void {\n\t\tthis.sessionStates.clear();\n\t}\n}\n","import type { SerializedItemSessionState } from '@pie-qti/item-player';\nimport type { AssessmentSessionState } from '../integration/api-contract.js';\nimport type { ItemResult } from '../types/index.js';\nimport {\n\tItemSessionController,\n\ttype ItemSessionControlSettings,\n\ttype ItemSessionState,\n} from './ItemSessionController.js';\n\nexport interface AssessmentSessionCoordinatorOptions {\n\tstate: AssessmentSessionState;\n\titemIdentifiers: string[];\n\titemSessionControl?: ItemSessionControlSettings;\n}\n\nexport interface ItemSessionInfo {\n\tcanSubmit: boolean;\n\tremainingAttempts: number | null;\n\tattemptCount: number;\n\tshowFeedback: boolean;\n\tshowSolution: boolean;\n\tcanReview: boolean;\n\tcanSkip: boolean;\n}\n\nexport class AssessmentSessionCoordinator {\n\t#state: AssessmentSessionState;\n\t#sessionController: ItemSessionController;\n\t#itemResults = new Map<string, ItemResult>();\n\t#itemIdentifiers: string[];\n\n\tconstructor({ state, itemIdentifiers, itemSessionControl }: AssessmentSessionCoordinatorOptions) {\n\t\tthis.#state = state;\n\t\tthis.#itemIdentifiers = itemIdentifiers;\n\t\tthis.#sessionController = new ItemSessionController(itemSessionControl);\n\t\tthis.#initializeItemSessions();\n\t\tthis.#restoreItemSessionsFromState(state);\n\t\tthis.#restoreItemResultsFromScores(state);\n\t}\n\n\tget state() {\n\t\treturn this.#state;\n\t}\n\n\trestoreState(state: AssessmentSessionState): void {\n\t\tthis.#state = state;\n\t\tthis.#restoreItemSessionsFromState(state);\n\t\tthis.#restoreItemResultsFromScores(state);\n\t}\n\n\tsnapshot(options: { includeItemSessions?: boolean } = {}): AssessmentSessionState {\n\t\treturn {\n\t\t\t...this.#state,\n\t\t\tvisitedItems: [...this.#state.visitedItems],\n\t\t\titemResponses: { ...this.#state.itemResponses },\n\t\t\titemScores: this.#state.itemScores ? { ...this.#state.itemScores } : undefined,\n\t\t\titemSessions:\n\t\t\t\toptions.includeItemSessions && this.#state.itemSessions\n\t\t\t\t\t? { ...this.#state.itemSessions }\n\t\t\t\t\t: undefined,\n\t\t\titemSessionStates: this.#itemSessionStateSnapshot(),\n\t\t\ttiming: {\n\t\t\t\t...this.#state.timing,\n\t\t\t\titemTimes: { ...this.#state.timing.itemTimes },\n\t\t\t\tsectionTimes: this.#state.timing.sectionTimes\n\t\t\t\t\t? { ...this.#state.timing.sectionTimes }\n\t\t\t\t\t: undefined,\n\t\t\t\ttestPartTimes: this.#state.timing.testPartTimes\n\t\t\t\t\t? { ...this.#state.timing.testPartTimes }\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t};\n\t}\n\n\tactivateItem(itemIdentifier: string): Record<string, unknown> {\n\t\tthis.#state.currentItemIdentifier = itemIdentifier;\n\t\treturn this.getResponses(itemIdentifier);\n\t}\n\n\tgetActiveResponses(): Record<string, unknown> {\n\t\treturn this.getResponses(this.#state.currentItemIdentifier);\n\t}\n\n\tgetResponses(itemIdentifier: string): Record<string, unknown> {\n\t\treturn { ...((this.#state.itemResponses?.[itemIdentifier] || {}) as Record<string, unknown>) };\n\t}\n\n\tgetPersistedItemSession(itemIdentifier: string): SerializedItemSessionState | undefined {\n\t\treturn this.#state.itemSessions?.[itemIdentifier];\n\t}\n\n\tupdateActiveResponse(responseId: string, value: unknown): Record<string, unknown> {\n\t\treturn this.updateResponseForItem(this.#state.currentItemIdentifier, responseId, value);\n\t}\n\n\tupdateResponseForItem(\n\t\titemIdentifier: string,\n\t\tresponseId: string,\n\t\tvalue: unknown\n\t): Record<string, unknown> {\n\t\tconst next = {\n\t\t\t...((this.#state.itemResponses?.[itemIdentifier] || {}) as Record<string, unknown>),\n\t\t\t[responseId]: value,\n\t\t};\n\t\tthis.#state.itemResponses[itemIdentifier] = next as any;\n\t\tthis.markAnswered(itemIdentifier, next);\n\t\treturn next;\n\t}\n\n\tsaveItemSession(\n\t\titemIdentifier: string,\n\t\tresponses: Record<string, unknown>,\n\t\tsessionState: SerializedItemSessionState,\n\t\tduration: number\n\t): void {\n\t\tthis.#state.itemSessions = {\n\t\t\t...(this.#state.itemSessions ?? {}),\n\t\t\t[itemIdentifier]: sessionState,\n\t\t};\n\t\tthis.#state.itemResponses[itemIdentifier] = responses as any;\n\t\tthis.#state.timing.itemTimes[itemIdentifier] = duration;\n\t\tthis.markAnswered(itemIdentifier, responses);\n\t}\n\n\tsetItemSession(itemIdentifier: string, sessionState: SerializedItemSessionState): void {\n\t\tthis.#state.itemSessions = {\n\t\t\t...(this.#state.itemSessions ?? {}),\n\t\t\t[itemIdentifier]: sessionState,\n\t\t};\n\t}\n\n\tmergeItemSessions(itemSessions: AssessmentSessionState['itemSessions']): void {\n\t\tif (!itemSessions) return;\n\t\tthis.#state.itemSessions = {\n\t\t\t...(this.#state.itemSessions ?? {}),\n\t\t\t...itemSessions,\n\t\t};\n\t}\n\n\treplaceStatePreservingItemSessions(updatedState: AssessmentSessionState): void {\n\t\tconst localItemSessions = this.#state.itemSessions;\n\t\tthis.restoreState(updatedState);\n\t\tthis.mergeItemSessions(localItemSessions);\n\t}\n\n\treplaceStatePreservingResponsesAndSessions(\n\t\tupdatedState: AssessmentSessionState,\n\t\titemResponses: AssessmentSessionState['itemResponses'],\n\t\titemSessions: AssessmentSessionState['itemSessions']\n\t): void {\n\t\tthis.restoreState(updatedState);\n\t\t// Own the accepted snapshots rather than retaining the submit loop's mutable\n\t\t// working maps. Later provisional items must not appear committed until their\n\t\t// backend request succeeds.\n\t\tthis.#state.itemResponses = { ...itemResponses };\n\t\tthis.#state.itemSessions = itemSessions ? { ...itemSessions } : undefined;\n\t}\n\n\tmarkVisited(itemIdentifier: string): void {\n\t\tif (!this.#state.visitedItems.includes(itemIdentifier)) {\n\t\t\tthis.#state.visitedItems.push(itemIdentifier);\n\t\t}\n\t}\n\n\tmarkAnswered(itemIdentifier: string, responses: Record<string, unknown>): void {\n\t\tthis.#sessionController.markAnswered(itemIdentifier, hasAnyResponse(responses));\n\t}\n\n\tcanReview(itemIdentifier: string): boolean {\n\t\treturn this.#sessionController.canReview(itemIdentifier);\n\t}\n\n\tcanNavigateAway(\n\t\titemIdentifier: string,\n\t\tresponses: Record<string, unknown>\n\t): { allowed: boolean; reason?: string } {\n\t\treturn this.#sessionController.canNavigateAway(itemIdentifier, hasAnyResponse(responses));\n\t}\n\n\tupdateItemSessionControl(settings: ItemSessionControlSettings): void {\n\t\tthis.#sessionController.updateSettings(settings);\n\t}\n\n\tmustValidateResponses(): boolean {\n\t\treturn this.#sessionController.mustValidateResponses();\n\t}\n\n\trecordAttempt(itemIdentifier: string): void {\n\t\tthis.#sessionController.recordAttempt(itemIdentifier);\n\t}\n\n\tsetItemResult(itemResult: ItemResult): void {\n\t\tthis.#itemResults.set(itemResult.itemIdentifier, itemResult);\n\t}\n\n\thasItemResult(itemIdentifier: string): boolean {\n\t\treturn this.#itemResults.has(itemIdentifier);\n\t}\n\n\tgetItemSessionInfo(itemIdentifier: string): ItemSessionInfo {\n\t\tif (!this.#sessionController.getItemState(itemIdentifier)) {\n\t\t\tthis.#sessionController.initializeItem(itemIdentifier);\n\t\t}\n\t\tconst state = this.#sessionController.getItemState(itemIdentifier);\n\t\treturn {\n\t\t\tcanSubmit: this.#sessionController.canSubmit(itemIdentifier),\n\t\t\tremainingAttempts: this.#sessionController.getRemainingAttempts(itemIdentifier),\n\t\t\tattemptCount: state?.attemptCount ?? 0,\n\t\t\tshowFeedback: this.#sessionController.shouldShowFeedback(itemIdentifier),\n\t\t\tshowSolution: this.#sessionController.shouldShowSolution(itemIdentifier),\n\t\t\tcanReview: this.#sessionController.canReview(itemIdentifier),\n\t\t\tcanSkip: this.#sessionController.canSkip(itemIdentifier),\n\t\t};\n\t}\n\n\t#initializeItemSessions(): void {\n\t\tfor (const itemIdentifier of this.#itemIdentifiers) {\n\t\t\tthis.#sessionController.initializeItem(itemIdentifier);\n\t\t}\n\t}\n\n\t#restoreItemSessionsFromState(state: AssessmentSessionState): void {\n\t\tconst restoredStates = new Map<string, ItemSessionState>();\n\t\tfor (const itemIdentifier of this.#itemIdentifiers) {\n\t\t\tconst persisted = state.itemSessionStates?.[itemIdentifier];\n\t\t\tif (persisted) {\n\t\t\t\trestoredStates.set(itemIdentifier, {\n\t\t\t\t\titemIdentifier,\n\t\t\t\t\tattemptCount: Math.max(0, persisted.attemptCount),\n\t\t\t\t\tisAnswered: persisted.isAnswered,\n\t\t\t\t\tisSubmitted: persisted.isSubmitted,\n\t\t\t\t\tlastSubmissionTime: persisted.lastSubmissionTime,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst responses = state.itemResponses?.[itemIdentifier] ?? {};\n\t\t\tconst isSubmitted = Boolean(state.itemScores?.[itemIdentifier]);\n\t\t\trestoredStates.set(itemIdentifier, {\n\t\t\t\titemIdentifier,\n\t\t\t\tattemptCount: isSubmitted ? 1 : 0,\n\t\t\t\tisAnswered: hasAnyResponse(responses),\n\t\t\t\tisSubmitted,\n\t\t\t});\n\t\t}\n\t\tthis.#sessionController.restoreStates(restoredStates);\n\t}\n\n\t#restoreItemResultsFromScores(state: AssessmentSessionState): void {\n\t\tthis.#itemResults.clear();\n\t\tif (!state.itemScores) return;\n\t\tfor (const [itemIdentifier, scoring] of Object.entries(state.itemScores)) {\n\t\t\tthis.#itemResults.set(itemIdentifier, {\n\t\t\t\titemIdentifier,\n\t\t\t\tscore: scoring.score,\n\t\t\t\tmaxScore: scoring.maxScore,\n\t\t\t\tresponses: state.itemResponses?.[itemIdentifier] || {},\n\t\t\t});\n\t\t}\n\t}\n\n\t#itemSessionStateSnapshot(): Record<string, ItemSessionState> {\n\t\treturn Object.fromEntries(\n\t\t\t[...this.#sessionController.getAllStates().entries()].map(([itemIdentifier, state]) => [\n\t\t\t\titemIdentifier,\n\t\t\t\t{ ...state },\n\t\t\t])\n\t\t);\n\t}\n}\n\nfunction hasAnyResponse(responses: Record<string, unknown>): boolean {\n\tfor (const value of Object.values(responses)) {\n\t\tif (value == null) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) return true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\tif (value.trim().length > 0) return true;\n\t\t\tcontinue;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n","/**\n * NavigationManager\n *\n * Handles navigation logic for linear and nonlinear assessment modes.\n * - Linear: Sequential forward navigation only; once left, an item cannot be revisited\n * - Nonlinear: Free navigation (can jump to any item)\n */\n\nexport type NavigationMode = 'linear' | 'nonlinear';\n\nexport class NavigationManager {\n\tprivate mode: NavigationMode;\n\tprivate totalItems: number;\n\tprivate visitedItems: Set<number>;\n\n\tconstructor(mode: NavigationMode, totalItems: number) {\n\t\tthis.mode = mode;\n\t\tthis.totalItems = totalItems;\n\t\tthis.visitedItems = new Set<number>();\n\t}\n\n\t/**\n\t * Check if navigation to a specific index is allowed\n\t */\n\tcanNavigateTo(targetIndex: number, currentIndex: number): boolean {\n\t\t// Out of bounds check\n\t\tif (targetIndex < 0 || targetIndex >= this.totalItems) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// In nonlinear mode, can navigate anywhere\n\t\tif (this.mode === 'nonlinear') {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Linear mode permits staying on the current item or advancing exactly\n\t\t// one item. QTI forbids returning after the candidate moves on.\n\t\treturn targetIndex === currentIndex || targetIndex === currentIndex + 1;\n\t}\n\n\t/**\n\t * Check if \"next\" navigation is allowed\n\t */\n\tcanNext(currentIndex: number): boolean {\n\t\treturn currentIndex < this.totalItems - 1;\n\t}\n\n\t/**\n\t * Check if \"previous\" navigation is allowed\n\t */\n\tcanPrevious(currentIndex: number): boolean {\n\t\treturn this.mode === 'nonlinear' && currentIndex > 0;\n\t}\n\n\t/**\n\t * Get the next valid index\n\t */\n\tgetNextIndex(currentIndex: number): number | null {\n\t\tif (!this.canNext(currentIndex)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn currentIndex + 1;\n\t}\n\n\t/**\n\t * Get the previous valid index\n\t */\n\tgetPreviousIndex(currentIndex: number): number | null {\n\t\tif (!this.canPrevious(currentIndex)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn currentIndex - 1;\n\t}\n\n\t/**\n\t * Mark an item as visited\n\t */\n\tmarkVisited(index: number): void {\n\t\tthis.visitedItems.add(index);\n\t}\n\n\t/**\n\t * Check if an item has been visited\n\t */\n\tisVisited(index: number): boolean {\n\t\treturn this.visitedItems.has(index);\n\t}\n\n\t/**\n\t * Get all visited item indices\n\t */\n\tgetVisitedItems(): number[] {\n\t\treturn Array.from(this.visitedItems).sort((a, b) => a - b);\n\t}\n\n\t/**\n\t * Get navigation mode\n\t */\n\tgetMode(): NavigationMode {\n\t\treturn this.mode;\n\t}\n\n\t/**\n\t * Reset visited items (e.g., for retaking assessment)\n\t */\n\treset(): void {\n\t\tthis.visitedItems.clear();\n\t}\n\n\t/**\n\t * Restore state (for save/resume)\n\t */\n\trestoreState(visitedItems: number[]): void {\n\t\tthis.visitedItems = new Set(visitedItems);\n\t}\n}\n","/**\n * TimeManager\n *\n * Manages time limits and tracking for QTI assessments.\n * Supports test-level, section-level, and item-level time limits.\n *\n * Features:\n * - Countdown timers with warnings\n * - Auto-submission when time expires\n * - Time spent tracking per item\n * - Pause/resume support\n * - Late submission handling\n */\n\nimport type { TimeLimits } from '../types/index.js';\n\nexport interface TimeManagerConfig {\n\t/** Assessment-level time limits */\n\tassessmentTimeLimits?: TimeLimits;\n\t/** Warning threshold (seconds before expiry) */\n\twarningThreshold?: number;\n\t/** Callback when time warning is triggered */\n\tonWarning?: (remainingSeconds: number) => void;\n\t/** Callback when time expires */\n\tonExpired?: () => void;\n\t/** Callback for time updates (fires every second) */\n\tonTick?: (remainingSeconds: number, elapsedSeconds: number) => void;\n\t/**\n\t * QTI 3.0 PNP extended time accommodation.\n\t * When active, multiplies assessmentTimeLimits.maxTime by the given multiplier.\n\t * multiplier: Infinity removes the time limit entirely.\n\t */\n\textendedTime?: { active: boolean; multiplier: number };\n\t/** Injectable monotonic wall clock for deterministic hosts/tests. */\n\tnow?: () => number;\n}\n\nexport interface ActiveTimeScopes {\n\ttestPart?: { identifier: string; timeLimits?: TimeLimits };\n\tsection?: { identifier: string; timeLimits?: TimeLimits };\n\titem?: { identifier: string; timeLimits?: TimeLimits };\n}\n\nexport interface TimeTrackingState {\n\t/** Total elapsed time (ms) */\n\ttotalElapsed: number;\n\t/** Time spent per item identifier (ms) */\n\titemTimes: Record<string, number>;\n\t/** Time spent per section identifier (ms) */\n\tsectionTimes: Record<string, number>;\n\t/** Time spent per testPart identifier (ms) */\n\ttestPartTimes: Record<string, number>;\n\t/** Session start timestamp */\n\tstartedAt: number;\n\t/** Current item start time (for tracking) */\n\tcurrentItemStartTime?: number;\n\t/** Current item identifier */\n\tcurrentItemId?: string;\n\t/** Current section identifier */\n\tcurrentSectionId?: string;\n\t/** Current section start time */\n\tcurrentSectionStartTime?: number;\n\t/** Current testPart identifier */\n\tcurrentTestPartId?: string;\n\t/** Current testPart start time */\n\tcurrentTestPartStartTime?: number;\n\t/** Is timer currently paused */\n\tisPaused: boolean;\n}\n\nexport class TimeManager {\n\tprivate config: TimeManagerConfig;\n\tprivate state: TimeTrackingState;\n\n\t// Timer internals\n\tprivate intervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate maxTimeSeconds: number | null = null;\n\tprivate warningTriggered = new Set<string>();\n\tprivate expirationTriggered = new Set<string>();\n\tprivate activeScopes: ActiveTimeScopes = {};\n\tprivate lastTickAt: number;\n\n\tconstructor(config: TimeManagerConfig) {\n\t\tthis.config = config;\n\t\tthis.state = {\n\t\t\ttotalElapsed: 0,\n\t\t\titemTimes: {},\n\t\t\tsectionTimes: {},\n\t\t\ttestPartTimes: {},\n\t\t\tstartedAt: this.now(),\n\t\t\tisPaused: false,\n\t\t};\n\t\tthis.lastTickAt = this.now();\n\n\t\t// Initialize timer if time limit exists, applying PNP extended-time multiplier if set.\n\t\tif (config.assessmentTimeLimits?.maxTime) {\n\t\t\tconst base = config.assessmentTimeLimits.maxTime;\n\t\t\tconst et = config.extendedTime;\n\t\t\tif (et?.active && et.multiplier === Infinity) {\n\t\t\t\t// multiplier: Infinity → unlimited time (no countdown)\n\t\t\t\tthis.maxTimeSeconds = null;\n\t\t\t} else if (et?.active && et.multiplier > 0) {\n\t\t\t\tthis.maxTimeSeconds = base * et.multiplier;\n\t\t\t} else {\n\t\t\t\tthis.maxTimeSeconds = base;\n\t\t\t}\n\t\t}\n\t\t// Scope timing is required even when the assessment itself has no maxTime.\n\t\tthis.startTimer();\n\t}\n\n\tprivate now(): number {\n\t\treturn this.config.now?.() ?? Date.now();\n\t}\n\n\tprivate applyExtendedTime(seconds: number | undefined): number | null {\n\t\tif (seconds === undefined) return null;\n\t\tconst extended = this.config.extendedTime;\n\t\tif (extended?.active && extended.multiplier === Infinity) return null;\n\t\tif (extended?.active && extended.multiplier > 0) return seconds * extended.multiplier;\n\t\treturn seconds;\n\t}\n\n\t/**\n\t * Start or resume the timer\n\t */\n\tprivate startTimer(): void {\n\t\tif (this.intervalId) {\n\t\t\treturn; // Already running\n\t\t}\n\n\t\tthis.state.isPaused = false;\n\t\tthis.lastTickAt = this.now();\n\n\t\tthis.intervalId = setInterval(() => {\n\t\t\tconst now = this.now();\n\t\t\tif (this.state.isPaused) {\n\t\t\t\tthis.lastTickAt = now;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.state.totalElapsed += Math.max(0, now - this.lastTickAt);\n\t\t\tthis.lastTickAt = now;\n\n\t\t\tconst elapsedSeconds = Math.floor(this.state.totalElapsed / 1000);\n\t\t\tconst candidates = this.getActiveCandidates();\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.remainingSeconds > 0 || this.expirationTriggered.has(candidate.key)) continue;\n\t\t\t\tthis.expirationTriggered.add(candidate.key);\n\t\t\t\tif (!candidate.allowLateSubmission) {\n\t\t\t\t\tthis.handleExpiration();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst activeRemaining = this.nearestRemaining(candidates);\n\t\t\tif (activeRemaining) {\n\t\t\t\tconst { key, remainingSeconds } = activeRemaining;\n\n\t\t\t\t// Trigger warning\n\t\t\t\tconst warningThreshold = this.config.warningThreshold ?? 60;\n\t\t\t\tif (!this.warningTriggered.has(key) && remainingSeconds <= warningThreshold && remainingSeconds > 0) {\n\t\t\t\t\tthis.warningTriggered.add(key);\n\t\t\t\t\tthis.config.onWarning?.(remainingSeconds);\n\t\t\t\t}\n\n\t\t\t\t// Tick callback\n\t\t\t\tthis.config.onTick?.(remainingSeconds, elapsedSeconds);\n\t\t\t} else {\n\t\t\t\t// No limit - just count up\n\t\t\t\tthis.config.onTick?.(0, elapsedSeconds);\n\t\t\t}\n\t\t}, 1000);\n\t}\n\n\tprivate getActiveCandidates(): Array<{\n\t\tkey: string;\n\t\tremainingSeconds: number;\n\t\tallowLateSubmission: boolean;\n\t}> {\n\t\tconst candidates: Array<{ key: string; remainingSeconds: number; allowLateSubmission: boolean }> = [];\n\t\tif (this.maxTimeSeconds !== null) {\n\t\t\tcandidates.push({\n\t\t\t\tkey: 'assessment',\n\t\t\t\tremainingSeconds: this.maxTimeSeconds - this.getElapsedSeconds(),\n\t\t\t\tallowLateSubmission: this.config.assessmentTimeLimits?.allowLateSubmission === true,\n\t\t\t});\n\t\t}\n\t\tfor (const scope of ['testPart', 'section', 'item'] as const) {\n\t\t\tconst active = this.activeScopes[scope];\n\t\t\tconst max = this.applyExtendedTime(active?.timeLimits?.maxTime);\n\t\t\tif (!active || max === null) continue;\n\t\t\tcandidates.push({\n\t\t\t\tkey: `${scope}:${active.identifier}`,\n\t\t\t\tremainingSeconds: max - this.getScopeElapsedMs(scope, active.identifier) / 1000,\n\t\t\t\tallowLateSubmission: active.timeLimits?.allowLateSubmission === true,\n\t\t\t});\n\t\t}\n\t\treturn candidates;\n\t}\n\n\tprivate nearestRemaining(\n\t\tcandidates: Array<{ key: string; remainingSeconds: number; allowLateSubmission: boolean }>,\n\t): { key: string; remainingSeconds: number; allowLateSubmission: boolean } | null {\n\t\tif (candidates.length === 0) return null;\n\t\treturn candidates.reduce((nearest, candidate) =>\n\t\t\tcandidate.remainingSeconds < nearest.remainingSeconds ? candidate : nearest\n\t\t);\n\t}\n\n\tprivate getActiveRemaining(): { key: string; remainingSeconds: number; allowLateSubmission: boolean } | null {\n\t\treturn this.nearestRemaining(this.getActiveCandidates());\n\t}\n\n\t/**\n\t * Handle time expiration\n\t */\n\tprivate handleExpiration(): void {\n\t\tthis.stopTimer();\n\t\tthis.config.onExpired?.();\n\t}\n\n\t/**\n\t * Stop the timer\n\t */\n\tstopTimer(): void {\n\t\tif (this.intervalId) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = null;\n\t\t}\n\t}\n\n\t/**\n\t * Pause the timer\n\t */\n\tpause(): void {\n\t\tif (this.state.isPaused) return;\n\t\tthis.state.totalElapsed = this.getTotalElapsedMs();\n\t\tthis.lastTickAt = this.now();\n\t\tthis.checkpointActiveScopes(false);\n\t\tthis.state.isPaused = true;\n\t}\n\n\t/**\n\t * Resume the timer\n\t */\n\tresume(): void {\n\t\tif (!this.state.isPaused) return;\n\t\tthis.state.isPaused = false;\n\t\tconst now = this.now();\n\t\tif (this.state.currentItemId) this.state.currentItemStartTime = now;\n\t\tif (this.state.currentSectionId) this.state.currentSectionStartTime = now;\n\t\tif (this.state.currentTestPartId) this.state.currentTestPartStartTime = now;\n\t\tthis.lastTickAt = now;\n\t}\n\n\t/**\n\t * Start tracking time for an item\n\t */\n\tstartItem(itemIdentifier: string): void {\n\t\tif (this.state.currentItemId === itemIdentifier && this.state.currentItemStartTime) return;\n\t\t// End previous item if any\n\t\tif (this.state.currentItemStartTime) {\n\t\t\tthis.endCurrentItem();\n\t\t}\n\n\t\tthis.state.currentItemId = itemIdentifier;\n\t\tthis.state.currentItemStartTime = this.state.isPaused ? undefined : this.now();\n\t}\n\n\t/**\n\t * End tracking time for current item\n\t */\n\tprivate endCurrentItem(): void {\n\t\tif (!this.state.currentItemStartTime) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst timeSpent = this.now() - this.state.currentItemStartTime;\n\t\tif (this.state.currentItemId) {\n\t\t\tthis.state.itemTimes[this.state.currentItemId] =\n\t\t\t\t(this.state.itemTimes[this.state.currentItemId] || 0) + Math.max(0, timeSpent);\n\t\t}\n\t\tthis.state.currentItemStartTime = undefined;\n\t\tthis.state.currentItemId = undefined;\n\t}\n\n\t/**\n\t * End tracking time for an item\n\t */\n\tendItem(itemIdentifier: string): void {\n\t\tif (!this.state.currentItemStartTime) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst timeSpent = this.now() - this.state.currentItemStartTime;\n\t\tconst activeIdentifier = this.state.currentItemId ?? itemIdentifier;\n\t\tthis.state.itemTimes[activeIdentifier] = (this.state.itemTimes[activeIdentifier] || 0) + Math.max(0, timeSpent);\n\t\tthis.state.currentItemStartTime = undefined;\n\t\tthis.state.currentItemId = undefined;\n\t}\n\n\t/**\n\t * Start tracking time for a section\n\t */\n\tstartSection(sectionIdentifier: string): void {\n\t\tif (this.state.currentSectionId === sectionIdentifier && this.state.currentSectionStartTime) return;\n\t\tthis.endCurrentSection();\n\t\tthis.state.currentSectionId = sectionIdentifier;\n\t\tthis.state.currentSectionStartTime = this.state.isPaused ? undefined : this.now();\n\t}\n\n\tstartTestPart(testPartIdentifier: string): void {\n\t\tif (this.state.currentTestPartId === testPartIdentifier && this.state.currentTestPartStartTime) return;\n\t\tthis.endCurrentTestPart();\n\t\tthis.state.currentTestPartId = testPartIdentifier;\n\t\tthis.state.currentTestPartStartTime = this.state.isPaused ? undefined : this.now();\n\t}\n\n\tactivateScopes(scopes: ActiveTimeScopes): void {\n\t\tif (scopes.testPart) this.startTestPart(scopes.testPart.identifier);\n\t\tif (scopes.section) this.startSection(scopes.section.identifier);\n\t\tif (scopes.item) this.startItem(scopes.item.identifier);\n\t\tthis.activeScopes = scopes;\n\t}\n\n\tprivate endCurrentSection(): void {\n\t\tif (this.state.currentSectionId && this.state.currentSectionStartTime) {\n\t\t\tconst elapsed = Math.max(0, this.now() - this.state.currentSectionStartTime);\n\t\t\tthis.state.sectionTimes[this.state.currentSectionId] =\n\t\t\t\t(this.state.sectionTimes[this.state.currentSectionId] || 0) + elapsed;\n\t\t}\n\t\tthis.state.currentSectionStartTime = undefined;\n\t}\n\n\tprivate endCurrentTestPart(): void {\n\t\tif (this.state.currentTestPartId && this.state.currentTestPartStartTime) {\n\t\t\tconst elapsed = Math.max(0, this.now() - this.state.currentTestPartStartTime);\n\t\t\tthis.state.testPartTimes[this.state.currentTestPartId] =\n\t\t\t\t(this.state.testPartTimes[this.state.currentTestPartId] || 0) + elapsed;\n\t\t}\n\t\tthis.state.currentTestPartStartTime = undefined;\n\t}\n\n\tprivate checkpointActiveScopes(restart: boolean): void {\n\t\tconst itemId = this.state.currentItemId;\n\t\tconst sectionId = this.state.currentSectionId;\n\t\tconst testPartId = this.state.currentTestPartId;\n\t\tthis.endCurrentItem();\n\t\tthis.endCurrentSection();\n\t\tthis.endCurrentTestPart();\n\t\tthis.state.currentItemId = itemId;\n\t\tthis.state.currentSectionId = sectionId;\n\t\tthis.state.currentTestPartId = testPartId;\n\t\tif (restart && !this.state.isPaused) {\n\t\t\tconst now = this.now();\n\t\t\tif (itemId) this.state.currentItemStartTime = now;\n\t\t\tif (sectionId) this.state.currentSectionStartTime = now;\n\t\t\tif (testPartId) this.state.currentTestPartStartTime = now;\n\t\t}\n\t}\n\n\t/**\n\t * Get remaining time in seconds (null if no limit)\n\t */\n\tgetRemainingSeconds(): number | null {\n\t\tconst active = this.getActiveRemaining();\n\t\treturn active ? Math.max(0, Math.ceil(active.remainingSeconds)) : null;\n\t}\n\n\t/**\n\t * Get elapsed time in seconds\n\t */\n\tgetElapsedSeconds(): number {\n\t\treturn Math.floor(this.getTotalElapsedMs() / 1000);\n\t}\n\n\tprivate getTotalElapsedMs(): number {\n\t\tif (this.state.isPaused) return this.state.totalElapsed;\n\t\treturn this.state.totalElapsed + Math.max(0, this.now() - this.lastTickAt);\n\t}\n\n\t/**\n\t * Get time spent on a specific item (ms)\n\t */\n\tgetItemTime(itemIdentifier: string): number {\n\t\treturn this.getScopeElapsedMs('item', itemIdentifier);\n\t}\n\n\tgetScopeElapsedMs(scope: 'assessment' | 'testPart' | 'section' | 'item', identifier?: string): number {\n\t\tif (scope === 'assessment') return this.getTotalElapsedMs();\n\t\tconst now = this.now();\n\t\tif (scope === 'item') {\n\t\t\tconst id = identifier ?? this.state.currentItemId;\n\t\t\tif (!id) return 0;\n\t\t\tconst active = id === this.state.currentItemId && this.state.currentItemStartTime && !this.state.isPaused\n\t\t\t\t? Math.max(0, now - this.state.currentItemStartTime)\n\t\t\t\t: 0;\n\t\t\treturn (this.state.itemTimes[id] || 0) + active;\n\t\t}\n\t\tif (scope === 'section') {\n\t\t\tconst id = identifier ?? this.state.currentSectionId;\n\t\t\tif (!id) return 0;\n\t\t\tconst active = id === this.state.currentSectionId && this.state.currentSectionStartTime && !this.state.isPaused\n\t\t\t\t? Math.max(0, now - this.state.currentSectionStartTime)\n\t\t\t\t: 0;\n\t\t\treturn (this.state.sectionTimes[id] || 0) + active;\n\t\t}\n\t\tconst id = identifier ?? this.state.currentTestPartId;\n\t\tif (!id) return 0;\n\t\tconst active = id === this.state.currentTestPartId && this.state.currentTestPartStartTime && !this.state.isPaused\n\t\t\t? Math.max(0, now - this.state.currentTestPartStartTime)\n\t\t\t: 0;\n\t\treturn (this.state.testPartTimes[id] || 0) + active;\n\t}\n\n\t/**\n\t * Get current tracking state (for persistence)\n\t */\n\tgetState(): TimeTrackingState {\n\t\tif (!this.state.isPaused) {\n\t\t\tthis.state.totalElapsed = this.getTotalElapsedMs();\n\t\t\tthis.lastTickAt = this.now();\n\t\t}\n\t\tthis.checkpointActiveScopes(true);\n\t\treturn {\n\t\t\t...this.state,\n\t\t\titemTimes: { ...this.state.itemTimes },\n\t\t\tsectionTimes: { ...this.state.sectionTimes },\n\t\t\ttestPartTimes: { ...this.state.testPartTimes },\n\t\t};\n\t}\n\n\t/**\n\t * Restore tracking state (for resume)\n\t */\n\trestoreState(state: TimeTrackingState): void {\n\t\tthis.state = {\n\t\t\t...state,\n\t\t\titemTimes: { ...state.itemTimes },\n\t\t\tsectionTimes: { ...state.sectionTimes },\n\t\t\ttestPartTimes: { ...(state.testPartTimes ?? {}) },\n\t\t\tcurrentItemStartTime: undefined,\n\t\t\tcurrentSectionStartTime: undefined,\n\t\t\tcurrentTestPartStartTime: undefined,\n\t\t};\n\t\tif (!this.state.isPaused) {\n\t\t\tconst now = this.now();\n\t\t\tif (this.state.currentItemId) this.state.currentItemStartTime = now;\n\t\t\tif (this.state.currentSectionId) this.state.currentSectionStartTime = now;\n\t\t\tif (this.state.currentTestPartId) this.state.currentTestPartStartTime = now;\n\t\t\tthis.lastTickAt = now;\n\t\t}\n\n\t\t// Restart timer if not expired\n\t\tif (this.maxTimeSeconds) {\n\t\t\tconst elapsedSeconds = Math.floor(this.state.totalElapsed / 1000);\n\t\t\tif (elapsedSeconds < this.maxTimeSeconds) {\n\t\t\t\tthis.startTimer();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if time has expired\n\t */\n\tisExpired(): boolean {\n\t\tconst active = this.getActiveRemaining();\n\t\treturn active !== null && active.remainingSeconds <= 0;\n\t}\n\n\t/**\n\t * Check if late submission is allowed\n\t */\n\tallowsLateSubmission(): boolean {\n\t\tconst candidates = this.getActiveCandidates();\n\t\tconst expired = candidates.filter((candidate) => candidate.remainingSeconds <= 0);\n\t\tif (expired.length > 0) {\n\t\t\treturn expired.every((candidate) => candidate.allowLateSubmission);\n\t\t}\n\t\treturn this.nearestRemaining(candidates)?.allowLateSubmission ?? false;\n\t}\n\n\t/**\n\t * Format time as MM:SS or HH:MM:SS\n\t */\n\tstatic formatTime(seconds: number): string {\n\t\tconst hours = Math.floor(seconds / 3600);\n\t\tconst minutes = Math.floor((seconds % 3600) / 60);\n\t\tconst secs = seconds % 60;\n\n\t\tif (hours > 0) {\n\t\t\treturn `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;\n\t\t}\n\n\t\treturn `${minutes}:${secs.toString().padStart(2, '0')}`;\n\t}\n\n\t/**\n\t * Cleanup - stop all timers\n\t */\n\tdestroy(): void {\n\t\tthis.checkpointActiveScopes(false);\n\t\tthis.stopTimer();\n\t}\n}\n","/**\n * AssessmentPlayer (backend-authoritative)\n *\n * Client responsibilities:\n * - Render items using @pie-qti/item-player\n * - Collect candidate responses\n * - Submit responses to BackendAdapter\n * - Apply backend navigation decisions + session state\n */\n\nimport {\n\tcreateAssessmentItemDefinition,\n\ttype AssessmentItemDefinition,\n\ttype AssessmentItemDefinitionPlugin,\n\ttype ItemSession,\n\ttype PciConfiguration,\n\ttype PnpProfile,\n\ttype PlayerSecurityConfig,\n\ttype QTIRole,\n\ttype SerializedItemSessionState,\n} from '@pie-qti/item-player';\nimport type { I18nProvider } from '@pie-qti/i18n';\nimport type { QtiSectionRuntimeHostContract, QtiSectionToolConfig } from '@pie-qti/section-player';\nimport type {\n\tAssessmentRubricBlock,\n\tAssessmentSessionState,\n\tAssessmentScoringResult,\n\tBackendAdapter,\n\tFinalizeAssessmentResponse,\n\tInitSessionRequest,\n\tInitSessionResponse,\n\tSecureAssessment,\n\tSecureItemRef,\n\tSecureSection,\n\tSecureSectionComponent,\n\tSecureTestPart,\n\tSessionId,\n} from '../integration/api-contract.js';\nimport type {\n\tAssessmentResults,\n\tItemResult,\n\tNavigationState,\n\tTimeLimits,\n} from '../types/index.js';\nimport { AssessmentSessionCoordinator } from './AssessmentSessionCoordinator.js';\nimport { NavigationManager } from './NavigationManager.js';\nimport { TimeManager } from './TimeManager.js';\n\nexport interface BackendAssessmentPlayerConfig {\n\tbackend: BackendAdapter;\n\tinitSession: InitSessionRequest;\n\trole?: QTIRole;\n\t/** Optional RNG for deterministic shuffling in selection/ordering. Defaults to Math.random. */\n\trng?: () => number;\n\t/** Definition-lifetime extractor and renderer extensions applied to every item. */\n\tplugins?: readonly AssessmentItemDefinitionPlugin[];\n\t/**\n\t * Optional i18n provider for internationalization.\n\t * If provided, this will be shared across all item players in the assessment.\n\t */\n\ti18nProvider?: I18nProvider;\n\t/**\n\t * Security configuration for URL policy and content restrictions.\n\t * If provided, this will be passed to all item players in the assessment.\n\t */\n\tsecurity?: PlayerSecurityConfig;\n\t/**\n\t * Explicit host trust configuration for Portable Custom Interaction modules.\n\t * Without this resolver, authored PCI code remains disabled.\n\t */\n\tpci?: PciConfiguration;\n\t/**\n\t * Optional host hooks for delegated section rendering.\n\t * Used for section shared-content URL policy and runtime callbacks.\n\t */\n\tsectionHost?: QtiSectionRuntimeHostContract;\n\t/** Optional section-scoped tools rendered by delegated section players. */\n\tsectionTools?: QtiSectionToolConfig[];\n\t/** Optional tools rendered in passage/rubric headers. */\n\tpassageTools?: QtiSectionToolConfig[];\n\t/** Optional tools rendered in item headers. */\n\titemTools?: QtiSectionToolConfig[];\n\t/**\n\t * Demo/reference-only escape hatch. When false (default), rich item-session\n\t * variables stay client-local and are not submitted because template variables\n\t * can contain answer keys. Production backends should own this state server-side.\n\t */\n\tsendItemSessionToBackend?: boolean;\n\t// UI options\n\tshowSections?: boolean;\n\tallowSectionNavigation?: boolean;\n\tshowProgress?: boolean;\n\t// Time management\n\ttimeWarningThreshold?: number;\n\t/**\n\t * QTI 3.0 §6.2 Personal Needs and Preferences profile.\n\t * Extended time (pnp.content.extendedTime) is applied to assessment timeLimits.\n\t * The full profile is passed down to each item player for component-level features\n\t * (color scheme, elimination tool).\n\t */\n\tpnp?: PnpProfile;\n\t// Callbacks\n\tonItemChange?: (itemIndex: number, totalItems: number) => void;\n\tonSectionChange?: (sectionIndex: number, totalSections: number) => void;\n\tonResponseChange?: (responses: Record<string, unknown>) => void;\n\tonComplete?: () => void;\n}\n\ntype FlatItem = {\n\tidentifier: string;\n\titem: SecureItemRef;\n\tsection: SecureSection;\n\ttestPart: SecureTestPart;\n\tindex: number;\n\tsectionIndex: number;\n};\n\ntype CurrentItemView = {\n\tidentifier: string;\n\ttitle?: string;\n\trequired?: boolean;\n\titemXml: string;\n\tdeliveryContext?: SecureItemRef['deliveryContext'];\n};\n\ntype SectionItemRefView = {\n\tidentifier: string;\n\thref?: string;\n\ttitle?: string;\n\titemXml: string;\n\tdeliveryContext?: SecureItemRef['deliveryContext'];\n};\n\nexport interface EffectiveItemTimeLimits {\n\ttimeLimits?: TimeLimits;\n\tsource?: 'item' | 'section' | 'testPart' | 'assessment';\n}\n\nexport class AssessmentPlayer {\n\tpublic static async create(config: BackendAssessmentPlayerConfig): Promise<AssessmentPlayer> {\n\t\tconst init = await config.backend.initSession(config.initSession);\n\t\treturn new AssessmentPlayer(config, init);\n\t}\n\n\tprivate backend: BackendAdapter;\n\tprivate sessionId: SessionId;\n\tprivate assessment: SecureAssessment;\n\tprivate i18nProvider: I18nProvider;\n\n\tprivate navigationManager: NavigationManager;\n\tprivate sessionCoordinator!: AssessmentSessionCoordinator;\n\tprivate timeManager: TimeManager | null = null;\n\n\tprivate items: FlatItem[] = [];\n\tprivate currentItemIndex = -1;\n\tprivate readonly itemDefinitions = new Map<string, AssessmentItemDefinition>();\n\tprivate currentItemSession: ItemSession | null = null;\n\tprivate currentItemSessionUnsubscribe: (() => void) | null = null;\n\tprivate visibleFeedback: Array<{ identifier: string; content: string; access: string }> = [];\n\n\t// Event listeners\n\tprivate itemChangeListeners = new Set<(index: number, total: number) => void>();\n\tprivate sectionChangeListeners = new Set<(index: number, total: number) => void>();\n\tprivate responseChangeListeners = new Set<(responses: Record<string, unknown>) => void>();\n\tprivate completeListeners = new Set<() => void>();\n\tprivate timeWarningListeners = new Set<(remainingSeconds: number) => void>();\n\tprivate timeExpiredListeners = new Set<() => void>();\n\tprivate timeTickListeners = new Set<(remainingSeconds: number, elapsedSeconds: number) => void>();\n\n\tprivate constructor(private config: BackendAssessmentPlayerConfig, init: InitSessionResponse) {\n\t\tthis.backend = config.backend;\n\t\tthis.sessionId = init.sessionId;\n\t\tthis.assessment = init.assessment;\n\t\tthis.i18nProvider = config.i18nProvider ?? this.createDefaultI18nProvider();\n\t\tconst initialState =\n\t\t\tinit.restoredState ??\n\t\t\t({\n\t\t\t\tcurrentItemIdentifier: '',\n\t\t\t\tvisitedItems: [],\n\t\t\t\titemResponses: {},\n\t\t\t\titemScores: {},\n\t\t\t\titemSessions: {},\n\t\t\t\ttiming: { startedAt: Date.now(), itemTimes: {}, totalTime: 0 },\n\t\t\t} as AssessmentSessionState);\n\n\t\tthis.items = this.flattenItems(this.assessment);\n\n\t\tconst navigationMode = this.assessment.navigationMode || 'nonlinear';\n\t\tthis.navigationManager = new NavigationManager(navigationMode, this.items.length);\n\n\t\t// Item session control is a UI hint; backend remains authoritative.\n\t\t// Start with testPart-level defaults; section-level overrides are applied per item in navigateTo().\n\t\tconst itemSessionControl = this.assessment.testParts?.[0]?.itemSessionControl;\n\t\tthis.sessionCoordinator = new AssessmentSessionCoordinator({\n\t\t\tstate: initialState,\n\t\t\titemIdentifiers: this.items.map((q) => q.identifier),\n\t\t\titemSessionControl,\n\t\t});\n\n\t\tthis.timeManager = new TimeManager({\n\t\t\tassessmentTimeLimits: this.assessment.timeLimits,\n\t\t\twarningThreshold: config.timeWarningThreshold || 60,\n\t\t\textendedTime: config.pnp?.content?.extendedTime,\n\t\t\tonWarning: (remainingSeconds) => this.notifyTimeWarning(remainingSeconds),\n\t\t\tonExpired: () => this.notifyTimeExpired(),\n\t\t\tonTick: (remainingSeconds, elapsedSeconds) => this.notifyTimeTick(remainingSeconds, elapsedSeconds),\n\t\t});\n\t\tif (init.restoredState?.timing) {\n\t\t\tthis.restoreTimeTracking(init.restoredState.timing);\n\t\t}\n\n\t\t// Restore to backend-provided current item if present\n\t\tconst startId = this.state.currentItemIdentifier;\n\t\tconst idx = startId ? this.items.findIndex((q) => q.identifier === startId) : -1;\n\t\tif (idx >= 0) {\n\t\t\tthis.navigateTo(idx, { restoring: true }).catch(() => {});\n\t\t} else if (this.items.length > 0) {\n\t\t\tthis.navigateTo(0, { restoring: true }).catch(() => {});\n\t\t}\n\t}\n\n\tprivate get state(): AssessmentSessionState {\n\t\treturn this.sessionCoordinator.state;\n\t}\n\n\tprivate set state(state: AssessmentSessionState) {\n\t\tthis.sessionCoordinator.restoreState(state);\n\t}\n\n\t/**\n\t * Compute effective itemSessionControl for a given item using three-level fallback:\n\t * section-level (highest priority) → testPart-level → defaults.\n\t * Section-level values override testPart-level when present.\n\t */\n\tprivate getEffectiveItemSessionControl(flat: FlatItem): SecureSection['itemSessionControl'] {\n\t\tconst testPartControl = flat.testPart.itemSessionControl;\n\t\tconst sectionControl = flat.section.itemSessionControl;\n\n\t\tif (!sectionControl) return testPartControl;\n\t\tif (!testPartControl) return sectionControl;\n\n\t\treturn {\n\t\t\tmaxAttempts: sectionControl.maxAttempts ?? testPartControl.maxAttempts,\n\t\t\tshowFeedback: sectionControl.showFeedback ?? testPartControl.showFeedback,\n\t\t\tallowReview: sectionControl.allowReview ?? testPartControl.allowReview,\n\t\t\tshowSolution: sectionControl.showSolution ?? testPartControl.showSolution,\n\t\t\tallowComment: sectionControl.allowComment ?? testPartControl.allowComment,\n\t\t\tallowSkipping: sectionControl.allowSkipping ?? testPartControl.allowSkipping,\n\t\t\tvalidateResponses: sectionControl.validateResponses ?? testPartControl.validateResponses,\n\t\t};\n\t}\n\n\tprivate getEffectiveItemTimeLimits(flat: FlatItem): EffectiveItemTimeLimits {\n\t\tconst scopes: Array<{ source: EffectiveItemTimeLimits['source']; limits?: TimeLimits }> = [\n\t\t\t{ source: 'assessment', limits: this.assessment.timeLimits },\n\t\t\t{ source: 'testPart', limits: flat.testPart.timeLimits },\n\t\t\t{ source: 'section', limits: flat.section.timeLimits },\n\t\t\t{ source: 'item', limits: flat.item.timeLimits },\n\t\t];\n\t\tlet source: EffectiveItemTimeLimits['source'];\n\t\tlet minTime: number | undefined;\n\t\tlet maxTime: number | undefined;\n\t\tlet allowLateSubmission: boolean | undefined;\n\t\tfor (const scope of scopes) {\n\t\t\tif (!scope.limits) continue;\n\t\t\tif (scope.limits.minTime !== undefined) {\n\t\t\t\tminTime = minTime === undefined ? scope.limits.minTime : Math.max(minTime, scope.limits.minTime);\n\t\t\t}\n\t\t\tif (scope.limits.maxTime !== undefined) {\n\t\t\t\tconst extended = this.config.pnp?.content?.extendedTime;\n\t\t\t\tconst scopedMaxTime = extended?.active\n\t\t\t\t\t? extended.multiplier === Infinity\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: scope.limits.maxTime * extended.multiplier\n\t\t\t\t\t: scope.limits.maxTime;\n\t\t\t\tif (scopedMaxTime !== undefined && (maxTime === undefined || scopedMaxTime < maxTime)) {\n\t\t\t\t\tmaxTime = scopedMaxTime;\n\t\t\t\t\tsource = scope.source;\n\t\t\t\t\tallowLateSubmission = scope.limits.allowLateSubmission;\n\t\t\t\t}\n\t\t\t} else if (scope.limits.allowLateSubmission !== undefined && maxTime === undefined) {\n\t\t\t\tallowLateSubmission = scope.limits.allowLateSubmission;\n\t\t\t\tsource = scope.source;\n\t\t\t}\n\t\t}\n\n\t\tif (maxTime === undefined && minTime === undefined && allowLateSubmission === undefined) {\n\t\t\treturn {};\n\t\t}\n\t\treturn { source, timeLimits: { minTime, maxTime, allowLateSubmission } };\n\t}\n\n\tpublic getCurrentEffectiveTimeLimits(): EffectiveItemTimeLimits {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\treturn q ? this.getEffectiveItemTimeLimits(q) : {};\n\t}\n\n\tprivate getSubmitTimingEvidence(q: FlatItem, elapsedMs: number): import('../integration/api-contract.js').SubmitTimingEvidence | undefined {\n\t\tconst effective = this.getEffectiveItemTimeLimits(q);\n\t\tconst limitSeconds = effective.timeLimits?.maxTime;\n\t\tif (!effective.source || limitSeconds === undefined) return undefined;\n\t\tconst scopeIdentifier = effective.source === 'item'\n\t\t\t? q.identifier\n\t\t\t: effective.source === 'section'\n\t\t\t\t? q.section.identifier\n\t\t\t\t: effective.source === 'testPart'\n\t\t\t\t\t? q.testPart.identifier\n\t\t\t\t\t: undefined;\n\t\tconst tracked = this.timeManager?.getScopeElapsedMs(effective.source, scopeIdentifier);\n\t\tconst scopedElapsedMs = tracked ?? elapsedMs;\n\t\treturn {\n\t\t\tscope: effective.source,\n\t\t\telapsedMs: scopedElapsedMs,\n\t\t\tlimitSeconds,\n\t\t\texpired: scopedElapsedMs >= limitSeconds * 1000,\n\t\t\tallowLateSubmission: effective.timeLimits?.allowLateSubmission,\n\t\t};\n\t}\n\n\tprivate assertMinimumTime(scope: 'assessment' | 'testPart' | 'section' | 'item', q: FlatItem): void {\n\t\tconst limits = scope === 'assessment'\n\t\t\t? this.assessment.timeLimits\n\t\t\t: scope === 'testPart'\n\t\t\t\t? q.testPart.timeLimits\n\t\t\t\t: scope === 'section'\n\t\t\t\t\t? q.section.timeLimits\n\t\t\t\t\t: q.item.timeLimits;\n\t\tif (limits?.minTime === undefined) return;\n\t\tconst identifier = scope === 'testPart'\n\t\t\t? q.testPart.identifier\n\t\t\t: scope === 'section'\n\t\t\t\t? q.section.identifier\n\t\t\t\t: scope === 'item'\n\t\t\t\t\t? q.identifier\n\t\t\t\t\t: undefined;\n\t\tconst elapsedMs = this.timeManager?.getScopeElapsedMs(scope, identifier) ?? 0;\n\t\tif (elapsedMs < limits.minTime * 1000) {\n\t\t\tconst remaining = Math.ceil(limits.minTime - elapsedMs / 1000);\n\t\t\tthrow new Error(`The ${scope} minimum time has not elapsed (${remaining}s remaining).`);\n\t\t}\n\t}\n\n\tprivate assertTransitionMinimum(current: FlatItem, target: FlatItem): void {\n\t\tif (current === target) return;\n\t\tthis.assertMinimumTime('item', current);\n\t\tif (current.section !== target.section) this.assertMinimumTime('section', current);\n\t\tif (current.testPart !== target.testPart) this.assertMinimumTime('testPart', current);\n\t}\n\n\tprivate flattenItems(assessment: SecureAssessment): FlatItem[] {\n\t\tconst out: FlatItem[] = [];\n\t\tconst testParts = assessment.testParts || [];\n\t\tlet idx = 0;\n\t\tlet secIdx = 0;\n\t\tconst rng = this.config.rng ?? Math.random;\n\n\t\tconst visitSection = (section: SecureSection, tp: SecureTestPart): void => {\n\t\t\tconst currentSectionIndex = secIdx++;\n\t\t\tlet components: SecureSectionComponent[] = section.children\n\t\t\t\t? [...section.children]\n\t\t\t\t: [\n\t\t\t\t\t...(section.assessmentItemRefs ?? []).map((item) => ({ type: 'item' as const, item })),\n\t\t\t\t\t...(section.sections ?? []).map((child) => ({ type: 'section' as const, section: child })),\n\t\t\t\t];\n\n\t\t\t// Selection is applied to direct children only. Required children are always\n\t\t\t// included, and selection preserves source order; ordering is a later step.\n\t\t\tif (section.selection) {\n\t\t\t\tconst count = Math.max(0, section.selection.select);\n\t\t\t\tconst indexed = components.map((component, sourceIndex) => ({ component, sourceIndex }));\n\t\t\t\tconst required = indexed.filter(({ component }) => isRequiredSectionComponent(component));\n\t\t\t\tif (count < required.length) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Section \"${section.identifier}\" selects ${count} components but contains ${required.length} required components.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (count > indexed.length) {\n\t\t\t\t\tconst replacement = section.selection.withReplacement === true;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\treplacement\n\t\t\t\t\t\t\t? `Section \"${section.identifier}\" requires cloned item instances for withReplacement selection; the backend must materialize those instances before delivery.`\n\t\t\t\t\t\t\t: `Section \"${section.identifier}\" selects ${count} components without replacement but only contains ${indexed.length}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst optional = shuffleArray(\n\t\t\t\t\tindexed.filter(({ component }) => !isRequiredSectionComponent(component)),\n\t\t\t\t\trng,\n\t\t\t\t);\n\t\t\t\tcomponents = [...required, ...optional.slice(0, count - required.length)]\n\t\t\t\t\t.sort((a, b) => a.sourceIndex - b.sourceIndex)\n\t\t\t\t\t.map(({ component }) => component);\n\t\t\t}\n\n\t\t\tif (section.ordering?.shuffle) {\n\t\t\t\tcomponents = shuffleSectionComponents(components, rng);\n\t\t\t}\n\n\t\t\tfor (const component of components) {\n\t\t\t\tif (component.type === 'section') {\n\t\t\t\t\tvisitSection(component.section, tp);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst item = component.item;\n\t\t\t\t\tout.push({\n\t\t\t\t\t\tidentifier: item.identifier,\n\t\t\t\t\t\titem,\n\t\t\t\t\t\tsection,\n\t\t\t\t\t\ttestPart: tp,\n\t\t\t\t\t\tindex: idx++,\n\t\t\t\t\t\tsectionIndex: currentSectionIndex,\n\t\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tfor (const tp of testParts) {\n\t\t\tfor (const section of tp.sections || []) visitSection(section, tp);\n\t\t}\n\t\treturn out;\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Public API used by components\n\t// ---------------------------------------------------------------------------\n\n\tpublic getAllSections(): Array<{ id: string; title?: string; visible: boolean; index: number }> {\n\t\tconst out: Array<{ id: string; title?: string; visible: boolean; index: number }> = [];\n\t\tlet idx = 0;\n\t\tconst visit = (section: SecureSection): void => {\n\t\t\tout.push({ id: section.identifier, title: section.title, visible: section.visible, index: idx++ });\n\t\t\tfor (const child of section.sections ?? []) visit(child);\n\t\t};\n\t\tfor (const tp of this.assessment.testParts || []) {\n\t\t\tfor (const section of tp.sections || []) visit(section);\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic getNavigationState(): NavigationState {\n\t\tconst total = this.items.length;\n\t\tconst canPrevious = this.canPrevious();\n\t\tconst canNext = this.canNext();\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tconst totalSections = this.getAllSections().length;\n\t\treturn {\n\t\t\tcurrentIndex: this.currentItemIndex,\n\t\t\ttotalItems: total,\n\t\t\tcanNext,\n\t\t\tcanPrevious,\n\t\t\tisLoading: false,\n\t\t\tcurrentSection: q\n\t\t\t\t? { id: q.section.identifier, title: q.section.title, index: q.sectionIndex }\n\t\t\t\t: undefined,\n\t\t\ttotalSections,\n\t\t};\n\t}\n\n\tpublic getCurrentItem(): CurrentItemView | null {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q) return null;\n\t\treturn {\n\t\t\tidentifier: q.item.identifier,\n\t\t\ttitle: q.section.title,\n\t\t\trequired: q.item.required,\n\t\t\titemXml: q.item.itemXml,\n\t\t\tdeliveryContext: q.item.deliveryContext,\n\t\t};\n\t}\n\n\t/**\n\t * The one authoritative live session for the active item.\n\t *\n\t * Section and item renderers receive this exact instance. Serialized item-session\n\t * state is reserved for persistence and restore, never for synchronizing a second\n\t * live player.\n\t */\n\tpublic getCurrentItemSession(): ItemSession | null {\n\t\treturn this.currentItemSession;\n\t}\n\n\tpublic getCurrentSectionItemRefs(): SectionItemRefView[] {\n\t\tconst current = this.items[this.currentItemIndex];\n\t\tif (!current) return [];\n\n\t\treturn this.items\n\t\t\t.filter((item) => item.section === current.section)\n\t\t\t.map((item) => {\n\t\t\t\tconst itemRef = item.item as SecureItemRef & { href?: string; title?: string };\n\t\t\t\treturn {\n\t\t\t\t\tidentifier: itemRef.identifier,\n\t\t\t\t\thref: itemRef.href,\n\t\t\t\t\ttitle: itemRef.title,\n\t\t\t\t\titemXml: itemRef.itemXml,\n\t\t\t\t\tdeliveryContext: cloneData(itemRef.deliveryContext),\n\t\t\t\t};\n\t\t\t});\n\t}\n\n\tpublic getResponsesForItem(itemIdentifier: string): Record<string, unknown> {\n\t\treturn cloneData(this.sessionCoordinator.getResponses(itemIdentifier)) ?? {};\n\t}\n\n\tpublic getCurrentSharedRubricBlocks(): AssessmentRubricBlock[] {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q) return [];\n\n\t\treturn [\n\t\t\t...(q.testPart.rubricBlocks ?? []),\n\t\t\t...(q.section.rubricBlocks ?? []),\n\t\t].map((block) => ({ ...block, view: [...block.view] }));\n\t}\n\n\tpublic getCurrentRubricBlocks(): AssessmentRubricBlock[] {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q) return [];\n\t\treturn q.section.rubricBlocks || q.testPart.rubricBlocks || [];\n\t}\n\n\tpublic getVisibleFeedback(): Array<{ identifier: string; content: string; access: string }> {\n\t\treturn this.visibleFeedback.map((item) => ({ ...item }));\n\t}\n\n\tpublic updateResponse(responseId: string, value: unknown): void {\n\t\tconst active = this.items[this.currentItemIndex];\n\t\tif (!active) return;\n\t\tif (this.currentItemSession) {\n\t\t\tthis.currentItemSession.dispatch({\n\t\t\t\taction: 'setResponse',\n\t\t\t\tresponseIdentifier: responseId,\n\t\t\t\tvalue,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.sessionCoordinator.updateResponseForItem(active.identifier, responseId, value);\n\t\tthis.notifyResponseChange();\n\t}\n\n\t/**\n\t * Update a response for a specific item.\n\t * Useful when response events are observed outside the current-item renderer and we\n\t * want to be explicit about which item receives the response (some assessments reuse\n\t * the same responseIdentifier like \"RESPONSE\" across items).\n\t */\n\tpublic updateResponseForItem(itemIdentifier: string, responseId: string, value: unknown): void {\n\t\tconst active = this.items[this.currentItemIndex];\n\t\tif (active?.identifier === itemIdentifier && this.currentItemSession) {\n\t\t\tconst liveValue = this.currentItemSession.state().responses[responseId];\n\t\t\tif (!responseValuesEqual(liveValue, value)) {\n\t\t\t\t// Programmatic/host callers still enter through this API. Browser item\n\t\t\t\t// adapters have already dispatched, so their equal value is not applied twice.\n\t\t\t\tthis.currentItemSession.dispatch({\n\t\t\t\t\taction: 'setResponse',\n\t\t\t\t\tresponseIdentifier: responseId,\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst persisted = this.sessionCoordinator.getPersistedItemSession(itemIdentifier);\n\t\tif (persisted && !isWritableItemLifecycle(persisted.lifecycleStatus)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot update responses while item session is ${persisted.lifecycleStatus}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.sessionCoordinator.updateResponseForItem(itemIdentifier, responseId, value);\n\t\tthis.notifyResponseChange();\n\t}\n\n\t/**\n\t * Get current unsaved responses for the active item.\n\t * (Useful for host integrations / web components.)\n\t */\n\tpublic getResponses(): Record<string, unknown> {\n\t\tif (this.currentItemSession) {\n\t\t\treturn cloneData(this.currentItemSession.state().responses) ?? {};\n\t\t}\n\t\treturn this.sessionCoordinator.getActiveResponses();\n\t}\n\n\tpublic saveCurrentItemSession(): SerializedItemSessionState | null {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q || !this.currentItemSession) return null;\n\n\t\tconst currentView = this.currentItemSession.state();\n\t\tconst transition = isWritableItemLifecycle(currentView.lifecycleStatus)\n\t\t\t? this.currentItemSession.dispatch({ action: 'suspendAttempt' })\n\t\t\t: null;\n\t\tconst itemSession = transition?.result?.sessionState ?? this.currentItemSession.serialize();\n\t\tconst responses = cloneData(transition?.current.responses ?? currentView.responses) ?? {};\n\t\tthis.sessionCoordinator.saveItemSession(\n\t\t\tq.identifier,\n\t\t\tresponses,\n\t\t\titemSession,\n\t\t\ttransition?.current.duration ?? currentView.duration,\n\t\t);\n\t\treturn itemSession;\n\t}\n\n\tprivate endItemSessionForSubmit(\n\t\tq: FlatItem,\n\t\tresponses: Record<string, unknown>,\n\t\titemSession?: SerializedItemSessionState,\n\t): SerializedItemSessionState {\n\t\tconst active = this.items[this.currentItemIndex];\n\t\tif (\n\t\t\tactive === q &&\n\t\t\tthis.currentItemSession &&\n\t\t\tthis.currentItemSession.state().lifecycleStatus !== 'suspended'\n\t\t) {\n\t\t\tconst transition = this.currentItemSession.dispatch({ action: 'endAttempt' });\n\t\t\treturn transition.result?.sessionState ?? this.currentItemSession.serialize();\n\t\t}\n\n\t\tconst session = this.getItemDefinition(q).openSession({\n\t\t\trestore: itemSession,\n\t\t\tresponses: itemSession ? undefined : responses,\n\t\t\tactivate: true,\n\t\t});\n\t\ttry {\n\t\t\tconst transition = session.dispatch({ action: 'endAttempt' });\n\t\t\treturn transition.result?.sessionState ?? session.serialize();\n\t\t} finally {\n\t\t\tsession.dispose();\n\t\t}\n\t}\n\n\tprivate getItemDefinition(q: FlatItem): AssessmentItemDefinition {\n\t\tconst cached = this.itemDefinitions.get(q.identifier);\n\t\tif (cached) return cached;\n\n\t\tconst definition = createAssessmentItemDefinition({\n\t\t\titemXml: q.item.itemXml,\n\t\t\t// The assessment host chooses the authorized delivery role. Item refs are\n\t\t\t// content records and must not silently widen or narrow session capabilities.\n\t\t\trole: this.config.role ?? 'candidate',\n\t\t\ti18nProvider: this.i18nProvider,\n\t\t\tpnp: this.config.pnp,\n\t\t\tsecurity: this.config.security,\n\t\t\tpci: this.config.pci,\n\t\t\tplugins: this.config.plugins,\n\t\t\tdeliveryContext: q.item.deliveryContext,\n\t\t});\n\t\tthis.itemDefinitions.set(q.identifier, definition);\n\t\treturn definition;\n\t}\n\n\tprivate mirrorSessionResponses(\n\t\titemIdentifier: string,\n\t\tresponses: Readonly<Record<string, unknown>>,\n\t): boolean {\n\t\tconst current = this.sessionCoordinator.getResponses(itemIdentifier);\n\t\tif (responseValuesEqual(current, responses)) return false;\n\n\t\tconst snapshot = cloneResponseRecord(responses);\n\t\tthis.state.itemResponses[itemIdentifier] = snapshot as any;\n\t\tthis.sessionCoordinator.markAnswered(itemIdentifier, snapshot);\n\t\treturn true;\n\t}\n\n\tprivate attachCurrentItemSession(q: FlatItem, session: ItemSession): void {\n\t\tthis.currentItemSession = session;\n\t\tthis.currentItemSessionUnsubscribe = session.subscribe((transition) => {\n\t\t\tif (this.currentItemSession !== session) return;\n\t\t\tif (this.mirrorSessionResponses(q.identifier, transition.current.responses)) {\n\t\t\t\tthis.notifyResponseChange();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate releaseCurrentItemSession(): void {\n\t\tthis.currentItemSessionUnsubscribe?.();\n\t\tthis.currentItemSessionUnsubscribe = null;\n\t\tthis.currentItemSession?.dispose();\n\t\tthis.currentItemSession = null;\n\t}\n\n\t/**\n\t * Get the current session state snapshot (client-side view).\n\t * Note: backend remains authoritative; this is intended for simple save/resume.\n\t */\n\tpublic getState(options: { includeItemSessions?: boolean } = {}): AssessmentSessionState {\n\t\tconst snapshot = this.sessionCoordinator.snapshot(options);\n\t\tconst current = this.items[this.currentItemIndex];\n\t\tif (options.includeItemSessions && current && this.currentItemSession) {\n\t\t\t// Navigation snapshots may predate edits made after revisiting this item.\n\t\t\t// Serialize the live authority without suspending the learner's attempt.\n\t\t\tsnapshot.itemSessions = {\n\t\t\t\t...snapshot.itemSessions,\n\t\t\t\t[current.identifier]: this.currentItemSession.serialize(),\n\t\t\t};\n\t\t}\n\t\tconst timing = this.timeManager?.getState();\n\t\tif (timing) {\n\t\t\tsnapshot.timing = {\n\t\t\t\tstartedAt: timing.startedAt,\n\t\t\t\titemTimes: { ...timing.itemTimes },\n\t\t\t\tsectionTimes: { ...timing.sectionTimes },\n\t\t\t\ttestPartTimes: { ...timing.testPartTimes },\n\t\t\t\ttotalTime: timing.totalElapsed,\n\t\t\t\tcurrentItemIdentifier: timing.currentItemId,\n\t\t\t\tcurrentSectionIdentifier: timing.currentSectionId,\n\t\t\t\tcurrentTestPartIdentifier: timing.currentTestPartId,\n\t\t\t\tisPaused: timing.isPaused,\n\t\t\t};\n\t\t}\n\t\treturn snapshot;\n\t}\n\n\t/**\n\t * Restore a previously saved session state.\n\t */\n\tpublic async restoreState(state: AssessmentSessionState): Promise<void> {\n\t\tthis.state = state;\n\t\tthis.restoreTimeTracking(state.timing);\n\n\t\t// Restore visited state for UI navigation hints.\n\t\tconst visitedIdx = (state.visitedItems || [])\n\t\t\t.map((id) => this.items.findIndex((q) => q.identifier === id))\n\t\t\t.filter((i) => i >= 0);\n\t\tthis.navigationManager.restoreState(visitedIdx);\n\n\t\tconst currentId = state.currentItemIdentifier;\n\t\tconst idx = currentId ? this.items.findIndex((q) => q.identifier === currentId) : -1;\n\t\tif (idx >= 0) {\n\t\t\tawait this.navigateTo(idx, { restoring: true });\n\t\t} else if (this.items.length > 0) {\n\t\t\tawait this.navigateTo(0, { restoring: true });\n\t\t}\n\t}\n\n\tprivate restoreTimeTracking(timing: AssessmentSessionState['timing']): void {\n\t\tthis.timeManager?.restoreState({\n\t\t\ttotalElapsed: timing.totalTime,\n\t\t\titemTimes: { ...timing.itemTimes },\n\t\t\tsectionTimes: { ...(timing.sectionTimes ?? {}) },\n\t\t\ttestPartTimes: { ...(timing.testPartTimes ?? {}) },\n\t\t\tstartedAt: timing.startedAt,\n\t\t\tcurrentItemId: timing.currentItemIdentifier,\n\t\t\tcurrentSectionId: timing.currentSectionIdentifier,\n\t\t\tcurrentTestPartId: timing.currentTestPartIdentifier,\n\t\t\tisPaused: timing.isPaused === true,\n\t\t});\n\t}\n\n\tpublic async navigateTo(index: number, options: { restoring?: boolean } = {}): Promise<void> {\n\t\tif (index < 0 || index >= this.items.length) throw new Error(`Invalid item index: ${index}`);\n\n\t\t// Enforce navigation rules (UI hints, still backend-authoritative for real deployments).\n\t\tif (!options.restoring && this.currentItemIndex >= 0 && !this.canNavigateByTestPart(index, this.currentItemIndex)) {\n\t\t\tconst currentMode = this.items[this.currentItemIndex]?.testPart.navigationMode ?? this.assessment.navigationMode;\n\t\t\tif (currentMode === 'linear' && index > this.currentItemIndex + 1) {\n\t\t\t\tthrow new Error('In linear navigation mode, you can only move to the next question.');\n\t\t\t}\n\t\t\tthrow new Error('Navigation is not allowed.');\n\t\t}\n\t\tconst target = this.items[index];\n\t\tif (!options.restoring && target && !this.sessionCoordinator.canReview(target.identifier)) {\n\t\t\tthrow new Error('You cannot go back to previous questions in this assessment.');\n\t\t}\n\n\t\tconst currentItem = this.items[this.currentItemIndex];\n\t\tif (!options.restoring && currentItem && target) {\n\t\t\tthis.assertTransitionMinimum(currentItem, target);\n\t\t\tif (currentItem.testPart !== target.testPart\n\t\t\t\t&& (currentItem.testPart.submissionMode ?? this.assessment.submissionMode) === 'simultaneous') {\n\t\t\t\t// Commit this part before leaving it; a failed request keeps the learner\n\t\t\t\t// in the current part so its remaining answers can be retried.\n\t\t\t\tawait this.submitSimultaneousItems(this.items.filter((q) => q.testPart === currentItem.testPart));\n\t\t\t}\n\t\t}\n\t\tif (!options.restoring && this.currentItemIndex === index && this.currentItemSession) {\n\t\t\treturn;\n\t\t}\n\t\tconst currentSessionStatus = currentItem\n\t\t\t? this.currentItemSession?.state().lifecycleStatus ??\n\t\t\t\tthis.state.itemSessions?.[currentItem.identifier]?.lifecycleStatus\n\t\t\t: undefined;\n\t\tif (\n\t\t\t!options.restoring &&\n\t\t\tthis.currentItemIndex >= 0 &&\n\t\t\tthis.currentItemIndex !== index &&\n\t\t\tcurrentSessionStatus !== 'closed'\n\t\t) {\n\t\t\tthis.saveCurrentItemSession();\n\t\t}\n\t\tif (currentItem && this.currentItemIndex !== index) {\n\t\t\tthis.timeManager?.endItem(currentItem.identifier);\n\t\t}\n\n\t\tthis.currentItemIndex = index;\n\t\tconst q = this.items[index]!;\n\t\tthis.state.currentItemIdentifier = q.identifier;\n\t\tthis.timeManager?.activateScopes({\n\t\t\ttestPart: { identifier: q.testPart.identifier, timeLimits: q.testPart.timeLimits },\n\t\t\tsection: { identifier: q.section.identifier, timeLimits: q.section.timeLimits },\n\t\t\titem: { identifier: q.identifier, timeLimits: q.item.timeLimits },\n\t\t});\n\n\t\t// Apply three-level itemSessionControl fallback for this item's section (S1).\n\t\tconst effectiveControl = this.getEffectiveItemSessionControl(q);\n\t\tif (effectiveControl) {\n\t\t\tthis.sessionCoordinator.updateItemSessionControl(effectiveControl);\n\t\t}\n\n\t\t// Restore responses into one live session owned by the assessment. The section\n\t\t// composition and item renderer receive this exact object.\n\t\tconst responses = this.sessionCoordinator.activateItem(q.identifier);\n\t\tconst restoredItemSession = this.state.itemSessions?.[q.identifier];\n\t\tthis.releaseCurrentItemSession();\n\t\tconst session = this.getItemDefinition(q).openSession({\n\t\t\trestore: restoredItemSession,\n\t\t\tresponses: restoredItemSession ? undefined : responses,\n\t\t\tactivate: true,\n\t\t});\n\t\tthis.attachCurrentItemSession(q, session);\n\n\t\tthis.notifyItemChange();\n\t\tthis.notifySectionChange();\n\t}\n\n\tpublic async navigateToSection(sectionId: string): Promise<void> {\n\t\tconst idx = this.items.findIndex((q) => q.section.identifier === sectionId);\n\t\tif (idx >= 0) await this.navigateTo(idx);\n\t}\n\n\tpublic async next(): Promise<void> {\n\t\tconst state = this.getNavigationState();\n\t\tif (!state.canNext) return;\n\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (q) {\n\t\t\tconst responses = this.sessionCoordinator.getActiveResponses();\n\t\t\tthis.sessionCoordinator.markAnswered(q.identifier, responses);\n\n\t\t\tconst navAway = this.sessionCoordinator.canNavigateAway(q.identifier, responses);\n\t\t\tif (!navAway.allowed) {\n\t\t\t\tthrow new Error(navAway.reason || 'You must answer this question before continuing.');\n\t\t\t}\n\n\t\t\t// In individual submission mode, submit current item before moving forward.\n\t\t\tif ((q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual') {\n\t\t\t\tconst before = this.currentItemIndex;\n\t\t\t\tawait this.submitCurrentItem();\n\t\t\t\t// submitCurrentItem may branch/navigate; if it did, we're done.\n\t\t\t\tif (this.currentItemIndex !== before) return;\n\t\t\t}\n\t\t}\n\n\t\tawait this.navigateTo(this.currentItemIndex + 1);\n\t}\n\n\tpublic async previous(): Promise<void> {\n\t\tconst state = this.getNavigationState();\n\t\tif (!state.canPrevious) return;\n\t\tawait this.navigateTo(this.currentItemIndex - 1);\n\t}\n\n\t/** Submit current item (server-side scoring) */\n\tpublic async submitCurrentItem(): Promise<ItemResult> {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q) throw new Error('No current item');\n\t\tthis.assertMinimumTime('item', q);\n\n\t\tconst submittedAt = Date.now();\n\t\tlet itemSession: SerializedItemSessionState | undefined;\n\t\tconst submittedSession = this.currentItemSession;\n\t\tconst preSubmitSession = submittedSession?.serialize();\n\t\tconst responses = this.currentItemSession\n\t\t\t? cloneResponseRecord(this.currentItemSession.state().responses)\n\t\t\t: this.sessionCoordinator.getActiveResponses();\n\t\tlet res: Awaited<ReturnType<BackendAdapter['submitResponses']>>;\n\t\ttry {\n\t\t\tif (submittedSession) {\n\t\t\t\tconst transition = submittedSession.dispatch({\n\t\t\t\t\taction: 'endAttempt',\n\t\t\t\t\tvalidateResponses: this.sessionCoordinator.mustValidateResponses(),\n\t\t\t\t});\n\t\t\t\tconst attempt = transition.result;\n\t\t\t\tif (!attempt) throw new Error('Item session did not produce an end-attempt result');\n\t\t\t\tif (attempt.validation && !attempt.validation.valid) {\n\t\t\t\t\tthrow new Error(attempt.validation.issues[0]?.message || 'Submit failed: invalid response');\n\t\t\t\t}\n\t\t\t\titemSession = attempt.sessionState;\n\t\t\t}\n\t\t\tres = await this.backend.submitResponses({\n\t\t\t\tsessionId: this.sessionId,\n\t\t\t\titemIdentifier: q.identifier,\n\t\t\t\tresponses: responses as any,\n\t\t\t\tsubmittedAt,\n\t\t\t\ttimeSpent: itemSession?.duration,\n\t\t\t\ttiming: this.getSubmitTimingEvidence(q, itemSession?.duration ?? 0),\n\t\t\t\titemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,\n\t\t\t});\n\n\t\t\tif (!res.success || !res.result) {\n\t\t\t\tthrow new Error(res.error || 'Submit failed');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Ending an attempt is a local provisional commit until the backend accepts\n\t\t\t// it. Restore the exact pre-submit lifecycle so a transient failure can be\n\t\t\t// retried without a closed item or a double-counted attempt.\n\t\t\tif (\n\t\t\t\tsubmittedSession &&\n\t\t\t\tpreSubmitSession &&\n\t\t\t\tthis.currentItemSession === submittedSession &&\n\t\t\t\tthis.items[this.currentItemIndex] === q\n\t\t\t) {\n\t\t\t\tthis.releaseCurrentItemSession();\n\t\t\t\tthis.attachCurrentItemSession(\n\t\t\t\t\tq,\n\t\t\t\t\tthis.getItemDefinition(q).openSession({ restore: preSubmitSession }),\n\t\t\t\t);\n\t\t\t\tthis.notifyItemChange();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (itemSession) {\n\t\t\tthis.sessionCoordinator.setItemSession(q.identifier, itemSession);\n\t\t}\n\n\t\tif (res.updatedState) {\n\t\t\tconst localResponses = cloneData(this.state.itemResponses || {})!;\n\t\t\tlocalResponses[q.identifier] = cloneResponseRecord(responses) as any;\n\t\t\tthis.sessionCoordinator.replaceStatePreservingResponsesAndSessions(\n\t\t\t\tres.updatedState,\n\t\t\t\tlocalResponses,\n\t\t\t\tcloneData(this.state.itemSessions || {})!,\n\t\t\t);\n\t\t} else {\n\t\t\t// Minimal state update when backend doesn't return full state.\n\t\t\tthis.state.itemScores = this.state.itemScores || {};\n\t\t\tthis.state.itemScores[q.identifier] = res.result;\n\t\t\tthis.sessionCoordinator.markVisited(q.identifier);\n\t\t\tthis.state.itemResponses[q.identifier] = responses as any;\n\t\t\tif (itemSession) {\n\t\t\t\tthis.sessionCoordinator.setItemSession(q.identifier, itemSession);\n\t\t\t}\n\t\t}\n\n\t\tconst itemResult: ItemResult = {\n\t\t\titemIdentifier: q.identifier,\n\t\t\tscore: res.result.score,\n\t\t\tmaxScore: res.result.maxScore,\n\t\t\tresponses: { ...responses },\n\t\t};\n\t\tthis.sessionCoordinator.setItemResult(itemResult);\n\n\t\t// Track item session rules (review/attempts) and visited items for navigation hints.\n\t\ttry {\n\t\t\tthis.sessionCoordinator.recordAttempt(q.identifier);\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\t\tthis.sessionCoordinator.markAnswered(q.identifier, responses);\n\t\tthis.navigationManager.markVisited(this.currentItemIndex);\n\n\t\t// Apply backend branching decision if provided.\n\t\t// Special QTI targets EXIT_TEST / EXIT_TESTPART / EXIT_SECTION trigger finalization.\n\t\tif (res.nextItemIdentifier) {\n\t\t\tconst special = res.nextItemIdentifier;\n\t\t\tif (special === 'EXIT_TEST') {\n\t\t\t\t// Finalize immediately — no further navigation\n\t\t\t\tfor (const l of this.completeListeners) l();\n\t\t\t\tthis.config.onComplete?.();\n\t\t\t} else if (special === 'EXIT_TESTPART' || special === 'EXIT_SECTION') {\n\t\t\t\t// Advance past all remaining items in the current testPart or section\n\t\t\t\tconst currentItem = this.items[this.currentItemIndex];\n\t\t\t\tconst isSection = special === 'EXIT_SECTION';\n\t\t\t\tconst nextIdx = this.items.findIndex((item, i) =>\n\t\t\t\t\ti > this.currentItemIndex &&\n\t\t\t\t\t(isSection\n\t\t\t\t\t\t? item.section.identifier !== currentItem?.section.identifier\n\t\t\t\t\t\t: item.testPart.identifier !== currentItem?.testPart.identifier)\n\t\t\t\t);\n\t\t\t\tif (nextIdx >= 0) {\n\t\t\t\t\tawait this.navigateTo(nextIdx, { restoring: true });\n\t\t\t\t} else {\n\t\t\t\t\t// No further items — signal completion\n\t\t\t\t\tfor (const l of this.completeListeners) l();\n\t\t\t\t\tthis.config.onComplete?.();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst nextIdx = this.items.findIndex((x) => x.identifier === special);\n\t\t\t\tif (nextIdx >= 0) {\n\t\t\t\t\tawait this.navigateTo(nextIdx, { restoring: true });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn itemResult;\n\t}\n\n\tprivate canPrevious(): boolean {\n\t\tif (this.currentItemIndex <= 0) return false;\n\t\tconst prev = this.items[this.currentItemIndex - 1];\n\t\tif (!prev) return false;\n\t\tif (!this.canNavigateByTestPart(this.currentItemIndex - 1, this.currentItemIndex)) return false;\n\t\treturn this.sessionCoordinator.canReview(prev.identifier);\n\t}\n\n\tprivate canNext(): boolean {\n\t\tif (this.currentItemIndex < 0) return false;\n\t\tconst nextIdx = this.currentItemIndex + 1;\n\t\tif (nextIdx >= this.items.length) return false;\n\t\tif (!this.canNavigateByTestPart(nextIdx, this.currentItemIndex)) return false;\n\t\t// Note: itemSessionControl constraints on leaving current item are enforced in next().\n\t\treturn true;\n\t}\n\n\tprivate canNavigateByTestPart(targetIndex: number, currentIndex: number): boolean {\n\t\tif (targetIndex < 0 || targetIndex >= this.items.length) return false;\n\t\tconst current = this.items[currentIndex];\n\t\tconst target = this.items[targetIndex];\n\t\tif (!current || !target) return false;\n\t\tif (current.testPart !== target.testPart) {\n\t\t\t// QTI testParts are delivered in sequence. A candidate may enter the next\n\t\t\t// part, but cannot jump across parts or return to a completed part.\n\t\t\treturn targetIndex === currentIndex + 1;\n\t\t}\n\t\tconst mode = current.testPart.navigationMode ?? this.assessment.navigationMode ?? 'nonlinear';\n\t\treturn mode === 'nonlinear' || targetIndex === currentIndex || targetIndex === currentIndex + 1;\n\t}\n\n\tprivate async submitSimultaneousItems(items: readonly FlatItem[]): Promise<void> {\n\t\tif (items.every((q) => this.sessionCoordinator.hasItemResult(q.identifier))) return;\n\t\tconst current = this.items[this.currentItemIndex];\n\t\tconst submittedItem = current && items.includes(current) ? current : undefined;\n\t\tconst preSubmitSession = submittedItem ? this.currentItemSession?.serialize() : undefined;\n\t\tlet allItemSessions: NonNullable<AssessmentSessionState['itemSessions']> = {};\n\n\t\ttry {\n\t\t\t// Suspending the rendered session gives the UI one non-writable state while\n\t\t\t// backend submission is in flight. Detached sessions perform the provisional\n\t\t\t// end-attempt work for every item.\n\t\t\tif (submittedItem) this.saveCurrentItemSession();\n\t\t\t// Preserve client-collected responses across backend state updates.\n\t\t\t// Some backend adapters return an updatedState snapshot that may only include\n\t\t\t// responses for items that have been submitted so far, which would otherwise\n\t\t\t// wipe out responses for later items during this loop.\n\t\t\tconst allItemResponses = cloneData(this.state.itemResponses || {}) as any;\n\t\t\tallItemSessions = cloneData(this.state.itemSessions || {})!;\n\n\t\t\tfor (const q of items) {\n\t\t\t\tif (this.sessionCoordinator.hasItemResult(q.identifier)) continue;\n\t\t\t\tconst submittedAt = Date.now();\n\t\t\t\tconst responsesForItem = (allItemResponses?.[q.identifier] || {}) as any;\n\t\t\t\tconst itemSession = this.endItemSessionForSubmit(\n\t\t\t\t\tq,\n\t\t\t\t\tresponsesForItem,\n\t\t\t\t\tallItemSessions[q.identifier],\n\t\t\t\t);\n\t\t\t\tallItemSessions[q.identifier] = itemSession;\n\t\t\t\tconst res = await this.backend.submitResponses({\n\t\t\t\t\tsessionId: this.sessionId,\n\t\t\t\t\titemIdentifier: q.identifier,\n\t\t\t\t\tresponses: responsesForItem,\n\t\t\t\t\tsubmittedAt,\n\t\t\t\t\ttimeSpent: itemSession.duration,\n\t\t\t\t\ttiming: this.getSubmitTimingEvidence(q, itemSession.duration),\n\t\t\t\t\titemSession: this.config.sendItemSessionToBackend ? itemSession : undefined,\n\t\t\t\t});\n\t\t\t\tif (!res.success || !res.result) {\n\t\t\t\t\tthrow new Error(res.error || `Submit failed for item ${q.identifier}`);\n\t\t\t\t}\n\t\t\t\tif (res.updatedState) {\n\t\t\t\t\tthis.sessionCoordinator.replaceStatePreservingResponsesAndSessions(\n\t\t\t\t\t\tres.updatedState,\n\t\t\t\t\t\tallItemResponses,\n\t\t\t\t\t\tallItemSessions,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthis.state.itemScores = this.state.itemScores || {};\n\t\t\t\t\tthis.state.itemScores[q.identifier] = res.result;\n\t\t\t\t\tthis.sessionCoordinator.markVisited(q.identifier);\n\t\t\t\t\tthis.state.itemResponses[q.identifier] = responsesForItem;\n\t\t\t\t\tthis.sessionCoordinator.setItemSession(q.identifier, itemSession);\n\t\t\t\t\tthis.sessionCoordinator.recordAttempt(q.identifier);\n\t\t\t\t}\n\t\t\t\tthis.sessionCoordinator.setItemResult({\n\t\t\t\t\titemIdentifier: q.identifier,\n\t\t\t\t\tscore: res.result.score,\n\t\t\t\t\tmaxScore: res.result.maxScore,\n\t\t\t\t\tresponses: this.state.itemResponses[q.identifier] || {},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// The attached item must represent the same accepted lifecycle as persistence.\n\t\t\t// Replace the provisional suspended object with one restored from the accepted\n\t\t\t// closed state; no second live state owner remains.\n\t\t\tif (submittedItem && this.items[this.currentItemIndex] === submittedItem) {\n\t\t\t\tconst accepted = allItemSessions[submittedItem.identifier];\n\t\t\t\tif (accepted) {\n\t\t\t\t\tthis.releaseCurrentItemSession();\n\t\t\t\t\tthis.attachCurrentItemSession(\n\t\t\t\t\t\tsubmittedItem,\n\t\t\t\t\t\tthis.getItemDefinition(submittedItem).openSession({ restore: accepted }),\n\t\t\t\t\t);\n\t\t\t\t\tthis.notifyItemChange();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The backend accepts simultaneous items one request at a time. Keep earlier\n\t\t\t// accepted items committed so retry cannot double-submit them. If the rendered\n\t\t\t// item was not accepted, restore only that item to its exact writable state.\n\t\t\tif (submittedItem && this.items[this.currentItemIndex] === submittedItem) {\n\t\t\t\tconst accepted = this.sessionCoordinator.hasItemResult(submittedItem.identifier)\n\t\t\t\t\t? allItemSessions[submittedItem.identifier]\n\t\t\t\t\t: undefined;\n\t\t\t\tconst restored = accepted ?? preSubmitSession;\n\t\t\t\tif (!accepted && preSubmitSession) {\n\t\t\t\t\tthis.sessionCoordinator.saveItemSession(\n\t\t\t\t\t\tsubmittedItem.identifier,\n\t\t\t\t\t\tcloneResponseRecord(valuesFromItemSession(preSubmitSession)),\n\t\t\t\t\t\tpreSubmitSession,\n\t\t\t\t\t\tpreSubmitSession.duration,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis.releaseCurrentItemSession();\n\t\t\t\tif (restored) {\n\t\t\t\t\tthis.attachCurrentItemSession(\n\t\t\t\t\t\tsubmittedItem,\n\t\t\t\t\t\tthis.getItemDefinition(submittedItem).openSession({ restore: restored }),\n\t\t\t\t\t);\n\t\t\t\t\tthis.notifyItemChange();\n\t\t\t\t\tthis.notifyResponseChange();\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Submit entire assessment (finalize on backend) */\n\tpublic async submit(): Promise<AssessmentResults> {\n\t\tconst current = this.items[this.currentItemIndex];\n\t\tif (current) {\n\t\t\tthis.assertMinimumTime('item', current);\n\t\t\tthis.assertMinimumTime('section', current);\n\t\t\tthis.assertMinimumTime('testPart', current);\n\t\t\tthis.assertMinimumTime('assessment', current);\n\t\t}\n\t\t// Submission modes belong to test parts. The assessment-level field is only\n\t\t// a fallback for older hosts that do not supply a mode on each part.\n\t\tawait this.submitSimultaneousItems(this.items.filter((q) =>\n\t\t\t(q.testPart.submissionMode ?? this.assessment.submissionMode) === 'simultaneous',\n\t\t));\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (q && (q.testPart.submissionMode ?? this.assessment.submissionMode) === 'individual'\n\t\t\t&& !this.sessionCoordinator.hasItemResult(q.identifier)) {\n\t\t\tawait this.submitCurrentItem();\n\t\t}\n\n\t\tconst finalized: FinalizeAssessmentResponse = await this.backend.finalizeAssessment({\n\t\t\tsessionId: this.sessionId,\n\t\t});\n\t\tif (!finalized.success) throw new Error('Finalize failed');\n\n\t\t// Map backend itemScores to ItemResult[]\n\t\tconst itemScores = finalized.itemScores || {};\n\t\tconst itemResults: ItemResult[] = Object.values(itemScores).map((r: AssessmentScoringResult) => ({\n\t\t\titemIdentifier: r.itemIdentifier,\n\t\t\tscore: r.score,\n\t\t\tmaxScore: r.maxScore,\n\t\t\tresponses: this.state.itemResponses[r.itemIdentifier] || {},\n\t\t}));\n\n\t\t// Evaluate testFeedback visibility using QTI string equality:\n\t\t// show when outcomeIdentifier's value equals feedback.identifier (for showHide='show'),\n\t\t// or does NOT equal it (for showHide='hide').\n\t\tconst structuredFeedback = this.assessment.testFeedback ?? [];\n\t\tconst outcomes = finalized.outcomes ?? {};\n\t\tif (structuredFeedback.length > 0) {\n\t\t\tthis.visibleFeedback = structuredFeedback\n\t\t\t\t.filter((fb) => fb.access === 'atEnd')\n\t\t\t\t.filter((fb) => {\n\t\t\t\t\tconst outcomeValue = String(outcomes[fb.outcomeIdentifier] ?? '');\n\t\t\t\t\tconst matches = outcomeValue === fb.identifier;\n\t\t\t\t\treturn fb.showHide === 'show' ? matches : !matches;\n\t\t\t\t})\n\t\t\t\t.map((fb) => ({ identifier: fb.identifier, content: fb.content, access: fb.access }));\n\t\t} else {\n\t\t\t// Legacy: backend returns a plain feedback string\n\t\t\tthis.visibleFeedback = finalized.feedback\n\t\t\t\t? [{ identifier: 'testFeedback', content: finalized.feedback, access: 'atEnd' }]\n\t\t\t\t: [];\n\t\t}\n\n\t\tthis.notifyComplete();\n\t\tif (this.config.onComplete) this.config.onComplete();\n\n\t\treturn {\n\t\t\ttotalScore: finalized.totalScore,\n\t\t\tmaxScore: finalized.maxScore,\n\t\t\titemResults,\n\t\t\tcompletedAt: new Date(finalized.finalizedAt),\n\t\t};\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Session info + time helpers\n\t// ---------------------------------------------------------------------------\n\n\tpublic getItemSessionInfo(_itemIdentifier?: string): {\n\t\tcanSubmit: boolean;\n\t\tremainingAttempts: number | null;\n\t\tattemptCount: number;\n\t\tshowFeedback: boolean;\n\t\tshowSolution: boolean;\n\t\tcanReview: boolean;\n\t\tcanSkip: boolean;\n\t} | null {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tif (!q) return null;\n\t\tconst id = q.identifier;\n\n\t\treturn this.sessionCoordinator.getItemSessionInfo(id);\n\t}\n\n\tpublic getRemainingTime(): number {\n\t\t// TimeManager exposes seconds getters.\n\t\treturn this.timeManager?.getRemainingSeconds() ?? 0;\n\t}\n\n\tpublic getElapsedTime(): number {\n\t\treturn this.timeManager?.getElapsedSeconds() ?? 0;\n\t}\n\n\tpublic isTimeExpired(): boolean {\n\t\treturn this.timeManager?.isExpired() ?? false;\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Event subscriptions\n\t// ---------------------------------------------------------------------------\n\n\tpublic onItemChange(listener: (index: number, total: number) => void): () => void {\n\t\tthis.itemChangeListeners.add(listener);\n\t\treturn () => this.itemChangeListeners.delete(listener);\n\t}\n\n\tpublic onSectionChange(listener: (index: number, total: number) => void): () => void {\n\t\tthis.sectionChangeListeners.add(listener);\n\t\treturn () => this.sectionChangeListeners.delete(listener);\n\t}\n\n\tpublic onResponseChange(listener: (responses: Record<string, unknown>) => void): () => void {\n\t\tthis.responseChangeListeners.add(listener);\n\t\treturn () => this.responseChangeListeners.delete(listener);\n\t}\n\n\tpublic onComplete(listener: () => void): () => void {\n\t\tthis.completeListeners.add(listener);\n\t\treturn () => this.completeListeners.delete(listener);\n\t}\n\n\tpublic onTimeWarning(listener: (remainingSeconds: number) => void): () => void {\n\t\tthis.timeWarningListeners.add(listener);\n\t\treturn () => this.timeWarningListeners.delete(listener);\n\t}\n\n\tpublic onTimeExpired(listener: () => void): () => void {\n\t\tthis.timeExpiredListeners.add(listener);\n\t\treturn () => this.timeExpiredListeners.delete(listener);\n\t}\n\n\tpublic onTimeTick(listener: (remainingSeconds: number, elapsedSeconds: number) => void): () => void {\n\t\tthis.timeTickListeners.add(listener);\n\t\treturn () => this.timeTickListeners.delete(listener);\n\t}\n\n\tpublic destroy(): void {\n\t\tthis.timeManager?.destroy();\n\t\tthis.releaseCurrentItemSession();\n\t\tthis.itemDefinitions.clear();\n\t\tthis.itemChangeListeners.clear();\n\t\tthis.sectionChangeListeners.clear();\n\t\tthis.responseChangeListeners.clear();\n\t\tthis.completeListeners.clear();\n\t\tthis.timeWarningListeners.clear();\n\t\tthis.timeExpiredListeners.clear();\n\t\tthis.timeTickListeners.clear();\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Internal notify helpers\n\t// ---------------------------------------------------------------------------\n\n\tprivate notifyItemChange(): void {\n\t\tfor (const l of this.itemChangeListeners) l(this.currentItemIndex, this.items.length);\n\t\tthis.config.onItemChange?.(this.currentItemIndex, this.items.length);\n\t}\n\n\tprivate notifySectionChange(): void {\n\t\tconst q = this.items[this.currentItemIndex];\n\t\tconst sectionIndex = q?.sectionIndex ?? 0;\n\t\tconst totalSections = this.getAllSections().length;\n\t\tfor (const l of this.sectionChangeListeners) l(sectionIndex, totalSections);\n\t\tthis.config.onSectionChange?.(sectionIndex, totalSections);\n\t}\n\n\tprivate notifyResponseChange(): void {\n\t\tconst responses = this.sessionCoordinator.getActiveResponses();\n\t\tfor (const l of this.responseChangeListeners) l(responses);\n\t\tthis.config.onResponseChange?.(responses);\n\t}\n\n\tprivate notifyComplete(): void {\n\t\tfor (const l of this.completeListeners) l();\n\t}\n\n\tprivate notifyTimeWarning(remainingSeconds: number): void {\n\t\tfor (const l of this.timeWarningListeners) l(remainingSeconds);\n\t}\n\n\tprivate notifyTimeExpired(): void {\n\t\tfor (const l of this.timeExpiredListeners) l();\n\t}\n\n\tprivate notifyTimeTick(remainingSeconds: number, elapsedSeconds: number): void {\n\t\tfor (const l of this.timeTickListeners) l(remainingSeconds, elapsedSeconds);\n\t}\n\n\t/**\n\t * Get the i18n provider instance\n\t * @returns I18nProvider instance\n\t */\n\tpublic getI18nProvider(): I18nProvider {\n\t\treturn this.i18nProvider;\n\t}\n\n\t/**\n\t * Create a simple fallback i18n provider when none is provided\n\t */\n\tprivate createDefaultI18nProvider(): I18nProvider {\n\t\treturn {\n\t\t\tgetLocale: () => 'en-US',\n\t\t\tsetLocale: () => {},\n\t\t\tt: (key: string) => key, // Fallback to key\n\t\t\tplural: (key: string) => key,\n\t\t\tformatNumber: (value: number) => value.toString(),\n\t\t\tformatDate: (date: Date) => date.toISOString(),\n\t\t};\n\t}\n}\n\n/** Fisher-Yates shuffle using a provided RNG (returns a new array). */\nfunction shuffleArray<T>(arr: 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(\n\tcomponents: SecureSectionComponent[],\n\trng: () => number,\n): SecureSectionComponent[] {\n\tconst result = [...components];\n\tconst movableIndexes = components\n\t\t.map((component, index) => ({ component, index }))\n\t\t.filter(({ component }) => !isFixedSectionComponent(component))\n\t\t.map(({ index }) => index);\n\tconst shuffled = shuffleArray(\n\t\tmovableIndexes.map((index) => components[index]!),\n\t\trng,\n\t);\n\tfor (let index = 0; index < movableIndexes.length; index++) {\n\t\tresult[movableIndexes[index]!] = shuffled[index]!;\n\t}\n\treturn result;\n}\n\nfunction cloneData<T>(value: T | undefined): T | undefined {\n\treturn value === undefined ? undefined : structuredClone(value);\n}\n\nfunction cloneResponseRecord(\n\tresponses: Readonly<Record<string, unknown>>,\n): Record<string, unknown> {\n\treturn structuredClone(responses) as Record<string, unknown>;\n}\n\nfunction valuesFromItemSession(\n\tstate: SerializedItemSessionState,\n): Record<string, unknown> {\n\treturn Object.fromEntries(\n\t\tObject.entries(state.responseVariables).map(([identifier, variable]) => [\n\t\t\tidentifier,\n\t\t\tcloneData(variable.value),\n\t\t]),\n\t);\n}\n\nfunction responseValuesEqual(left: unknown, right: unknown): boolean {\n\tif (Object.is(left, right)) return true;\n\tif (Array.isArray(left) || Array.isArray(right)) {\n\t\tif (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n\t\treturn left.every((value, index) => responseValuesEqual(value, right[index]));\n\t}\n\tif (!isRecord(left) || !isRecord(right)) return false;\n\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\tif (leftKeys.length !== rightKeys.length) return false;\n\tconst rightKeySet = new Set(rightKeys);\n\treturn leftKeys.every(\n\t\t(key) => rightKeySet.has(key) && responseValuesEqual(left[key], right[key]),\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === 'object';\n}\n\nfunction isWritableItemLifecycle(lifecycleStatus: SerializedItemSessionState['lifecycleStatus']): boolean {\n\treturn lifecycleStatus === 'initial' || lifecycleStatus === 'interacting';\n}\n","import { normalizeQtiSharedContext } from '@pie-qti/assessment-toolkit';\nimport {\n\tresolveQtiSectionComposition,\n\ttype QtiSectionItemRef,\n\ttype QtiSectionRole,\n\ttype QtiSectionToolConfig,\n\ttype ResolvedQtiSectionComposition,\n} from '@pie-qti/section-player';\nimport type { AssessmentPlayer, BackendAssessmentPlayerConfig } from '../core/AssessmentPlayer.js';\n\nfunction toSectionRole(role: BackendAssessmentPlayerConfig['role']): QtiSectionRole {\n\tswitch (role) {\n\t\tcase 'author':\n\t\tcase 'candidate':\n\t\tcase 'proctor':\n\t\tcase 'scorer':\n\t\tcase 'testConstructor':\n\t\tcase 'tutor':\n\t\t\treturn role;\n\t\tdefault:\n\t\t\treturn 'candidate';\n\t}\n}\n\nfunction scopedTools(tools: QtiSectionToolConfig[] | undefined, scope: QtiSectionToolConfig['scope']): QtiSectionToolConfig[] | undefined {\n\tif (!tools || tools.length === 0) return undefined;\n\treturn tools.map((tool) => ({ ...tool, scope }));\n}\n\nexport function toSectionComposition(\n\tplayer: AssessmentPlayer,\n\tconfig: Partial<BackendAssessmentPlayerConfig> = {}\n): ResolvedQtiSectionComposition {\n\tconst navState = player.getNavigationState();\n\tconst currentItem = player.getCurrentItem();\n\tconst role = toSectionRole(config.role);\n\tconst sharedContext = normalizeQtiSharedContext({\n\t\trubricBlocks: player.getCurrentSharedRubricBlocks(),\n\t\trole,\n\t\tpassageTools: scopedTools(config.passageTools, 'passage'),\n\t});\n\tconst activeSession = player.getCurrentItemSession();\n\tconst sectionItems: QtiSectionItemRef[] = player.getCurrentSectionItemRefs().map((item) => {\n\t\tconst common = {\n\t\t\tidentifier: item.identifier,\n\t\t\thref: item.href,\n\t\t\ttitle: item.title,\n\t\t\titemXml: item.itemXml,\n\t\t\tdeliveryContext: item.deliveryContext,\n\t\t\ttools: scopedTools(config.itemTools, 'item'),\n\t\t};\n\t\treturn item.identifier === currentItem?.identifier && activeSession\n\t\t\t? { ...common, session: activeSession }\n\t\t\t: { ...common, responses: player.getResponsesForItem(item.identifier) };\n\t});\n\n\treturn resolveQtiSectionComposition({\n\t\tsection: {\n\t\t\tidentifier: navState.currentSection?.id ?? 'active-section',\n\t\t\ttitle: navState.currentSection?.title ?? currentItem?.title,\n\t\t\trole,\n\t\t\tlayoutPreference: sharedContext.passages.length > 0 ? 'split-pane' : 'vertical',\n\t\t\ttools: scopedTools(config.sectionTools, 'section'),\n\t\t\titemRefs: sectionItems,\n\t\t\tsharedContext,\n\t\t},\n\t\tactiveItemIdentifier: currentItem?.identifier,\n\t\tcanPrevious: navState.canPrevious,\n\t\tcanNext: navState.canNext,\n\t\tsecurity: config.security,\n\t\thost: config.sectionHost,\n\t});\n}\n","<script lang=\"ts\">\n\timport { onDestroy } from 'svelte';\n\n\t/**\n\t * Accessibility Announcer Component\n\t *\n\t * Provides ARIA live region for announcing dynamic content changes\n\t * to screen reader users, particularly for state restoration.\n\t *\n\t * Usage:\n\t * ```svelte\n\t * <AccessibilityAnnouncer bind:this={announcer} />\n\t *\n\t * // Later announce something\n\t * announcer.announce('Session restored from previous attempt');\n\t * ```\n\t */\n\n\tinterface Props {\n\t\t/** Priority level for announcements */\n\t\tpriority?: 'polite' | 'assertive';\n\t}\n\n\tconst { priority = 'polite' }: Props = $props();\n\n\tlet announcement = $state('');\n\tlet currentPriority = $state<'polite' | 'assertive'>('polite');\n\tlet announceTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\t$effect(() => {\n\t\tif (!announcement) {\n\t\t\tcurrentPriority = priority;\n\t\t}\n\t});\n\n\t// Clean up timeout on destroy to prevent memory leaks\n\tonDestroy(() => {\n\t\tif (announceTimeout) {\n\t\t\tclearTimeout(announceTimeout);\n\t\t\tannounceTimeout = null;\n\t\t}\n\t});\n\n\t/**\n\t * Announce a message to screen readers\n\t *\n\t * @param message - Text to announce\n\t * @param clearAfter - Milliseconds to wait before clearing (default: 1000)\n\t * @param nextPriority - Announcement priority for this message\n\t */\n\texport function announce(message: string, clearAfter = 1000, nextPriority: 'polite' | 'assertive' = priority): void {\n\t\t// Clear any existing announcement timeout\n\t\tif (announceTimeout) {\n\t\t\tclearTimeout(announceTimeout);\n\t\t\tannounceTimeout = null;\n\t\t}\n\n\t\t// Set the new announcement\n\t\tcurrentPriority = nextPriority;\n\t\tannouncement = message;\n\n\t\t// Clear after delay to allow screen readers to announce\n\t\t// and prepare for next announcement\n\t\tannounceTimeout = setTimeout(() => {\n\t\t\tannouncement = '';\n\t\t\tcurrentPriority = priority;\n\t\t\tannounceTimeout = null;\n\t\t}, clearAfter);\n\t}\n\n\t/**\n\t * Clear the current announcement immediately\n\t */\n\texport function clear(): void {\n\t\tif (announceTimeout) {\n\t\t\tclearTimeout(announceTimeout);\n\t\t\tannounceTimeout = null;\n\t\t}\n\t\tannouncement = '';\n\t\tcurrentPriority = priority;\n\t}\n</script>\n\n<!--\n\tARIA live region for screen reader announcements\n\t- visually-hidden: Hide from sighted users but available to screen readers\n\t- aria-live: Announce changes to this region\n\t- aria-atomic: Read entire region content when it changes\n\t- role=\"status\": Indicates this is a status message\n-->\n<div\n\tclass=\"sr-only\"\n\trole=\"status\"\n\taria-live={currentPriority}\n\taria-atomic=\"true\"\n>\n\t{announcement}\n</div>\n\n<style>\n\t/* Screen reader only - visually hidden but accessible */\n\t.sr-only {\n\t\tposition: absolute;\n\t\twidth: 1px;\n\t\theight: 1px;\n\t\tpadding: 0;\n\t\tmargin: -1px;\n\t\toverflow: hidden;\n\t\tclip: rect(0, 0, 0, 0);\n\t\twhite-space: nowrap;\n\t\tborder-width: 0;\n\t}\n</style>\n","<script lang=\"ts\">\n\timport { tick } from 'svelte';\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\n\tinterface Section {\n\t\tid: string;\n\t\ttitle?: string;\n\t\tindex: number;\n\t}\n\n\tinterface Props {\n\t\tsections: Section[];\n\t\tcurrentSectionIndex?: number;\n\t\ti18n?: I18nProvider;\n\t\tonSectionSelect?: (sectionIndex: number) => void;\n\t\tdisabled?: boolean;\n\t}\n\n\tconst { sections, currentSectionIndex, i18n, onSectionSelect, disabled = false }: Props = $props();\n\n\tlet isOpen = $state(false);\n\tlet toggleButton = $state<HTMLButtonElement | null>(null);\n\tlet dropdownContent = $state<HTMLDivElement | null>(null);\n\tconst menuId = 'assessment-section-menu';\n\n\tasync function openMenu() {\n\t\tif (disabled) return;\n\t\tisOpen = true;\n\t\tawait tick();\n\t\tconst active = dropdownContent?.querySelector<HTMLButtonElement>('.section-item.active');\n\t\tconst first = dropdownContent?.querySelector<HTMLButtonElement>('.section-item:not(:disabled)');\n\t\t(active ?? first)?.focus();\n\t}\n\n\tfunction closeMenu({ restoreFocus = true } = {}) {\n\t\tisOpen = false;\n\t\tif (restoreFocus) {\n\t\t\ttoggleButton?.focus();\n\t\t}\n\t}\n\n\tfunction toggleMenu() {\n\t\tif (isOpen) {\n\t\t\tcloseMenu();\n\t\t\treturn;\n\t\t}\n\t\tvoid openMenu();\n\t}\n\n\tfunction handleMenuKeydown(event: KeyboardEvent) {\n\t\tif (event.key === 'Escape') {\n\t\t\tevent.preventDefault();\n\t\t\tcloseMenu();\n\t\t}\n\t}\n\n\tfunction handleToggleKeydown(event: KeyboardEvent) {\n\t\tif (event.key === 'ArrowDown') {\n\t\t\tevent.preventDefault();\n\t\t\tvoid openMenu();\n\t\t}\n\t}\n\n\tfunction handleBackdropClick() {\n\t\tcloseMenu();\n\t}\n\n\tfunction selectSection(sectionIndex: number) {\n\t\tif (disabled) return;\n\t\tif (onSectionSelect) {\n\t\t\tonSectionSelect(sectionIndex);\n\t\t}\n\t\tcloseMenu();\n\t}\n</script>\n\n{#if sections.length > 1}\n\t<div class=\"section-menu\">\n\t\t<button\n\t\t\tbind:this={toggleButton}\n\t\t\tclass=\"btn btn-outline btn-sm\"\n\t\t\ttype=\"button\"\n\t\t\taria-expanded={isOpen}\n\t\t\taria-controls={menuId}\n\t\t\tonclick={() => toggleMenu?.()}\n\t\t\tonkeydown={handleToggleKeydown}\n\t\t\tdisabled={disabled}\n\t\t>\n\t\t\t<svg\n\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\tclass=\"h-5 w-5\"\n\t\t\t\tfill=\"none\"\n\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\tstroke=\"currentColor\"\n\t\t\t>\n\t\t\t\t<path\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\td=\"M4 6h16M4 12h16M4 18h16\"\n\t\t\t\t/>\n\t\t\t</svg>\n\t\t\t{i18n?.t('assessment.sections.title') ?? 'Sections'}\n\t\t</button>\n\n\t\t{#if isOpen}\n\t\t\t<div class=\"section-dropdown\">\n\t\t\t\t<div\n\t\t\t\t\tbind:this={dropdownContent}\n\t\t\t\t\tid={menuId}\n\t\t\t\t\tclass=\"section-dropdown-content\"\n\t\t\t\t\trole=\"menu\"\n\t\t\t\t\ttabindex=\"-1\"\n\t\t\t\t\taria-label={i18n?.t('assessment.sections.title') ?? 'Sections'}\n\t\t\t\t\tonkeydown={handleMenuKeydown}\n\t\t\t\t>\n\t\t\t\t\t<div class=\"section-list\">\n\t\t\t\t\t\t{#each sections as section}\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\tclass=\"section-item\"\n\t\t\t\t\t\t\t\tclass:active={currentSectionIndex === section.index}\n\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\trole=\"menuitemradio\"\n\t\t\t\t\t\t\t\taria-checked={currentSectionIndex === section.index}\n\t\t\t\t\t\t\t\tonclick={() => selectSection(section.index)}\n\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<div class=\"section-icon\">\n\t\t\t\t\t\t\t\t\t{#if currentSectionIndex === section.index}\n\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\tclass=\"h-5 w-5\"\n\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 20 20\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\t\tfill-rule=\"evenodd\"\n\t\t\t\t\t\t\t\t\t\t\t\td=\"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z\"\n\t\t\t\t\t\t\t\t\t\t\t\tclip-rule=\"evenodd\"\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\tclass=\"h-5 w-5\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\td=\"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z\"\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"section-info\">\n\t\t\t\t\t\t\t\t\t<div class=\"section-title\">\n\t\t\t\t\t\t\t\t\t\t{section.title || (i18n?.t('assessment.sectionDefault', { number: section.index + 1 }) ?? `Section ${section.index + 1}`)}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t{/each}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<button\n\t\t\t\t\tclass=\"section-backdrop\"\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={handleBackdropClick}\n\t\t\t\t\taria-label={i18n?.t('assessment.closeMenu') ?? 'Close menu'}\n\t\t\t\t></button>\n\t\t\t</div>\n\t\t{/if}\n\t</div>\n{/if}\n\n<style>\n\t.section-menu {\n\t\tposition: relative;\n\t}\n\n\t.section-dropdown {\n\t\tposition: fixed;\n\t\tinset: 0;\n\t\tz-index: 50;\n\t}\n\n\t.section-backdrop {\n\t\tposition: absolute;\n\t\tinset: 0;\n\t\tbackground: transparent;\n\t\tborder: none;\n\t\tcursor: default;\n\t}\n\n\t.section-dropdown-content {\n\t\tposition: absolute;\n\t\ttop: 4rem;\n\t\tright: 1rem;\n\t\twidth: 20rem;\n\t\tmax-height: 24rem;\n\t\toverflow-y: auto;\n\t\tbackground: var(--color-base-100);\n\t\tborder: 1px solid var(--color-base-300);\n\t\tborder-radius: 0.5rem;\n\t\tbox-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);\n\t\tz-index: 51;\n\t}\n\n\t.section-list {\n\t\tpadding: 0.5rem;\n\t}\n\n\t.section-item {\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tgap: 0.75rem;\n\t\twidth: 100%;\n\t\tpadding: 0.75rem;\n\t\tborder: none;\n\t\tbackground: transparent;\n\t\tborder-radius: 0.375rem;\n\t\tcursor: pointer;\n\t\ttransition: background-color 0.2s;\n\t\ttext-align: left;\n\t}\n\n\t.section-item:hover:not(:disabled) {\n\t\tbackground: var(--color-base-200);\n\t}\n\n\t.section-item.active {\n\t\tbackground: color-mix(in oklab, var(--color-primary) 12%, transparent);\n\t\tcolor: var(--color-primary);\n\t}\n\n\t.section-item:disabled {\n\t\topacity: 0.5;\n\t\tcursor: not-allowed;\n\t}\n\n\t.section-icon {\n\t\tflex-shrink: 0;\n\t\tcolor: color-mix(in oklab, var(--color-base-content) 60%, transparent);\n\t}\n\n\t.section-item.active .section-icon {\n\t\tcolor: var(--color-primary);\n\t}\n\n\t.section-info {\n\t\tflex: 1;\n\t\tmin-width: 0;\n\t}\n\n\t.section-title {\n\t\tfont-weight: 500;\n\t\toverflow: hidden;\n\t\ttext-overflow: ellipsis;\n\t\twhite-space: nowrap;\n\t}\n\n\t@media (max-width: 640px) {\n\t\t.section-dropdown-content {\n\t\t\tright: 0;\n\t\t\tleft: 0;\n\t\t\twidth: auto;\n\t\t\tmargin: 0 1rem;\n\t\t}\n\t}\n</style>\n","<script lang=\"ts\">\n\timport SectionMenu from './SectionMenu.svelte';\n\n\tinterface Section {\n\t\tid: string;\n\t\ttitle?: string;\n\t\tindex: number;\n\t}\n\n\tinterface Props {\n\t\t/** Assessment title */\n\t\ttitle: string;\n\t\t/** Available sections */\n\t\tsections?: Section[];\n\t\t/** Current section index */\n\t\tcurrentSectionIndex?: number;\n\t\t/** Whether to show section menu */\n\t\tshowSections?: boolean;\n\t\t/** Whether section navigation is allowed */\n\t\tallowSectionNavigation?: boolean;\n\t\t/** Section selection callback */\n\t\tonSectionSelect?: (sectionIndex: number) => void;\n\t}\n\n\tconst {\n\t\ttitle,\n\t\tsections = [],\n\t\tcurrentSectionIndex,\n\t\tshowSections = true,\n\t\tallowSectionNavigation = true,\n\t\tonSectionSelect\n\t}: Props = $props();\n</script>\n\n<div class=\"assessment-header\">\n\t<div class=\"assessment-title\">\n\t\t<h2 class=\"text-2xl font-bold\">{title}</h2>\n\t</div>\n\n\t{#if showSections && sections.length > 1}\n\t\t<SectionMenu\n\t\t\t{sections}\n\t\t\t{currentSectionIndex}\n\t\t\t{onSectionSelect}\n\t\t\tdisabled={!allowSectionNavigation}\n\t\t/>\n\t{/if}\n</div>\n\n<style>\n\t.assessment-header {\n\t\tdisplay: flex;\n\t\tjustify-content: space-between;\n\t\talign-items: center;\n\t\tpadding: 1.5rem;\n\t\tborder-bottom: 1px solid var(--color-base-300);\n\t\tbackground: var(--color-base-100);\n\t\tposition: sticky;\n\t\ttop: 0;\n\t\tz-index: 10;\n\t}\n\n\t.assessment-title {\n\t\tflex: 1;\n\t}\n\n\t@media (max-width: 768px) {\n\t\t.assessment-header {\n\t\t\tpadding: 1rem;\n\t\t}\n\n\t\t.assessment-title :global(h2) {\n\t\t\tfont-size: 1.25rem;\n\t\t}\n\t}\n</style>\n","<script lang=\"ts\">\n\timport type { NavigationState } from '../types/index.js';\n\timport type { I18nProvider } from '@pie-qti/i18n';\n\n\tinterface Props {\n\t\tnavState: NavigationState;\n\t\ti18n?: I18nProvider;\n\t\tonPrevious?: () => void;\n\t\tonNext?: () => void;\n\t\tonSubmit?: () => void;\n\t\tshowProgress?: boolean;\n\t}\n\n\tconst { navState, i18n, onPrevious, onNext, onSubmit, showProgress = true }: Props = $props();\n\n\tconst progressPercentage = $derived(\n\t\tnavState.totalItems > 0 ? ((navState.currentIndex + 1) / navState.totalItems) * 100 : 0,\n\t);\n\n\t// Simplified translations - no manual subscriptions needed\n\t// Locale changes trigger page refresh, so reactivity is not required\n\tconst translations = $derived({\n\t\tquestion: i18n?.t('assessment.question', { current: navState.currentIndex + 1, total: navState.totalItems })\n\t\t\t?? `Question ${navState.currentIndex + 1} of ${navState.totalItems}`,\n\t\tsection: navState.currentSection\n\t\t\t? (navState.currentSection.title ?? (i18n?.t('assessment.section', { current: navState.currentSection.index + 1, total: 0 })\n\t\t\t\t?? `Section ${navState.currentSection.index + 1}`))\n\t\t\t: null,\n\t\tprevious: i18n?.t('common.previous') ?? 'Previous',\n\t\tnext: i18n?.t('common.next') ?? 'Next',\n\t\tsubmit: i18n?.t('assessment.navigation.submit') ?? 'Submit',\n\t\tprogress: `${i18n?.t('assessment.navigation.progress', { percent: Math.round(progressPercentage) }) ?? `Progress: ${Math.round(progressPercentage)}%`}: ${i18n?.t('assessment.question', { current: navState.currentIndex + 1, total: navState.totalItems }) ?? `Question ${navState.currentIndex + 1} of ${navState.totalItems}`}`,\n\t});\n</script>\n\n<div class=\"navigation-bar\">\n\t<!-- Progress indicator -->\n\t{#if showProgress}\n\t\t<div class=\"progress-section\">\n\t\t\t<div class=\"progress-label text-sm\">\n\t\t\t\t{translations.question}\n\t\t\t\t{#if translations.section}\n\t\t\t\t\t<span class=\"text-base-content/60\">\n\t\t\t\t\t\t({translations.section})\n\t\t\t\t\t</span>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t\t<progress\n\t\t\t\tclass=\"progress progress-primary w-full\"\n\t\t\t\tvalue={progressPercentage}\n\t\t\t\tmax=\"100\"\n\t\t\t\taria-label={translations.progress}\n\t\t\t></progress>\n\t\t</div>\n\t{/if}\n\n\t<!-- Navigation buttons -->\n\t<div class=\"navigation-buttons\">\n\t\t<button\n\t\t\tclass=\"btn btn-outline\"\n\t\t\tdata-testid=\"assessment-prev\"\n\t\t\tonclick={() => onPrevious?.()}\n\t\t\tdisabled={!navState.canPrevious || navState.isLoading}\n\t\t>\n\t\t\t<svg\n\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\tclass=\"h-5 w-5\"\n\t\t\t\tfill=\"none\"\n\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\tstroke=\"currentColor\"\n\t\t\t>\n\t\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M15 19l-7-7 7-7\" />\n\t\t\t</svg>\n\t\t\t{translations.previous}\n\t\t</button>\n\n\t\t<div class=\"flex-1\"></div>\n\n\t\t{#if navState.currentIndex === navState.totalItems - 1}\n\t\t\t<!-- Submit button on last item -->\n\t\t\t<button class=\"btn btn-primary\" data-testid=\"assessment-submit\" onclick={() => onSubmit?.()} disabled={navState.isLoading}>\n\t\t\t\t{translations.submit}\n\t\t\t</button>\n\t\t{:else}\n\t\t\t<!-- Next button -->\n\t\t\t<button\n\t\t\t\tclass=\"btn btn-primary\"\n\t\t\t\tdata-testid=\"assessment-next\"\n\t\t\t\tonclick={() => onNext?.()}\n\t\t\t\tdisabled={!navState.canNext || navState.isLoading}\n\t\t\t>\n\t\t\t\t{translations.next}\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\tclass=\"h-5 w-5\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t>\n\t\t\t\t\t<path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M9 5l7 7-7 7\" />\n\t\t\t\t</svg>\n\t\t\t</button>\n\t\t{/if}\n\t</div>\n</div>\n\n<style>\n\t.navigation-bar {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 1rem;\n\t\tpadding: 1rem;\n\t\tborder-top: 1px solid var(--color-base-300);\n\t\tbackground: var(--color-base-100);\n\t}\n\n\t.progress-section {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 0.5rem;\n\t}\n\n\t.progress-label {\n\t\tfont-weight: 500;\n\t}\n\n\t.navigation-buttons {\n\t\tdisplay: flex;\n\t\tgap: 0.5rem;\n\t\talign-items: center;\n\t}\n\n\t@media (max-width: 640px) {\n\t\t.navigation-buttons {\n\t\t\tflex-direction: column;\n\t\t}\n\n\t\t.navigation-buttons button {\n\t\t\twidth: 100%;\n\t\t}\n\n\t\t.flex-1 {\n\t\t\tdisplay: none;\n\t\t}\n\t}\n</style>\n","<script lang=\"ts\">\n\timport { onMount, tick, getContext } from 'svelte';\n\timport { DefaultI18nProvider, type I18nProvider } from '@pie-qti/i18n';\n\timport type { QtiSharedHtmlBlock } from '@pie-qti/section-player';\n\timport { SectionPlayerSplitPane, SectionPlayerVertical, TestFeedback as SectionTestFeedback } from '../../../section-player/src/components/index.js';\n\timport type { BackendAssessmentPlayerConfig } from '../core/AssessmentPlayer.js';\n\timport { AssessmentPlayer } from '../core/AssessmentPlayer.js';\n\timport type { BackendAdapter, InitSessionRequest } from '../integration/api-contract.js';\n\timport { toSectionComposition } from '../integration/toSectionComposition.js';\n\timport type { AssessmentResults, NavigationState } from '../types/index.js';\n\timport AccessibilityAnnouncer from './AccessibilityAnnouncer.svelte';\n\timport AssessmentHeader from './AssessmentHeader.svelte';\n\timport NavigationBar from './NavigationBar.svelte';\n\n\tinterface Props {\n\t\tbackend: BackendAdapter;\n\t\tinitSession: InitSessionRequest;\n\t\tconfig?: Partial<BackendAssessmentPlayerConfig>;\n\t\t/**\n\t\t * Called after a successful submit (with results).\n\t\t * Note: `config.onComplete` is invoked by `AssessmentPlayer.submit()` already.\n\t\t */\n\t\tonSubmit?: (results: AssessmentResults) => void;\n\t\t/** Math typesetting function (KaTeX, MathJax, etc.) */\n\t\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\t}\n\n\tconst { backend, initSession, config = {}, onSubmit, typeset }: Props = $props();\n\n\t// Get i18n from context (set by +layout.svelte)\n\tconst contextI18nWrapper = getContext<{ value: I18nProvider | null } | undefined>('i18n');\n\tconst contextI18n = $derived(contextI18nWrapper?.value ?? undefined);\n\tconst fallbackI18n = new DefaultI18nProvider();\n\tconst i18n = $derived(config.i18nProvider ?? contextI18n ?? fallbackI18n);\n\t// The core and cached item definitions retain one provider reference, while a\n\t// host may finish loading its actual provider after this shell mounts. Resolve\n\t// methods against the current provider and preserve their receiver.\n\tconst playerI18n: I18nProvider = new Proxy(fallbackI18n, {\n\t\tget(_target, key) {\n\t\t\tconst provider = i18n;\n\t\t\tconst value = Reflect.get(provider, key, provider);\n\t\t\treturn typeof value === 'function' ? value.bind(provider) : value;\n\t\t},\n\t});\n\n\tlet player = $state<AssessmentPlayer | null>(null);\n\tlet navState = $state<NavigationState>({\n\t\tcurrentIndex: -1,\n\t\ttotalItems: 0,\n\t\tcanNext: false,\n\t\tcanPrevious: false,\n\t\tisLoading: false,\n\t\tcurrentSection: undefined,\n\t\ttotalSections: undefined,\n\t});\n\tlet currentItem = $state<any>(null);\n\tlet currentRubricBlocks = $state<any[]>([]);\n\tlet currentResponses = $state<Record<string, unknown>>({});\n\tlet sections = $state<any[]>([]);\n\tlet error = $state<string | null>(null);\n\tlet navError = $state<string | null>(null);\n\tlet submitError = $state<string | null>(null);\n\tlet isSubmitting = $state(false);\n\tlet retryButton = $state<HTMLButtonElement | null>(null);\n\tlet itemPaneEl = $state<HTMLElement | null>(null);\n\tlet rootEl = $state<HTMLElement | null>(null);\n\tlet testFeedback = $state<Array<{ identifier: string; content: string; access: string }>>([]);\n\tlet isComplete = $state(false);\n\tlet initTimeout: ReturnType<typeof setTimeout> | null = null;\n\tlet hasFirstItem = $state(false);\n\tlet announcer = $state<AccessibilityAnnouncer | null>(null);\n\tlet responseVersion = $state(0);\n\tlet stateVersion = $state(0);\n\n\tconst sectionComposition = $derived.by(() => {\n\t\tresponseVersion;\n\t\tstateVersion;\n\t\treturn player ? toSectionComposition(player, config) : null;\n\t});\n\tconst hasSplitPane = $derived(sectionComposition?.layout === 'split-pane');\n\tconst sectionRole = $derived(config.role ?? 'candidate');\n\tconst testFeedbackBlocks = $derived<QtiSharedHtmlBlock[]>(\n\t\ttestFeedback.map((item) => ({\n\t\t\tidentifier: item.identifier,\n\t\t\tkind: 'test-feedback',\n\t\t\tscope: 'assessment',\n\t\t\trawHtml: item.content,\n\t\t}))\n\t);\n\n\t// Initialize player\n\tonMount(() => {\n\t\t// Never allow infinite \"Loading assessment...\" state\n\t\tinitTimeout = setTimeout(() => {\n\t\t\tif (!hasFirstItem && !error) {\n\t\t\t\terror = i18n.t('assessment.loadingError');\n\t\t\t\tannouncer?.announce(error, 3000, 'assertive');\n\t\t\t}\n\t\t}, 10000);\n\n\t\tconst playerConfig: BackendAssessmentPlayerConfig = {\n\t\t\tbackend,\n\t\t\tinitSession,\n\t\t\tshowSections: config.showSections !== false,\n\t\t\tallowSectionNavigation: config.allowSectionNavigation !== false,\n\t\t\tshowProgress: config.showProgress !== false,\n\t\t\t...config,\n\t\t\ti18nProvider: playerI18n,\n\t\t};\n\n\t\t(async () => {\n\t\t\tplayer = await AssessmentPlayer.create(playerConfig);\n\n\t\t\t// Get sections\n\t\t\tsections = player.getAllSections();\n\n\t\t\t// Set up event listeners\n\t\t\tplayer.onItemChange(async () => {\n\t\t\t\tupdateState();\n\t\t\t\tnavError = null;\n\t\t\t\thasFirstItem = true;\n\t\t\t\tif (initTimeout) {\n\t\t\t\t\tclearTimeout(initTimeout);\n\t\t\t\t\tinitTimeout = null;\n\t\t\t\t}\n\t\t\t\tawait tick();\n\t\t\t\titemPaneEl?.scrollTo({ top: 0, behavior: 'auto' });\n\t\t\t});\n\n\t\t\tplayer.onSectionChange(() => {\n\t\t\t\tupdateState();\n\t\t\t});\n\n\t\t\tplayer.onResponseChange((responses) => {\n\t\t\t\tcurrentResponses = responses;\n\t\t\t\tresponseVersion += 1;\n\t\t\t});\n\n\t\t\t// If backend did not restore a current item, start at index 0.\n\t\t\tif (player.getNavigationState().currentIndex < 0) {\n\t\t\t\tawait player.navigateTo(0);\n\t\t\t} else {\n\t\t\t\tupdateState();\n\t\t\t\thasFirstItem = true;\n\t\t\t\tif (initTimeout) {\n\t\t\t\t\tclearTimeout(initTimeout);\n\t\t\t\t\tinitTimeout = null;\n\t\t\t\t}\n\t\t\t}\n\t\t})().catch((err) => {\n\t\t\tconsole.error('Failed to initialize assessment player:', err);\n\t\t\terror = err instanceof Error ? err.message : i18n.t('assessment.loadingError');\n\t\t\tannouncer?.announce(error, 3000, 'assertive');\n\t\t});\n\n\t\treturn () => {\n\t\t\tif (initTimeout) {\n\t\t\t\tclearTimeout(initTimeout);\n\t\t\t\tinitTimeout = null;\n\t\t\t}\n\t\t\tif (player) {\n\t\t\t\tplayer.destroy();\n\t\t\t}\n\t\t};\n\t});\n\n\tfunction updateState() {\n\t\tif (!player) return;\n\n\t\tnavState = player.getNavigationState();\n\t\tcurrentItem = player.getCurrentItem();\n\t\tcurrentRubricBlocks = player.getCurrentRubricBlocks();\n\t\tcurrentResponses = player.getResponses();\n\t\tstateVersion += 1;\n\t}\n\n\tasync function handlePrevious() {\n\t\tif (!player || isSubmitting || isComplete) return;\n\t\ttry {\n\t\t\tnavError = null;\n\t\t\tawait player.previous();\n\t\t\tawait manageFocusAfterNavigation();\n\t\t\tannounceCurrentQuestion();\n\t\t} catch (err) {\n\t\t\tconsole.error('Previous navigation failed:', err);\n\t\t\tconst message = err instanceof Error ? err.message : (i18n?.t('assessment.errors.navigationFailed') ?? 'assessment.errors.navigationFailed');\n\t\t\tnavError = message;\n\t\t}\n\t}\n\n\tasync function handleNext() {\n\t\tif (!player || isSubmitting || isComplete) return;\n\t\ttry {\n\t\t\tnavError = null;\n\t\t\tawait player.next();\n\t\t\tawait manageFocusAfterNavigation();\n\t\t\tannounceCurrentQuestion();\n\t\t} catch (err) {\n\t\t\tconsole.error('Next navigation failed:', err);\n\t\t\tconst message = err instanceof Error ? err.message : (i18n?.t('assessment.errors.navigationFailed') ?? 'assessment.errors.navigationFailed');\n\t\t\tnavError = message;\n\t\t}\n\t}\n\n\t/**\n\t * Announce current question to screen readers\n\t */\n\tfunction announceCurrentQuestion() {\n\t\tif (!player) return;\n\t\tconst state = player.getNavigationState();\n\t\tconst msg = i18n?.t('assessment.questionAnnouncement', {\n\t\t\tcurrent: state.currentIndex + 1,\n\t\t\ttotal: state.totalItems\n\t\t}) ?? `assessment.questionAnnouncement (${state.currentIndex + 1}/${state.totalItems})`;\n\t\tannouncer?.announce(msg, 1500);\n\t}\n\n\tasync function handleSectionSelect(sectionIndex: number) {\n\t\tif (!player || isSubmitting || isComplete || !sections[sectionIndex]) return;\n\n\t\tconst section = sections[sectionIndex];\n\t\tawait player.navigateToSection(section.id);\n\t\tawait manageFocusAfterNavigation();\n\t}\n\n\t/**\n\t * Manage focus after navigation to improve accessibility.\n\t * Moves focus to the content area so screen reader users are aware of the content change.\n\t */\n\tasync function manageFocusAfterNavigation() {\n\t\tawait tick(); // Wait for DOM updates\n\n\t\t// Try to focus on the item pane (for split pane layout)\n\t\tif (itemPaneEl) {\n\t\t\titemPaneEl.focus();\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise focus on the content area\n\t\tconst contentEl = document.querySelector('.assessment-content') as HTMLElement;\n\t\tif (contentEl) {\n\t\t\tcontentEl.focus();\n\t\t}\n\t}\n\n\tasync function handleSubmit() {\n\t\tif (!player || isSubmitting || isComplete) return;\n\n\t\tsubmitError = null;\n\t\tisSubmitting = true;\n\t\tlet results: AssessmentResults;\n\t\ttry {\n\t\t\tresults = await player.submit();\n\t\t} catch (err) {\n\t\t\tconsole.error('Failed to submit assessment:', err);\n\t\t\tsubmitError = err instanceof Error ? err.message : (i18n?.t('assessment.errors.submitFailed') ?? 'Submission failed. Please try again.');\n\t\t\t// Keep the shell and its session available after the core restores a\n\t\t\t// failed submission. Already accepted responses are retained for retry.\n\t\t\tupdateState();\n\t\t\treturn;\n\t\t} finally {\n\t\t\tisSubmitting = false;\n\t\t\tif (submitError) {\n\t\t\t\tawait tick();\n\t\t\t\tretryButton?.focus();\n\t\t\t}\n\t\t}\n\n\t\ttestFeedback = player.getVisibleFeedback();\n\t\tisComplete = true;\n\t\tonSubmit?.(results);\n\t}\n\n\t/**\n\t * Imperative API (useful for embedding in host frameworks / custom elements)\n\t */\n\texport async function next() {\n\t\treturn player?.next();\n\t}\n\n\texport async function previous() {\n\t\treturn player?.previous();\n\t}\n\n\texport async function navigateTo(index: number) {\n\t\treturn player?.navigateTo(index);\n\t}\n\n\texport async function navigateToSection(sectionIdentifier: string) {\n\t\treturn player?.navigateToSection(sectionIdentifier);\n\t}\n\n\texport async function submit() {\n\t\treturn player?.submit();\n\t}\n\n\texport function getResponses() {\n\t\treturn player?.getResponses();\n\t}\n\n\texport function getState() {\n\t\treturn player?.getState();\n\t}\n\n\texport function restoreState(state: any) {\n\t\treturn player?.restoreState(state);\n\t}\n</script>\n\n<!-- Accessibility announcer for screen readers -->\n<AccessibilityAnnouncer bind:this={announcer} />\n\n{#if error}\n\t<div class=\"assessment-error\">\n\t\t<div class=\"alert alert-error\" role=\"alert\" aria-live=\"assertive\">\n\t\t\t<svg\n\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\tclass=\"stroke-current shrink-0 h-6 w-6\"\n\t\t\t\tfill=\"none\"\n\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t>\n\t\t\t\t<path\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\td=\"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z\"\n\t\t\t\t/>\n\t\t\t</svg>\n\t\t\t<span>{error}</span>\n\t\t</div>\n\t</div>\n{:else if !player || navState.currentIndex < 0}\n\t<div class=\"assessment-loading\">\n\t\t<div class=\"flex items-center justify-center p-8\" role=\"status\" aria-live=\"polite\">\n\t\t\t<span class=\"loading loading-spinner loading-lg\"></span>\n\t\t\t<span class=\"ml-4\">{i18n.t('assessment.loading')}</span>\n\t\t</div>\n\t</div>\n{:else}\n\t<div bind:this={rootEl} class=\"assessment-shell\" role=\"region\" aria-label=\"Assessment player\" aria-busy={isSubmitting}>\n\t\t<!-- Header with title and section menu -->\n\t\t<AssessmentHeader\n\t\t\ttitle={initSession.assessmentId || (i18n?.t('assessment.title') ?? 'Assessment')}\n\t\t\t{sections}\n\t\t\tcurrentSectionIndex={navState.currentSection?.index}\n\t\t\tshowSections={config.showSections}\n\t\t\tallowSectionNavigation={!isSubmitting && !isComplete && config.allowSectionNavigation !== false}\n\t\t\tonSectionSelect={handleSectionSelect}\n\t\t/>\n\n\t\t<!-- Test Feedback (shown after completion) -->\n\t\t{#if isComplete && testFeedback.length > 0}\n\t\t\t<SectionTestFeedback\n\t\t\t\tfeedback={testFeedbackBlocks}\n\t\t\t\trole={sectionRole}\n\t\t\t\t{i18n}\n\t\t\t\tsecurity={config.security}\n\t\t\t\thost={config.sectionHost}\n\t\t\t\t{typeset}\n\t\t\t/>\n\t\t{/if}\n\n\t\t{#if navError}\n\t\t\t<div class=\"assessment-nav-error\">\n\t\t\t\t<div class=\"alert alert-warning\" role=\"alert\" aria-live=\"assertive\">\n\t\t\t\t\t<svg\n\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\tclass=\"stroke-current shrink-0 h-6 w-6\"\n\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<path\n\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\td=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t</svg>\n\t\t\t\t\t<span>{navError}</span>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Main content area -->\n\t\t<div\n\t\t\tclass:has-passage={hasSplitPane}\n\t\t\tclass=\"assessment-content\"\n\t\t\ttabindex=\"-1\"\n\t\t\trole=\"region\"\n\t\t\taria-label={i18n?.t('accessibility.itemBody') ?? 'Question content'}\n\t\t>\n\t\t\t{#if sectionComposition}\n\t\t\t\t{#if sectionComposition.layout === 'split-pane'}\n\t\t\t\t\t<SectionPlayerSplitPane\n\t\t\t\t\t\tcomposition={sectionComposition}\n\t\t\t\t\t\t{i18n}\n\t\t\t\t\t\tsecurity={config.security}\n\t\t\t\t\t\tpci={config.pci}\n\t\t\t\t\t\tpnp={config.pnp}\n\t\t\t\t\t\t{typeset}\n\t\t\t\t\t\tonItemPaneReady={(el) => (itemPaneEl = el)}\n\t\t\t\t\t/>\n\t\t\t\t{:else}\n\t\t\t\t\t<SectionPlayerVertical\n\t\t\t\t\t\tcomposition={sectionComposition}\n\t\t\t\t\t\t{i18n}\n\t\t\t\t\t\tsecurity={config.security}\n\t\t\t\t\t\tpci={config.pci}\n\t\t\t\t\t\tpnp={config.pnp}\n\t\t\t\t\t\t{typeset}\n\t\t\t\t\t\tonItemPaneReady={(el) => (itemPaneEl = el)}\n\t\t\t\t\t/>\n\t\t\t\t{/if}\n\t\t\t{/if}\n\t\t</div>\n\n\t\t{#if submitError}\n\t\t\t<div class=\"assessment-submit-error\">\n\t\t\t\t<p role=\"alert\">{submitError}</p>\n\t\t\t\t<button bind:this={retryButton} type=\"button\" class=\"btn btn-primary\" onclick={handleSubmit} disabled={isSubmitting}>\n\t\t\t\t\t{i18n?.t('common.tryAgain') ?? 'Try Again'}\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t{/if}\n\t\t{#if isSubmitting}\n\t\t\t<p class=\"assessment-submit-status\" role=\"status\">{i18n?.t('common.submitting') ?? 'Submitting...'}</p>\n\t\t{/if}\n\n\t\t<!-- Navigation bar -->\n\t\t{#if i18n}\n\t\t\t<NavigationBar\n\t\t\t\tnavState={{ ...navState, isLoading: navState.isLoading || isSubmitting || isComplete }}\n\t\t\t\t{i18n}\n\t\t\t\tonPrevious={handlePrevious}\n\t\t\t\tonNext={handleNext}\n\t\t\t\tonSubmit={handleSubmit}\n\t\t\t\tshowProgress={config.showProgress !== false}\n\t\t\t/>\n\t\t{/if}\n\t</div>\n{/if}\n\n<style>\n\t.assessment-shell {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\theight: 100vh;\n\t\toverflow: hidden;\n\t\tbackground: var(--color-base-100);\n\t}\n\n\t.assessment-content {\n\t\tflex: 1;\n\t\tpadding: 2rem;\n\t\tmax-width: 1200px;\n\t\tmargin: 0 auto;\n\t\twidth: 100%;\n\t\toverflow: auto;\n\t}\n\n\t.assessment-content:focus {\n\t\toutline: 2px solid var(--color-primary);\n\t\toutline-offset: -2px;\n\t}\n\n\t.assessment-content.has-passage {\n\t\tpadding: 0;\n\t\tmax-width: none;\n\t\toverflow: hidden;\n\t}\n\n\t.assessment-error,\n\t.assessment-loading {\n\t\tpadding: 2rem;\n\t}\n\n\t.assessment-nav-error {\n\t\tpadding: 1rem 2rem 0;\n\t}\n\n\t.assessment-submit-error {\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\tjustify-content: space-between;\n\t\tflex-wrap: wrap;\n\t\tgap: 1rem;\n\t\tpadding: 1rem;\n\t\tborder-top: 2px solid var(--color-error);\n\t}\n\n\t.assessment-submit-error p {\n\t\tflex: 1 1 16rem;\n\t\toverflow-wrap: anywhere;\n\t}\n\n\t.assessment-submit-status {\n\t\tpadding: 0.5rem 1rem;\n\t}\n\n\t@media (max-width: 768px) {\n\t\t.assessment-content {\n\t\t\tpadding: 1rem;\n\t\t}\n\n\t\t.assessment-content.has-passage {\n\t\t\tpadding: 0;\n\t\t}\n\t}\n</style>\n","export function safeJsonParse<T>(value: string | null | undefined): T | undefined {\n\tif (!value) return undefined;\n\ttry {\n\t\treturn JSON.parse(value) as T;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n\n","import { mount, unmount } from 'svelte';\nimport { createSubscriber } from 'svelte/reactivity';\nimport { createSvelteMountController, type SvelteMountController } from '@pie-qti/qti-common';\n\nconst HTMLElementBase: typeof HTMLElement = globalThis.HTMLElement ?? (class {} as typeof HTMLElement);\n\nexport abstract class BaseSvelteMountElement<TProps extends Record<string, unknown>> extends HTMLElementBase {\n\tprotected abstract Component: any;\n\tprotected abstract getProps(): TProps;\n\tprotected readonly reactiveProps: boolean = true;\n\n\t#mountController: SvelteMountController<TProps, any> | null = null;\n\n\tprotected get _instance() {\n\t\treturn this.#mountController?.instance ?? null;\n\t}\n\n\tconnectedCallback() {\n\t\tthis._mountOrUpdate();\n\t}\n\n\tdisconnectedCallback() {\n\t\tthis._teardownInstance();\n\t}\n\n\tprotected _mountOrUpdate() {\n\t\tthis.#controller().mountOrUpdate(this.getProps());\n\t}\n\n\tprotected _teardownInstance() {\n\t\tthis.#mountController?.teardown({ removeContainer: true });\n\t}\n\n\t#controller() {\n\t\tif (!this.#mountController) {\n\t\t\tthis.#mountController = createSvelteMountController({\n\t\t\t\thost: this,\n\t\t\t\tcreateSubscriber: this.reactiveProps ? createSubscriber : undefined,\n\t\t\t\tmount: (target, props) =>\n\t\t\t\t\tmount(this.Component, {\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tprops,\n\t\t\t\t\t}),\n\t\t\t\tunmount,\n\t\t\t});\n\t\t}\n\t\treturn this.#mountController;\n\t}\n}\n","import type { AssessmentResults, BackendAdapter, BackendAssessmentPlayerConfig, InitSessionRequest } from '@pie-qti/assessment-player';\nimport { ReferenceBackendAdapter } from '@pie-qti/assessment-player';\nimport type { PciConfiguration, PlayerSecurityConfig } from '@pie-qti/item-player';\nimport { enforceItemXmlLimits } from '@pie-qti/item-player/security';\nimport AssessmentShell from '../../../assessment-player/src/components/AssessmentShell.svelte';\nimport { QTI_ASSESSMENT_PLAYER_TAG } from '../constants.js';\nimport { parseAssessmentTestXml } from '../qti/parseAssessmentTest.js';\nimport {\n\tcreateAssessmentResourceResolver,\n\ttype QtiItemFetchPolicy,\n\ttype QtiItemMap,\n\tresolveItemsForAssessment,\n} from '../qti/resolveItems.js';\nimport type { ParsedAssessmentSection, ParsedAssessmentTest } from '../qti/types.js';\nimport { safeJsonParse } from '../utils/json.js';\nimport { BaseSvelteMountElement } from './BaseSvelteMountElement.js';\n\nexport type QtiAssessmentResponseChangeDetail = {\n\tresponses: Record<string, unknown>;\n};\n\nexport type QtiAssessmentItemChangeDetail = {\n\titemIndex: number;\n\ttotalItems: number;\n};\n\nexport type QtiAssessmentSectionChangeDetail = {\n\tsectionIndex: number;\n\ttotalSections: number;\n};\n\nexport type QtiAssessmentSubmitDetail = {\n\tresults: AssessmentResults;\n};\n\nexport type QtiAssessmentLoadErrorDetail = {\n\tmessage: string;\n};\n\nexport interface QtiAssessmentPlayerEventMap {\n\tready: CustomEvent<void>;\n\t'load-start': CustomEvent<void>;\n\t'load-end': CustomEvent<void>;\n\t'load-error': CustomEvent<QtiAssessmentLoadErrorDetail>;\n\t'item-change': CustomEvent<QtiAssessmentItemChangeDetail>;\n\t'section-change': CustomEvent<QtiAssessmentSectionChangeDetail>;\n\t'response-change': CustomEvent<QtiAssessmentResponseChangeDetail>;\n\tsubmit: CustomEvent<QtiAssessmentSubmitDetail>;\n\tcomplete: CustomEvent<void>;\n}\n\nexport class QtiAssessmentPlayerElement extends BaseSvelteMountElement<Record<string, unknown>> {\n\tstatic get observedAttributes() {\n\t\treturn [\n\t\t\t// Pure-QTI inputs\n\t\t\t'assessment-test-xml',\n\t\t\t'reference-mode',\n\t\t\t'assessment-id',\n\t\t\t'candidate-id',\n\t\t\t'item-base-url',\n\t\t\t'items-json',\n\t\t\t// Common\n\t\t\t'config-json',\n\t\t\t'security-json',\n\t\t];\n\t}\n\n\tprotected Component: any = AssessmentShell;\n\t// These host properties configure the assessment/session created on mount.\n\t// Section and item props update a live presentation; replacing these inputs\n\t// must still recreate the assessment core and its definition-level policies.\n\tprotected override readonly reactiveProps = false;\n\n\t#assessmentTestXml: string | null = null;\n\t#assessmentId: string | undefined;\n\t#candidateId: string | undefined;\n\t#itemBaseUrl: string | undefined;\n\t#items: QtiItemMap | undefined;\n\t#itemFetchPolicy: QtiItemFetchPolicy | undefined;\n\t#config: Partial<BackendAssessmentPlayerConfig> = {};\n\t#security: PlayerSecurityConfig | undefined;\n\t#pci: PciConfiguration | undefined;\n\t#referenceMode = false;\n\t#backend: BackendAdapter | undefined;\n\t#hostBackend: BackendAdapter | undefined;\n\t#initSession: InitSessionRequest | undefined;\n\t#initSessionSource: 'host' | 'local' | undefined;\n\n\t#loadSeq = 0;\n\t#allowMount = false;\n\t#resourceLoadController: AbortController | undefined;\n\n\tconnectedCallback() {\n\t\tsuper.connectedCallback();\n\t\tqueueMicrotask(() => {\n\t\t\tif (this.#hostBackend && !this.#initSession) {\n\t\t\t\tthis.#dispatchLoadError(\n\t\t\t\t\t'Set `initSession`, or both `assessmentId` and `candidateId`, before using an injected assessment backend.',\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.dispatchEvent(new CustomEvent('ready', { bubbles: true, composed: true }));\n\t\t\tvoid this.#syncFromQti();\n\t\t});\n\t}\n\n\tdisconnectedCallback() {\n\t\tthis.#loadSeq++;\n\t\tthis.#resourceLoadController?.abort();\n\t\tthis.#resourceLoadController = undefined;\n\t\tsuper.disconnectedCallback();\n\t}\n\n\tprotected override _mountOrUpdate() {\n\t\t// Pure-QTI assessment elements need their XML resolved before the Svelte shell mounts.\n\t\tif (!this.#allowMount) {\n\t\t\treturn;\n\t\t}\n\t\tsuper._mountOrUpdate();\n\t}\n\n\tattributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {\n\t\tif (name === 'assessment-test-xml') {\n\t\t\tthis.#assessmentTestXml = newValue;\n\t\t}\n\n\t\tif (name === 'reference-mode') {\n\t\t\tthis.#referenceMode = newValue !== null && newValue !== 'false';\n\t\t}\n\n\t\tif (name === 'assessment-id') {\n\t\t\tthis.#assessmentId = newValue ?? undefined;\n\t\t\tthis.#syncInitSessionFromIds();\n\t\t}\n\n\t\tif (name === 'candidate-id') {\n\t\t\tthis.#candidateId = newValue ?? undefined;\n\t\t\tthis.#syncInitSessionFromIds();\n\t\t}\n\n\t\tif (name === 'item-base-url') {\n\t\t\tthis.#itemBaseUrl = newValue ?? undefined;\n\t\t}\n\n\t\tif (name === 'items-json') {\n\t\t\tconst parsed = safeJsonParse<QtiItemMap>(newValue);\n\t\t\tif (parsed) this.#items = parsed;\n\t\t}\n\n\t\tif (name === 'config-json') {\n\t\t\tconst parsed = safeJsonParse<Partial<BackendAssessmentPlayerConfig>>(newValue);\n\t\t\tif (parsed) this.#config = parsed;\n\t\t}\n\n\t\tif (name === 'security-json') {\n\t\t\tconst parsed = safeJsonParse<PlayerSecurityConfig>(newValue);\n\t\t\tif (parsed) this.#security = parsed;\n\t\t}\n\n\t\tvoid this.#syncFromQti();\n\t\t// Don't call _mountOrUpdate here - let #syncFromQti handle it when done\n\t}\n\n\tget config() {\n\t\treturn this.#config;\n\t}\n\tset config(value: Partial<BackendAssessmentPlayerConfig>) {\n\t\tthis.#config = value ?? {};\n\t\t// Let #syncFromQti mount once the assessment backend is ready.\n\t\tif (this.#allowMount) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\tget security() {\n\t\treturn this.#security;\n\t}\n\tset security(value: PlayerSecurityConfig | undefined) {\n\t\tthis.#security = value;\n\t\t// Let #syncFromQti mount once the assessment backend is ready.\n\t\tif (this.#allowMount) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\t/**\n\t * Portable Custom Interaction trust configuration. Set as a JavaScript property;\n\t * the required resolver function cannot be represented safely as an attribute.\n\t */\n\tget pci(): PciConfiguration | undefined {\n\t\treturn this.#pci ?? this.#config.pci;\n\t}\n\tset pci(value: PciConfiguration | undefined) {\n\t\tthis.#pci = value;\n\t\tif (this.#allowMount) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\t/**\n\t * Production backend boundary. The backend must return candidate-safe item XML\n\t * and remain authoritative for scoring, timing, navigation, and persistence.\n\t */\n\tget backend(): BackendAdapter | undefined {\n\t\treturn this.#hostBackend;\n\t}\n\tset backend(value: BackendAdapter | undefined) {\n\t\tthis.#loadSeq++;\n\t\tthis.#resourceLoadController?.abort();\n\t\tthis.#resourceLoadController = undefined;\n\t\tthis.#allowMount = false;\n\t\tthis._teardownInstance();\n\t\t// A session synthesized for the answer-bearing preview backend is not an\n\t\t// authorization decision for a subsequently injected production backend.\n\t\tif (this.#initSessionSource === 'local') {\n\t\t\tthis.#initSession = undefined;\n\t\t\tthis.#initSessionSource = undefined;\n\t\t}\n\t\tthis.#hostBackend = value;\n\t\tthis.#backend = value;\n\t\tif (!value) {\n\t\t\tvoid this.#syncFromQti();\n\t\t\treturn;\n\t\t}\n\t\tthis.#syncSecureBackendMount();\n\t}\n\n\tget initSession(): InitSessionRequest | undefined {\n\t\treturn this.#initSession ? { ...this.#initSession } : undefined;\n\t}\n\tset initSession(value: InitSessionRequest | undefined) {\n\t\tthis.#initSession = value ? { ...value } : undefined;\n\t\tthis.#initSessionSource = value ? 'host' : undefined;\n\t\tthis.#assessmentId = value?.assessmentId;\n\t\tthis.#candidateId = value?.candidateId;\n\t\tthis.#syncSecureBackendMount();\n\t}\n\n\tget assessmentId(): string | undefined {\n\t\treturn this.#assessmentId;\n\t}\n\tset assessmentId(value: string | undefined) {\n\t\tthis.#assessmentId = value;\n\t\tthis.#syncInitSessionFromIds();\n\t}\n\n\tget candidateId(): string | undefined {\n\t\treturn this.#candidateId;\n\t}\n\tset candidateId(value: string | undefined) {\n\t\tthis.#candidateId = value;\n\t\tthis.#syncInitSessionFromIds();\n\t}\n\n\t/**\n\t * Explicitly enables the local ReferenceBackendAdapter. This mode exposes item\n\t * XML and answer/scoring data to the browser and is only suitable for previews,\n\t * demos, and trusted low-stakes content.\n\t */\n\tget referenceMode(): boolean {\n\t\treturn this.#referenceMode;\n\t}\n\tset referenceMode(value: boolean) {\n\t\tthis.#referenceMode = value === true;\n\t\tif (this.#referenceMode) this.setAttribute('reference-mode', '');\n\t\telse this.removeAttribute('reference-mode');\n\t\tvoid this.#syncFromQti();\n\t}\n\n\t/**\n\t * Pure-QTI API (preferred): supply an assessmentTest XML string and let the element\n\t * resolve itemRefs via either an item map (A) or base URL fetching (B).\n\t */\n\tget assessmentTestXml() {\n\t\treturn this.#assessmentTestXml;\n\t}\n\tset assessmentTestXml(value: string | null) {\n\t\tthis.#assessmentTestXml = value;\n\t\tvoid this.#syncFromQti();\n\t\t// Don't call _mountOrUpdate here - let #syncFromQti handle it when done\n\t}\n\n\tget itemBaseUrl() {\n\t\treturn this.#itemBaseUrl;\n\t}\n\tset itemBaseUrl(value: string | undefined) {\n\t\tthis.#itemBaseUrl = value;\n\t\tvoid this.#syncFromQti();\n\t\t// Don't call _mountOrUpdate here - let #syncFromQti handle it when done\n\t}\n\n\tget items() {\n\t\treturn this.#items;\n\t}\n\tset items(value: QtiItemMap | undefined) {\n\t\tthis.#items = value;\n\t\tvoid this.#syncFromQti();\n\t\t// Don't call _mountOrUpdate here - let #syncFromQti handle it when done\n\t}\n\n\tget itemFetchPolicy(): QtiItemFetchPolicy | undefined {\n\t\treturn this.#itemFetchPolicy;\n\t}\n\tset itemFetchPolicy(value: QtiItemFetchPolicy | undefined) {\n\t\tthis.#itemFetchPolicy = value ? { ...value } : undefined;\n\t\tvoid this.#syncFromQti();\n\t}\n\n\t/**\n\t * Imperative API (proxied through `AssessmentShell` exports)\n\t */\n\tasync next() {\n\t\treturn this._instance?.next?.();\n\t}\n\tasync previous() {\n\t\treturn this._instance?.previous?.();\n\t}\n\tasync navigateTo(index: number) {\n\t\treturn this._instance?.navigateTo?.(index);\n\t}\n\tasync navigateToSection(sectionIdentifier: string) {\n\t\treturn this._instance?.navigateToSection?.(sectionIdentifier);\n\t}\n\tasync submit() {\n\t\treturn this._instance?.submit?.();\n\t}\n\tgetResponses() {\n\t\treturn this._instance?.getResponses?.();\n\t}\n\tgetState() {\n\t\treturn this._instance?.getState?.();\n\t}\n\trestoreState(state: unknown) {\n\t\treturn this._instance?.restoreState?.(state);\n\t}\n\n\taddEventListener<K extends keyof QtiAssessmentPlayerEventMap>(\n\t\ttype: K,\n\t\tlistener: (this: QtiAssessmentPlayerElement, event: QtiAssessmentPlayerEventMap[K]) => unknown,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void {\n\t\tsuper.addEventListener(type, listener, options);\n\t}\n\n\tasync #syncFromQti() {\n\t\tconst seq = ++this.#loadSeq;\n\t\tthis.#resourceLoadController?.abort();\n\t\tthis.#resourceLoadController = undefined;\n\t\tif (this.#hostBackend) {\n\t\t\tthis.#syncSecureBackendMount();\n\t\t\treturn;\n\t\t}\n\t\tif (!this.#assessmentTestXml) {\n\t\t\tthis.#deactivateLocalBackend();\n\t\t\treturn;\n\t\t}\n\t\tif (!this.#referenceMode) {\n\t\t\tthis.#deactivateLocalBackend();\n\t\t\tthis.#dispatchLoadError(\n\t\t\t\t'Raw assessment XML uses the local answer-bearing backend. Set `referenceMode = true` for explicit preview/offline delivery, or inject `backend` and `initSession` for authoritative delivery.',\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Revoke the previous local player before resolving a replacement. If the\n\t\t// replacement fails, stale answer-bearing content must not remain usable.\n\t\tthis.#deactivateLocalBackend();\n\n\t\tconst resourceLoadController = new AbortController();\n\t\tthis.#resourceLoadController = resourceLoadController;\n\t\tthis.dispatchEvent(new CustomEvent('load-start', { bubbles: true, composed: true }));\n\n\t\ttry {\n\t\t\tconst security = this.#effectiveSecurity();\n\t\t\tenforceItemXmlLimits(this.#assessmentTestXml, security);\n\t\t\tconst configuredSectionDepth = security.parsingLimits?.enabled\n\t\t\t\t? security.parsingLimits.maxHtmlDepth\n\t\t\t\t: undefined;\n\t\t\tconst parsed = parseAssessmentTestXml(\n\t\t\t\tthis.#assessmentTestXml,\n\t\t\t\tconfiguredSectionDepth === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: { maxSectionDepth: configuredSectionDepth },\n\t\t\t);\n\t\t\tconst resolverItems = this.#resourceItemsForParsedAssessment(parsed);\n\t\t\tconst resourceResolver = createAssessmentResourceResolver({\n\t\t\t\titemBaseUrl: this.#itemBaseUrl,\n\t\t\t\titems: resolverItems,\n\t\t\t\tsecurity,\n\t\t\t\tfetchPolicy: this.#itemFetchPolicy,\n\t\t\t\tsignal: resourceLoadController.signal,\n\t\t\t});\n\t\t\tawait resolveItemsForAssessment({\n\t\t\t\tassessment: parsed,\n\t\t\t\titemBaseUrl: this.#itemBaseUrl,\n\t\t\t\titems: resolverItems,\n\t\t\t\tsecurity,\n\t\t\t\tfetchPolicy: this.#itemFetchPolicy,\n\t\t\t\tsignal: resourceLoadController.signal,\n\t\t\t\tresourceResolver,\n\t\t\t});\n\n\t\t\tif (seq !== this.#loadSeq) return; // superseded\n\t\t\tconst assessmentId = this.#assessmentId ?? parsed.identifier ?? 'assessment';\n\t\t\tconst candidateId = this.#candidateId ?? 'candidate';\n\n\t\t\tconst secure = await ReferenceBackendAdapter.parseAssessmentTestXml(this.#assessmentTestXml, {\n\t\t\t\trole: this.#config.role ?? 'candidate',\n\t\t\t\titemXmlMap: this.#resolvedItemXmlMap(parsed),\n\t\t\t\tfileResolver: resourceResolver,\n\t\t\t\t...(configuredSectionDepth === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { sectionReferenceLimits: { maxDepth: configuredSectionDepth } }),\n\t\t\t});\n\t\t\tconst backend = new ReferenceBackendAdapter();\n\t\t\tbackend.registerAssessment(assessmentId, secure);\n\t\t\tthis.#backend = backend;\n\t\t\tthis.#initSession = { assessmentId, candidateId };\n\t\t\tthis.#initSessionSource = 'local';\n\n\t\t\tthis.dispatchEvent(new CustomEvent('load-end', { bubbles: true, composed: true }));\n\n\t\t\t// Allow mounting now that backend is ready\n\t\t\tthis.#allowMount = true;\n\t\t\tthis._mountOrUpdate();\n\t\t} catch (e) {\n\t\t\tif (seq !== this.#loadSeq || resourceLoadController.signal.aborted) return;\n\t\t\tthis.#deactivateLocalBackend();\n\t\t\tthis.#dispatchLoadError(e instanceof Error ? e.message : String(e));\n\t\t} finally {\n\t\t\tif (this.#resourceLoadController === resourceLoadController) {\n\t\t\t\tthis.#resourceLoadController = undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\t#effectiveSecurity(): PlayerSecurityConfig {\n\t\treturn {\n\t\t\t...(this.#security ?? {}),\n\t\t\tparsingLimits: {\n\t\t\t\tenabled: true,\n\t\t\t\t...(this.#security?.parsingLimits ?? {}),\n\t\t\t},\n\t\t};\n\t}\n\n\t#dispatchLoadError(message: string): void {\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent<QtiAssessmentLoadErrorDetail>('load-error', {\n\t\t\t\tdetail: { message },\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t}),\n\t\t);\n\t}\n\n\t#syncInitSessionFromIds(): void {\n\t\tif (this.#assessmentId && this.#candidateId) {\n\t\t\tthis.#initSession = {\n\t\t\t\t...(this.#initSession?.resumeSessionId\n\t\t\t\t\t? { resumeSessionId: this.#initSession.resumeSessionId }\n\t\t\t\t\t: {}),\n\t\t\t\tassessmentId: this.#assessmentId,\n\t\t\t\tcandidateId: this.#candidateId,\n\t\t\t};\n\t\t\tthis.#initSessionSource = 'host';\n\t\t} else if (this.#hostBackend) {\n\t\t\tthis.#initSession = undefined;\n\t\t\tthis.#initSessionSource = undefined;\n\t\t}\n\t\tthis.#syncSecureBackendMount();\n\t}\n\n\t#syncSecureBackendMount(): void {\n\t\tif (!this.#hostBackend || !this.#initSession) {\n\t\t\tif (this.#hostBackend) {\n\t\t\t\tthis.#allowMount = false;\n\t\t\t\tthis._teardownInstance();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthis.#backend = this.#hostBackend;\n\t\tthis.#allowMount = true;\n\t\tif (this.isConnected) this._mountOrUpdate();\n\t}\n\n\t#deactivateLocalBackend(): void {\n\t\tthis.#allowMount = false;\n\t\tthis._teardownInstance();\n\t\tif (!this.#hostBackend) {\n\t\t\tthis.#backend = undefined;\n\t\t\tthis.#initSession = undefined;\n\t\t\tthis.#initSessionSource = undefined;\n\t\t}\n\t}\n\n\t#resourceItemsForParsedAssessment(parsed: ParsedAssessmentTest): QtiItemMap | undefined {\n\t\tif (!this.#items) return undefined;\n\t\tconst map = { ...this.#items };\n\t\tconst visit = (sections: ParsedAssessmentSection[]): void => {\n\t\t\tfor (const section of sections) {\n\t\t\t\tfor (const item of section.assessmentItemRefs ?? []) {\n\t\t\t\t\tif (item.href && map[item.href] === undefined && map[item.identifier] !== undefined) {\n\t\t\t\t\t\tmap[item.href] = map[item.identifier]!;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvisit(section.sections ?? []);\n\t\t\t}\n\t\t};\n\t\tfor (const part of parsed.testParts ?? []) visit(part.sections ?? []);\n\t\treturn map;\n\t}\n\n\t#resolvedItemXmlMap(parsed: ParsedAssessmentTest): Record<string, string> {\n\t\tconst map: Record<string, string> = {};\n\t\tconst visit = (sections: ParsedAssessmentSection[]): void => {\n\t\t\tfor (const section of sections) {\n\t\t\t\tfor (const item of section.assessmentItemRefs ?? []) {\n\t\t\t\t\tif (!item.itemXml) {\n\t\t\t\t\t\tthrow new Error(`Missing itemXml for item \"${item.identifier}\" (provide items or itemBaseUrl).`);\n\t\t\t\t\t}\n\t\t\t\t\tmap[item.identifier] = item.itemXml;\n\t\t\t\t\tif (item.href) map[item.href] = item.itemXml;\n\t\t\t\t}\n\t\t\t\tvisit(section.sections ?? []);\n\t\t\t}\n\t\t};\n\t\tfor (const part of parsed.testParts ?? []) visit(part.sections ?? []);\n\t\treturn map;\n\t}\n\n\tgetProps() {\n\t\tif (!this.#backend || !this.#initSession) {\n\t\t\tthrow new Error('Assessment backend and initSession must be configured before mounting.');\n\t\t}\n\t\t// Ensure we never expose callback-style config as the public API.\n\t\t// Consumers should listen to DOM events instead.\n\t\tconst baseConfig: Partial<BackendAssessmentPlayerConfig> = {\n\t\t\t...this.#config,\n\t\t\tsecurity: this.#effectiveSecurity(),\n\t\t\tpci: this.#pci ?? this.#config.pci,\n\t\t\tonItemChange: (itemIndex: number, totalItems: number) => {\n\t\t\t\tconst detail: QtiAssessmentItemChangeDetail = { itemIndex, totalItems };\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent<QtiAssessmentItemChangeDetail>('item-change', {\n\t\t\t\t\t\tdetail,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcomposed: true,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t\tonSectionChange: (sectionIndex: number, totalSections: number) => {\n\t\t\t\tconst detail: QtiAssessmentSectionChangeDetail = { sectionIndex, totalSections };\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent<QtiAssessmentSectionChangeDetail>('section-change', {\n\t\t\t\t\t\tdetail,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcomposed: true,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t\tonResponseChange: (responses: Record<string, unknown>) => {\n\t\t\t\tconst detail: QtiAssessmentResponseChangeDetail = { responses: { ...responses } };\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent<QtiAssessmentResponseChangeDetail>('response-change', {\n\t\t\t\t\t\tdetail,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcomposed: true,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t\tonComplete: () => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('complete', { bubbles: true, composed: true }));\n\t\t\t},\n\t\t};\n\n\t\tconst props: any = {\n\t\t\tbackend: this.#backend,\n\t\t\tinitSession: this.#initSession,\n\t\t\tconfig: baseConfig,\n\t\t\tonSubmit: (results: AssessmentResults) => {\n\t\t\t\tconst detail: QtiAssessmentSubmitDetail = { results };\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent<QtiAssessmentSubmitDetail>('submit', {\n\t\t\t\t\t\tdetail,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcomposed: true,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t\t// Don't pass typeset at all if not provided (passing undefined can cause issues)\n\t\treturn props;\n\t}\n}\n\nexport function defineQtiAssessmentPlayerElement() {\n\tif (!customElements.get(QTI_ASSESSMENT_PLAYER_TAG)) {\n\t\tcustomElements.define(QTI_ASSESSMENT_PLAYER_TAG, QtiAssessmentPlayerElement);\n\t}\n}\n","import type { PciConfiguration, PlayerSecurityConfig } from '@pie-qti/item-player';\nimport type { ResolvedQtiSectionComposition } from '@pie-qti/section-player';\nimport SectionPlayerSplitPane from '../../../section-player/src/components/SectionPlayerSplitPane.svelte';\nimport { QTI_SECTION_PLAYER_SPLITPANE_TAG } from '../constants.js';\nimport { BaseSvelteMountElement } from './BaseSvelteMountElement.js';\n\nexport type QtiSectionResponseDeltaDetail = {\n\tsectionIdentifier: string;\n\titemIdentifier: string;\n\tresponseIdentifier: string;\n\tvalue: unknown;\n};\n\nexport interface QtiSectionPlayerEventMap {\n\t'qti-section-response-delta': CustomEvent<QtiSectionResponseDeltaDetail>;\n}\n\ntype SectionPlayerElementProps = {\n\tcomposition: ResolvedQtiSectionComposition;\n\tsecurity?: PlayerSecurityConfig;\n\tpci?: PciConfiguration;\n\ttypeset?: (root: HTMLElement) => void | Promise<void>;\n\tonResponseChange: (itemIdentifier: string, responseIdentifier: string, value: unknown) => void;\n};\n\nexport abstract class QtiSectionPlayerElementBase extends BaseSvelteMountElement<SectionPlayerElementProps> {\n\t#composition: ResolvedQtiSectionComposition | null = null;\n\t#security: PlayerSecurityConfig | undefined;\n\t#pci: PciConfiguration | undefined;\n\t#typeset: ((root: HTMLElement) => void | Promise<void>) | undefined;\n\n\tget composition() {\n\t\treturn this.#composition;\n\t}\n\n\tset composition(value: ResolvedQtiSectionComposition | null) {\n\t\tthis.#composition = value;\n\t\tif (this.isConnected) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\tget security() {\n\t\treturn this.#security;\n\t}\n\n\tset security(value: PlayerSecurityConfig | undefined) {\n\t\tthis.#security = value;\n\t\tif (this.isConnected) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\t/** Portable Custom Interaction trust configuration. JS-only because it contains a resolver. */\n\tget pci(): PciConfiguration | undefined {\n\t\treturn this.#pci;\n\t}\n\n\tset pci(value: PciConfiguration | undefined) {\n\t\tthis.#pci = value;\n\t\tif (this.isConnected) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\tget typeset() {\n\t\treturn this.#typeset;\n\t}\n\n\tset typeset(value: ((root: HTMLElement) => void | Promise<void>) | undefined) {\n\t\tthis.#typeset = value;\n\t\tif (this.isConnected) {\n\t\t\tthis._mountOrUpdate();\n\t\t}\n\t}\n\n\tprotected override _mountOrUpdate() {\n\t\tif (!this.#composition) {\n\t\t\treturn;\n\t\t}\n\t\tsuper._mountOrUpdate();\n\t}\n\n\taddEventListener<K extends keyof QtiSectionPlayerEventMap>(\n\t\ttype: K,\n\t\tlistener: (this: QtiSectionPlayerElementBase, event: QtiSectionPlayerEventMap[K]) => unknown,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void {\n\t\tsuper.addEventListener(type, listener, options);\n\t}\n\n\tprotected getProps(): SectionPlayerElementProps {\n\t\tconst composition = this.#composition;\n\t\tif (!composition) {\n\t\t\tthrow new Error('Cannot mount section player before composition is assigned.');\n\t\t}\n\n\t\treturn {\n\t\t\tcomposition,\n\t\t\tsecurity: this.#security ?? composition.security,\n\t\t\tpci: this.#pci,\n\t\t\ttypeset: this.#typeset,\n\t\t\tonResponseChange: (itemIdentifier, responseIdentifier, value) => {\n\t\t\t\tconst detail: QtiSectionResponseDeltaDetail = {\n\t\t\t\t\tsectionIdentifier: composition.section.identifier,\n\t\t\t\t\titemIdentifier,\n\t\t\t\t\tresponseIdentifier,\n\t\t\t\t\tvalue,\n\t\t\t\t};\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent<QtiSectionResponseDeltaDetail>('qti-section-response-delta', {\n\t\t\t\t\t\tdetail,\n\t\t\t\t\t\tbubbles: true,\n\t\t\t\t\t\tcomposed: true,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport class QtiSectionPlayerSplitPaneElement extends QtiSectionPlayerElementBase {\n\tprotected Component: any = SectionPlayerSplitPane;\n}\n\nexport function defineQtiSectionPlayerSplitPaneElement() {\n\tif (!customElements.get(QTI_SECTION_PLAYER_SPLITPANE_TAG)) {\n\t\tcustomElements.define(QTI_SECTION_PLAYER_SPLITPANE_TAG, QtiSectionPlayerSplitPaneElement);\n\t}\n}\n","import SectionPlayerVertical from '../../../section-player/src/components/SectionPlayerVertical.svelte';\nimport { QTI_SECTION_PLAYER_VERTICAL_TAG } from '../constants.js';\nimport { QtiSectionPlayerElementBase } from './QtiSectionPlayerSplitPaneElement.js';\n\nexport class QtiSectionPlayerVerticalElement extends QtiSectionPlayerElementBase {\n\tprotected Component: any = SectionPlayerVertical;\n}\n\nexport function defineQtiSectionPlayerVerticalElement() {\n\tif (!customElements.get(QTI_SECTION_PLAYER_VERTICAL_TAG)) {\n\t\tcustomElements.define(QTI_SECTION_PLAYER_VERTICAL_TAG, QtiSectionPlayerVerticalElement);\n\t}\n}\n","import { defineQtiAssessmentPlayerElement } from './elements/QtiAssessmentPlayerElement.js';\nimport { defineQtiItemPlayerElement } from './elements/QtiItemPlayerElement.js';\nimport { defineQtiSectionPlayerSplitPaneElement } from './elements/QtiSectionPlayerSplitPaneElement.js';\nimport { defineQtiSectionPlayerVerticalElement } from './elements/QtiSectionPlayerVerticalElement.js';\n\nexport function defineQtiPlayerElements() {\n\tdefineQtiItemPlayerElement();\n\tdefineQtiAssessmentPlayerElement();\n\tdefineQtiSectionPlayerSplitPaneElement();\n\tdefineQtiSectionPlayerVerticalElement();\n}\n\n\n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