@pie-players/pie-assessment-toolkit 1.0.0-beta.0 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -8
  3. package/custom-elements.json +51 -23
  4. package/dist/attempt/AssessmentSession.d.ts +7 -0
  5. package/dist/attempt/AssessmentSession.js +14 -0
  6. package/dist/attempt/TestSession.d.ts +7 -0
  7. package/dist/attempt/TestSession.js +3 -0
  8. package/dist/components/ItemScope.custom-element.js +1 -1
  9. package/dist/components/ItemToolBar.custom-element.js +1 -1
  10. package/dist/components/PieAssessmentToolkit.custom-element.js +45 -45
  11. package/dist/components/SectionToolBar.custom-element.js +1 -1
  12. package/dist/components/THIRD-PARTY-LICENSES.txt +42 -0
  13. package/dist/components/chunks/ItemToolBar-8qpnhyg4.js +40 -0
  14. package/dist/components/chunks/ItemToolBar-bsww9e8f.js +4 -0
  15. package/dist/components/chunks/ItemToolBar-eg8jarh0.js +2 -0
  16. package/dist/components/chunks/{ItemToolBar-66hcwmfw.js → ItemToolBar-gsb96731.js} +2 -2
  17. package/dist/components/chunks/ItemToolBar-na4e5vwt.js +2 -0
  18. package/dist/components/chunks/{ItemToolBar-kkj69ptr.js → ItemToolBar-wcw4yxjy.js} +1 -1
  19. package/dist/components/chunks/sre-engine-wazxma67.js +1 -0
  20. package/dist/components/element-contracts.d.ts +115 -0
  21. package/dist/components/element-contracts.js +1 -0
  22. package/dist/components/item-scope-element.d.ts +1 -1
  23. package/dist/components/item-scope-element.js +0 -1
  24. package/dist/components/item-toolbar-element.d.ts +1 -1
  25. package/dist/components/item-toolbar-element.js +0 -1
  26. package/dist/components/pie-assessment-toolkit-element.d.ts +1 -1
  27. package/dist/components/pie-assessment-toolkit-element.js +0 -1
  28. package/dist/components/section-toolbar-element.d.ts +1 -1
  29. package/dist/components/section-toolbar-element.js +0 -1
  30. package/dist/context/assessment-toolkit-context.d.ts +15 -1
  31. package/dist/index.d.ts +3 -3
  32. package/dist/index.js +2 -2
  33. package/dist/policy/core/ToolPolicyEngine.d.ts +8 -0
  34. package/dist/policy/core/ToolPolicyEngine.js +4 -2
  35. package/dist/policy/core/compose-decision.js +31 -0
  36. package/dist/policy/core/decision-types.d.ts +30 -5
  37. package/dist/policy/core/feature-decision.d.ts +11 -4
  38. package/dist/policy/core/feature-decision.js +9 -2
  39. package/dist/policy/core/pnp-policy-inputs.js +6 -2
  40. package/dist/policy/core/provenance.d.ts +1 -1
  41. package/dist/policy/core/tool-parameters.js +17 -5
  42. package/dist/policy/engine.d.ts +2 -1
  43. package/dist/policy/sources/PnpPolicySource.d.ts +48 -4
  44. package/dist/policy/sources/PnpPolicySource.js +107 -12
  45. package/dist/runtime/SectionControllerBinding.js +14 -6
  46. package/dist/runtime/content-language.js +31 -5
  47. package/dist/runtime/core/engine-resolver.d.ts +17 -0
  48. package/dist/runtime/item-feature-decisions.js +115 -0
  49. package/dist/runtime/registration-events.d.ts +31 -4
  50. package/dist/runtime/registration-events.js +20 -1
  51. package/dist/runtime/shell-event-bridge.d.ts +7 -1
  52. package/dist/runtime/shell-event-bridge.js +44 -1
  53. package/dist/runtime/shell-scope.d.ts +2 -2
  54. package/dist/runtime/shell-scope.js +14 -5
  55. package/dist/services/AccessibilityCatalogResolver.js +9 -5
  56. package/dist/services/HighlightCoordinator.js +54 -47
  57. package/dist/services/SSMLExtractor.js +8 -23
  58. package/dist/services/TTSService.d.ts +10 -7
  59. package/dist/services/TTSService.js +43 -17
  60. package/dist/services/ToolRegistry.d.ts +17 -8
  61. package/dist/services/ToolRegistry.js +10 -5
  62. package/dist/services/ToolkitCoordinator.d.ts +21 -47
  63. package/dist/services/ToolkitCoordinator.js +74 -289
  64. package/dist/services/interfaces.d.ts +14 -0
  65. package/dist/services/section-controller-types.d.ts +71 -20
  66. package/dist/services/support-conflicts.js +11 -0
  67. package/dist/services/tool-config-validation.d.ts +1 -1
  68. package/dist/services/tool-config-validation.js +8 -2
  69. package/dist/services/tool-context.d.ts +33 -2
  70. package/dist/services/tool-context.js +163 -60
  71. package/dist/services/tool-icons.js +3 -0
  72. package/dist/services/tool-provider-defaults.js +20 -0
  73. package/dist/services/tool-providers/TTSToolProvider.d.ts +16 -1
  74. package/dist/services/tool-providers/TTSToolProvider.js +50 -32
  75. package/dist/services/toolbar-decided-tools.js +1 -0
  76. package/dist/services/toolbar-items.d.ts +1 -1
  77. package/dist/services/tts/browser-provider.js +12 -3
  78. package/dist/services/tts/math-control-names.js +42 -2
  79. package/dist/services/tts/tts-lifecycle.d.ts +142 -0
  80. package/dist/services/tts/tts-lifecycle.js +341 -0
  81. package/dist/tools/content-surfaces.d.ts +35 -0
  82. package/dist/tools/content-surfaces.js +35 -0
  83. package/dist/tools/registration.d.ts +4 -2
  84. package/dist/tools/registration.js +6 -1
  85. package/package.json +31 -23
  86. package/dist/components/chunks/ItemToolBar-3zrc4p3d.js +0 -4
  87. package/dist/components/chunks/ItemToolBar-9gqhfxtn.js +0 -40
  88. package/dist/components/chunks/ItemToolBar-hzc5wyjp.js +0 -2
  89. package/dist/components/chunks/ItemToolBar-vdkyn9f3.js +0 -2
  90. package/dist/components/chunks/sre-engine-bj997w4b.js +0 -1
  91. package/dist/policy/core/compose-decision.d.ts +0 -58
  92. package/dist/policy/core/pnp-policy-inputs.d.ts +0 -59
  93. package/dist/policy/core/tool-parameters.d.ts +0 -11
  94. package/dist/runtime/RuntimeRegistry.d.ts +0 -12
  95. package/dist/runtime/SectionControllerBinding.d.ts +0 -283
  96. package/dist/runtime/adapter/SectionEngineAdapter.d.ts +0 -82
  97. package/dist/runtime/adapter/dom-event-bridge.d.ts +0 -47
  98. package/dist/runtime/composition-emit-scheduler.d.ts +0 -72
  99. package/dist/runtime/content-language.d.ts +0 -32
  100. package/dist/runtime/content-registration.d.ts +0 -13
  101. package/dist/runtime/core/SectionEngineCore.d.ts +0 -49
  102. package/dist/runtime/core/engine-transition.d.ts +0 -43
  103. package/dist/runtime/page-warnings.d.ts +0 -13
  104. package/dist/runtime/policy-input-forwarding.d.ts +0 -25
  105. package/dist/runtime/runtime-event-claim.d.ts +0 -8
  106. package/dist/runtime/runtime-id.d.ts +0 -7
  107. package/dist/runtime/session-event-emitter-policy.d.ts +0 -11
  108. package/dist/runtime/shell-registration.d.ts +0 -73
  109. package/dist/runtime/unclaimed-registration-watch.d.ts +0 -7
  110. package/dist/services/section-session-assignment.d.ts +0 -21
  111. package/dist/services/spoken-audio-cards.d.ts +0 -50
  112. package/dist/services/tool-config-defaults.d.ts +0 -15
  113. package/dist/services/toolbar-decided-tools.d.ts +0 -16
  114. package/dist/services/tts/catalog-span-alignment.d.ts +0 -24
  115. package/dist/services/tts/generated-speech/assemble-plan.d.ts +0 -35
  116. package/dist/services/tts/generated-speech/dom/build-dom-plan.d.ts +0 -27
  117. package/dist/services/tts/generated-speech/dom/to-chunk-inputs.d.ts +0 -19
  118. package/dist/services/tts/generated-speech/dom/types.d.ts +0 -37
  119. package/dist/services/tts/generated-speech/index.d.ts +0 -17
  120. package/dist/services/tts/generated-speech/math-speech-cache.d.ts +0 -17
  121. package/dist/services/tts/generated-speech/types.d.ts +0 -92
  122. package/dist/services/tts/highlight-pipeline/boundary-normalizer.d.ts +0 -2
  123. package/dist/services/tts/highlight-pipeline/create-highlight-plan.d.ts +0 -6
  124. package/dist/services/tts/highlight-pipeline/highlight-policy.d.ts +0 -2
  125. package/dist/services/tts/highlight-pipeline/index.d.ts +0 -9
  126. package/dist/services/tts/highlight-pipeline/math-semantic-resolver.d.ts +0 -3
  127. package/dist/services/tts/highlight-pipeline/normalize-speech-chunks.d.ts +0 -29
  128. package/dist/services/tts/highlight-pipeline/prose-boundary-resolver.d.ts +0 -2
  129. package/dist/services/tts/highlight-pipeline/readable-region.d.ts +0 -1
  130. package/dist/services/tts/highlight-pipeline/rendered-math-target-resolver.d.ts +0 -6
  131. package/dist/services/tts/highlight-pipeline/types.d.ts +0 -77
  132. package/dist/services/tts/highlight-pipeline/visible-map-range.d.ts +0 -14
  133. package/dist/services/tts/math-alignment/index.d.ts +0 -25
  134. package/dist/services/tts/math-alignment/mathml-tokenizer.d.ts +0 -2
  135. package/dist/services/tts/math-alignment/range-resolver.d.ts +0 -10
  136. package/dist/services/tts/math-alignment/sequence-aligner.d.ts +0 -7
  137. package/dist/services/tts/math-alignment/speech-tokenizer.d.ts +0 -39
  138. package/dist/services/tts/math-alignment/types.d.ts +0 -60
  139. package/dist/services/tts/math-control-names.d.ts +0 -21
  140. package/dist/services/tts/mathml-sanitization.d.ts +0 -8
  141. package/dist/services/tts/sre-engine.d.ts +0 -7
  142. package/dist/services/tts/sre-locales.d.ts +0 -14
  143. package/dist/services/tts/ssml/spoken-text.d.ts +0 -9
  144. package/dist/services/tts/text-segmentation.d.ts +0 -21
  145. package/dist/utils/structural-equality.d.ts +0 -11
@@ -1,10 +1,10 @@
1
- import{a as a0,b as m1,c as u1,e as p1,f as g1,g as c1,h as d1,i as K8,j as U8}from"./chunks/ItemToolBar-vdkyn9f3.js";import{o as J1,p as H7,q as DZ,r as h1,s as cZ}from"./chunks/ItemToolBar-hzc5wyjp.js";import{$ as k1,A as v,B as C1,C as b1,D as M7,E as t0,F as e0,G as y,H as E1,I as F,J as I,M as N7,N as S1,O as Z5,P as Q5,Q as y1,U as T1,V as x1,aa as k,ba as f1,ca as I1,da as J5,ga as P7,ja as v1,la as F1,ma as hZ,u as N1,v as w1,w as R1,x as i,y as x,z as n}from"./chunks/ItemToolBar-3zrc4p3d.js";import{na as G9,oa as j9}from"./chunks/ItemToolBar-66hcwmfw.js";import{qa as V3}from"./chunks/ItemToolBar-kkj69ptr.js";import{coerceBooleanAttributes as k2}from"@pie-players/pie-players-shared/ui/attribute-coercion";import{ContextProvider as L1,requestContext as M1}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as f2,resolveInstrumentationProvider as I2,TOOLKIT_INSTRUMENTATION_EVENT_MAP as v2}from"@pie-players/pie-players-shared/pie";import{commitPendingSessions as P1,createPieLogger as h2,isGlobalDebugEnabled as m2,isInstrumentationProvider as u2}from"@pie-players/pie-players-shared";import{createPieI18n as p2,DEFAULT_LOCALE as g2}from"@pie-players/pie-players-shared/i18n";var v6="error";function _5(Z){if(Z==="off"||Z==="warn"||Z==="error")return Z;return v6}function a(Z){return Z}function h6(Z){if(!Z)return new Map;return new Map(Z.getAllTools().slice().sort((Q,J)=>Q.toolId.localeCompare(J.toolId)).map((Q)=>[Q.toolId,Q]))}function m6(Z,Q,J,Y){if(!Q||!J?.sanitizeConfig)return Q;try{let X=J.sanitizeConfig(Q);if(!X||typeof X!=="object"||Array.isArray(X))return Y.push(a({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" must return an object.`,toolId:Z})),Q;return X}catch(X){return Y.push(a({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z})),Q}}function u6(Z,Q,J,Y){if(!Q||!J?.validateConfig)return;try{let X=J.validateConfig(Q);if(!Array.isArray(X)){Y.push(a({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" must return an array.`,toolId:Z}));return}for(let G of X)Y.push({...G,path:G.path||`providers.${Z}`,toolId:G.toolId||Z})}catch(X){Y.push(a({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z}))}}function p6(Z,Q,J){if(Q.size===0)return;let Y=["section","item","passage"];for(let X of Y)for(let G of Z.placement[X]){let j=Q.get(G);if(!j){J.push(a({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${G}" in placement.${X}.`,toolId:G}));continue}if(j.activation==="region"){J.push(a({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${G}" renders into a host surface (activation "region") and cannot be placed on the ${X} toolbar. Remove it from placement.${X}; its availability comes from policy plus its content dependency.`,toolId:G}));continue}let B=j.supportedLevels.includes(X),V=X==="item"&&j.supportedLevels.includes("section");if(!B&&!V)J.push(a({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${G}" does not support level "${X}".`,toolId:G}))}}function g6(Z,Q,J){if(Q.size===0)return;for(let Y of Z.policy.allowed||[]){if(Q.has(Y))continue;J.push(a({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${Y}" in policy.allowed.`,toolId:Y}))}for(let Y of Z.policy.blocked||[]){if(Q.has(Y))continue;J.push(a({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${Y}" in policy.blocked.`,toolId:Y}))}}function c6(Z,Q,J){for(let Y of Object.keys(Z.providers).sort()){if(Q.size===0||Q.has(Y))continue;J.push(a({code:"tools.unknownProviderKey",severity:"error",path:`providers.${Y}`,message:`Unknown provider key "${Y}".`,toolId:Y}))}}function Q8(Z,Q){if(Z.length===0)return;for(let J of Z){let Y=`[tool-config-validation:${Q}]`;console.warn(`${Y} ${J.path} - ${J.message}`)}}function d6(Z,Q){let J=Z.map((Y)=>`- ${Y.path}: ${Y.message}`).join(`
1
+ import{a as _8,c as X5,d as G4,e as j4,i as B4,j as W4,k as V4,l as K4,m as q4,n as b8,o as E8}from"./chunks/ItemToolBar-eg8jarh0.js";import{t as L1,u as y7,v as _0,w as X4,x as n0}from"./chunks/ItemToolBar-na4e5vwt.js";import{A as i1,B as l1,C as u,D as f,E as s,F as h,G as s1,H as n1,I as I7,J as G5,K as j5,L as y,M as r1,N as F,O as x,R as h7,S as a1,T as B5,U as W5,V as o1,Z as t1,_ as e1,ea as Z4,fa as I,ga as Q4,ha as J4,ia as V5,la as v7,oa as Y4,qa as f1,ra as u0,z as d1}from"./chunks/ItemToolBar-bsww9e8f.js";import{sa as P9,ta as N9}from"./chunks/ItemToolBar-gsb96731.js";import{va as x3}from"./chunks/ItemToolBar-wcw4yxjy.js";import{coerceBooleanAttributes as BQ}from"@pie-players/pie-players-shared/ui/attribute-coercion";import{ContextProvider as f7,interfaceLocaleContext as WQ,requestContext as g1}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as VQ,resolveInstrumentationProvider as KQ,TOOLKIT_INSTRUMENTATION_EVENT_MAP as qQ}from"@pie-players/pie-players-shared/pie";import{commitPendingSessions as c1,createPieLogger as UQ,isGlobalDebugEnabled as $Q,isInstrumentationProvider as FQ}from"@pie-players/pie-players-shared";import{createPieI18n as zQ,DEFAULT_LOCALE as AQ,defaultContentLanguage as HQ,hostChoseInterfaceLocale as DQ,isLocaleRequested as _Q,localeDirection as MQ,requestedInterfaceLocale as OQ,stampInterfaceLocale as LQ}from"@pie-players/pie-players-shared/i18n";import{settleAll as MZ}from"@pie-players/pie-players-shared/promise";var G6="error";function C5(Z){if(Z==="off"||Z==="warn"||Z==="error")return Z;return G6}function o(Z){return Z}function j6(Z){if(!Z)return new Map;return new Map(Z.getAllTools().slice().sort((Q,J)=>Q.toolId.localeCompare(J.toolId)).map((Q)=>[Q.toolId,Q]))}function B6(Z,Q,J,Y){if(!Q||!J?.sanitizeConfig)return Q;try{let X=J.sanitizeConfig(Q);if(!X||typeof X!=="object"||Array.isArray(X))return Y.push(o({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" must return an object.`,toolId:Z})),Q;return X}catch(X){return Y.push(o({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z})),Q}}function W6(Z,Q,J,Y){if(!Q||!J?.validateConfig)return;try{let X=J.validateConfig(Q);if(!Array.isArray(X)){Y.push(o({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" must return an array.`,toolId:Z}));return}for(let G of X)Y.push({...G,path:G.path||`providers.${Z}`,toolId:G.toolId||Z})}catch(X){Y.push(o({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z}))}}function V6(Z,Q,J){if(Q.size===0)return;let Y=["section","item","passage"];for(let X of Y)for(let G of Z.placement[X]){let j=Q.get(G);if(!j){J.push(o({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${G}" in placement.${X}.`,toolId:G}));continue}if(j.activation==="region"){J.push(o({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${G}" renders into a host surface (activation "region") and cannot be placed on the ${X} toolbar. Remove it from placement.${X}; its availability comes from policy plus its content dependency.`,toolId:G}));continue}let B=j.supportedLevels.includes(X),V=X==="item"&&j.supportedLevels.includes("section");if(!B&&!V)J.push(o({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${G}" does not support level "${X}".`,toolId:G}))}}var H8=new Set(_8);function K6(Z,Q,J){if(Q.size===0)return;for(let Y of Z.policy.allowed||[]){if(Q.has(Y)||H8.has(Y))continue;J.push(o({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${Y}" in policy.allowed.`,toolId:Y}))}for(let Y of Z.policy.blocked||[]){if(Q.has(Y)||H8.has(Y))continue;J.push(o({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${Y}" in policy.blocked.`,toolId:Y}))}}function q6(Z,Q,J){for(let Y of Object.keys(Z.providers).sort()){if(Q.size===0||Q.has(Y))continue;J.push(o({code:"tools.unknownProviderKey",severity:"error",path:`providers.${Y}`,message:`Unknown provider key "${Y}".`,toolId:Y}))}}function D8(Z,Q){if(Z.length===0)return;for(let J of Z){let Y=`[tool-config-validation:${Q}]`;console.warn(`${Y} ${J.path} - ${J.message}`)}}function U6(Z,Q){let J=Z.map((Y)=>`- ${Y.path}: ${Y.message}`).join(`
2
2
  `);throw Error(`[tool-config-validation:${Q}] Invalid tools config:
3
- ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q),J}function O5(Z,Q){let J=h6(Q),Y=cZ(Z),X=[],G=Object.values(Y.placement).some((V)=>V.length>0)||Object.keys(Y.providers).length>0||(Y.policy.allowed?.length??0)>0||(Y.policy.blocked?.length??0)>0;if(J.size===0&&G)X.push(a({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated, and a coordinator without one registers no tool providers. Pass `toolRegistry` to the coordinator or the toolkit it is bound to — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let j={...Y.providers||{}};for(let V of Object.keys(j).sort()){let K=J.get(V);j[V]=m6(V,j[V],K,X),u6(V,j[V],K,X)}let B={...Y,providers:j};return p6(B,J,X),g6(B,J,X),c6(B,J,X),{config:B,diagnostics:X}}function L5(Z,Q={}){let J=_5(Q.strictness),Y=Q.source??"tools";if(J==="warn")Q8(Z,Y);let X=Z.filter((G)=>G.severity==="error");if(J==="error"&&X.length>0)d6(X,Y);if(J==="error"&&X.length===0)Q8(Z,Y)}import{languageTagLookupSequence as r6,normalizeLanguageTag as j8}from"@pie-players/pie-players-shared/i18n/language-tags";var N5=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),Y8=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),X8=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),G8=new Set(["break","mark","lexicon"]);function l6(Z){let Q=Z;for(let J of G8){let Y=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Q=Q.replace(Y,(X,G)=>{let j=G?G.replace(/\s+$/,""):"";return`<${J}${j}></${J}>`})}return Q}var i6=[/^localhost$/i,/^127(?:\.\d{1,3}){3}$/,/^0(?:\.\d{1,3}){3}$/,/^10(?:\.\d{1,3}){3}$/,/^192\.168(?:\.\d{1,3}){2}$/,/^172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/,/^169\.254(?:\.\d{1,3}){2}$/,/^::1$/,/^fe80:/i,/^fc00:/i,/^fd[0-9a-f]{2}:/i,/^metadata\.google\.internal$/i,/^metadata\.azure\.internal$/i,/^metadata\.packet\.net$/i];function s6(Z){if(typeof Z!=="string"||Z.length===0)return!1;let Q;try{Q=new URL(Z)}catch{return!1}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;let J=Q.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!i6.some((Y)=>Y.test(J))}function M5(Z){let Q=Array.from(Z.children);for(let Y of Q){let X=Y.tagName.toLowerCase();if(Y8.has(X)){Y.remove();continue}if(M5(Y),!N5.has(X)){let G=Z.ownerDocument.createTextNode(Y.textContent??"");Y.replaceWith(G)}}let J=Array.from(Z.attributes).map((Y)=>Y.name);for(let Y of J)if(!X8.has(Y.toLowerCase()))Z.removeAttribute(Y);if(Z.tagName.toLowerCase()==="audio"){let Y=Z.getAttribute("src");if(Y!==null&&!s6(Y))Z.removeAttribute("src")}}function P5(Z){let Q=Z.tagName.toLowerCase(),J=Array.from(Z.attributes).filter((X)=>X8.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${n6(X.value)}"`).join("");if(G8.has(Q))return`<${Q}${J}/>`;let Y=[];for(let X of Array.from(Z.childNodes))if(X.nodeType===3)Y.push(b0(X.nodeValue??""));else if(X.nodeType===1){let G=X,j=G.tagName.toLowerCase();if(Y8.has(j))continue;if(N5.has(j))Y.push(P5(G));else Y.push(b0(G.textContent??""))}return`<${Q}${J}>${Y.join("")}</${Q}>`}function w5(Z){let Q=String(Z||"").trim();if(!Q||!Q.includes("<"))return Z;if(typeof DOMParser>"u")return Z;let Y=new DOMParser().parseFromString(l6(Q),"text/html"),X=Y.querySelector("speak");if(X)return M5(X),P5(X);let G=Y.createElement("speak");for(let j of Array.from(Y.body.childNodes))G.appendChild(j);return M5(G),Array.from(G.childNodes).map((j)=>{if(j.nodeType===3)return b0(j.nodeValue??"");if(j.nodeType===1){let B=j;if(N5.has(B.tagName.toLowerCase()))return P5(B);return b0(B.textContent??"")}return""}).join("")}function b0(Z){return Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function n6(Z){return Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var $8=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),R5="ext:";function B8(Z){if($8.has(Z))return!0;return Z.startsWith(R5)&&Z.length>R5.length}var W8=new Set;function C5(Z,Q=new Set){if(Z===null||typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z>"u")return Z;if(typeof Z!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Q.has(Z))throw TypeError("catalog cards must not contain cycles");Q.add(Z);try{if(Array.isArray(Z))return Object.freeze(Z.map((X)=>C5(X,Q)));let J=Object.getPrototypeOf(Z);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let Y={};for(let[X,G]of Object.entries(Z))Y[X]=C5(G,Q);return Object.freeze(Y)}finally{Q.delete(Z)}}function V8(Z,Q,J){let Y=`${Q}|${Z}`;if(W8.has(Y))return;W8.add(Y);let X=`${Array.from($8).join(", ")}, or an "${R5}" prefixed vendor extension`;if(Q==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Z}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${X}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${Z}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var q8=(Z)=>Z.payload!==void 0?"payload":"content";class b5{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Z,Q="en-US"){this.defaultLanguage=Q,this.indexCatalogs(Z??[],"assessment")}setDefaultLanguage(Z){this.defaultLanguage=Z}onCatalogsChange(Z){return this.catalogChangeListeners.add(Z),()=>{this.catalogChangeListeners.delete(Z)}}emitCatalogsChange(Z){for(let Q of Array.from(this.catalogChangeListeners))try{Q(Z)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Z,Q){let J=Q==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let Y of this.sanitizeCatalogs(Z)){if(J.has(Y.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Q} catalog "${Y.identifier}" ignored`);continue}J.set(Y.identifier,Y)}}insertScopedCatalogs(Z,Q){if(!Q||Q.length===0)return null;let J=this.getOwnerKey(Z),Y=this.scopedCatalogs.get(J),X=Y?.catalogs??new Map,G=[];for(let j of this.sanitizeCatalogs(Q)){if(X.has(j.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${j.identifier}" ignored for ${J}`);continue}X.set(j.identifier,j),G.push(j.identifier)}if(!Y&&G.length>0)this.scopedCatalogs.set(J,{context:{...Z},catalogs:X});return{key:J,context:{...Z},catalogs:X,insertedIds:G}}removeScopedInsertion(Z){let Q=this.scopedCatalogs.get(Z.key);if(Q?.catalogs!==Z.catalogs)return!1;let J=!1;for(let Y of Z.insertedIds)J=Q.catalogs.delete(Y)||J;if(Q.catalogs.size===0)this.scopedCatalogs.delete(Z.key);return J}registerCatalogs(Z,Q){let J=this.insertScopedCatalogs(Z,Q);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Z});let Y=!0;return()=>{if(!Y)return;if(Y=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Z})}}registerOwner(Z){let{owner:Q,entity:J}=Z,Y=K8(Q),X=[],G=[];try{G=U8(J,Q)}catch(V){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",V)}for(let V of G)try{let K=this.insertScopedCatalogs(V.context,V.catalogs);if(K)X.push(K)}catch(K){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",K)}if(X.some((V)=>V.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:Y});let B=!0;return()=>{if(!B)return;B=!1;let V=!1;for(let K of X)V=this.removeScopedInsertion(K)||V;if(V)this.emitCatalogsChange({reason:"scoped-removed",context:Y})}}forOwner(Z){let Q={...Z};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Q),onChange:(J)=>this.onCatalogsChange((Y)=>{if(this.catalogChangeAffectsOwner(Y,Q))J()})})}addItemCatalogs(Z){if(!Z||Z.length===0)return;this.indexCatalogs(Z,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Z){return this.itemCatalogs.has(Z)||this.assessmentCatalogs.has(Z)||Array.from(this.scopedCatalogs.values()).some((Q)=>Q.catalogs.has(Z))}getAlternative(Z,Q){if(!B8(Q.type))V8(Q.type,"lookup",Z);let J=Q.context?this.scopedCatalogs.get(this.getOwnerKey(Q.context))?.catalogs.get(Z):null;if(J){let G=this.findMatchingCard(J,Q);if(G)return this.resolveCard(Z,G,"item")}if(Q.context){let G=this.findScopedCandidates(Z,Q.context);if(G.length===1){let j=this.findMatchingCard(G[0],Q);if(j)return this.resolveCard(Z,j,"item")}else if(G.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Z}" for owner context`,Q.context),null}let Y=this.itemCatalogs.get(Z);if(Y){let G=this.findMatchingCard(Y,Q);if(G)return this.resolveCard(Z,G,"item")}let X=this.assessmentCatalogs.get(Z);if(X){let G=this.findMatchingCard(X,Q);if(G)return this.resolveCard(Z,G,"assessment")}return null}resolveCard(Z,Q,J){return{catalogId:Z,type:Q.catalog,language:Q.language,content:Q.catalog==="spoken"&&Q.content!==void 0?this.ensureSpokenSanitized(Q.content):Q.content,payload:Q.payload,source:J}}ensureSpokenSanitized(Z){let Q=this.sanitizedSpokenCache.get(Z);if(Q!==void 0)return Q;let J=w5(Z);return this.sanitizedSpokenCache.set(Z,J),J}getOwnerKey(Z){return[Z.ownerKind,Z.assessmentId||"",Z.sectionId||"",Z.canonicalItemId||"",Z.itemId||"",Z.passageId||"",Z.modelId||""].join("|")}scopedCatalogEntries(){let Z=[];for(let Q of this.scopedCatalogs.values())for(let J of Q.catalogs.entries())Z.push(J);return Z}findScopedCandidates(Z,Q){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Q)).map((J)=>J.catalogs.get(Z)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Z,Q){if(Z.ownerKind!==Q.ownerKind)return!1;if(Q.assessmentId&&Z.assessmentId!==Q.assessmentId)return!1;if(Q.sectionId&&Z.sectionId!==Q.sectionId)return!1;if(Q.canonicalItemId&&Z.canonicalItemId!==Q.canonicalItemId)return!1;if(Q.itemId&&Z.itemId!==Q.itemId)return!1;if(Q.passageId&&Z.passageId!==Q.passageId)return!1;if(Q.modelId&&Z.modelId!==Q.modelId)return!1;return!0}ownerScopedCatalogEntries(Z){let Q=[],J=this.scopedCatalogs.get(this.getOwnerKey(Z));if(J)Q.push(...J.catalogs.entries());for(let Y of this.scopedCatalogs.values()){if(Y===J)continue;if(!this.isCompatibleOwnerContext(Y.context,Z))continue;Q.push(...Y.catalogs.entries())}return Q}createOwnerSnapshot(Z){let Q=[],J=this.ownerScopedCatalogEntries(Z);if(Z.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[Y,X]of J)for(let G of X.cards)try{Q.push(Object.freeze({catalogId:Y,card:C5(G)}))}catch(j){let B=`${this.getOwnerKey(Z)}\x00${Y}`;if(!this.reportedSnapshotProblems.has(B))this.reportedSnapshotProblems.add(B),console.warn(`[AccessibilityCatalogResolver] Catalog "${Y}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,j)}return Object.freeze({cards:Object.freeze(Q)})}catalogChangeAffectsOwner(Z,Q){if(!Z.context)return!1;if(this.isCompatibleOwnerContext(Z.context,Q))return!0;if(Q.ownerKind==="itemModel"&&Q.modelId&&Z.context.ownerKind==="itemModel"&&!Z.context.modelId)return this.isCompatibleOwnerContext({...Z.context,modelId:Q.modelId},Q);return!1}sanitizeCatalogs(Z){return Z.map((Q)=>({...Q,cards:Q.cards.map((J)=>{if(!B8(J.catalog))V8(J.catalog,"card",Q.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?w5(J.content):J.content}})}))}findMatchingCard(Z,Q){let{type:J,language:Y,useFallback:X=!0,form:G}=Q,j=[],B=(V)=>{for(let K of r6(V))j.push((U)=>j8(U.language)===K)};if(Y)B(Y);if(X)B(this.defaultLanguage),j.push(()=>!0);for(let V of j){let K=Z.cards.filter((U)=>U.catalog===J&&V(U));if(K.length===0)continue;if(G){let U=K.find(($)=>q8($)===G);if(U)return U}return K[0]}return null}getAllAlternatives(Z){let Q=[],J=new Set,Y=(j,B)=>{let V=`${j.catalog}|${j8(j.language)}|${q8(j)}`;if(J.has(V))return;J.add(V),Q.push(this.resolveCard(Z,j,B))},X=this.itemCatalogs.get(Z);if(X)for(let j of X.cards)Y(j,"item");let G=this.assessmentCatalogs.get(Z);if(G)for(let j of G.cards)Y(j,"assessment");for(let[j,B]of this.scopedCatalogEntries()){if(j!==Z)continue;for(let V of B.cards)Y(V,"item")}return Q}getAllCatalogIds(){let Z=this.scopedCatalogEntries().map(([Q])=>Q);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Z]))}getStatistics(){let Z=new Set,Q=new Set;for(let J of this.assessmentCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.itemCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.scopedCatalogs.values())for(let Y of J.catalogs.values())for(let X of Y.cards)if(Z.add(X.catalog),X.language)Q.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),availableTypes:Z,availableLanguages:Q}}hasAlternativeType(Z,Q){return this.getAllAlternatives(Z).some((Y)=>Y.type===Q)}getCatalogsByType(Z){let Q=new Set;for(let[J,Y]of this.assessmentCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.itemCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.scopedCatalogEntries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);return Array.from(Q)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}var F8=["assessmentId","sectionId","attemptId","itemId","elementId"];function E5(Z){return Z.replace(/%/g,"%25").replace(/:/g,"%3A")}function o6(Z){return Z.replace(/%(25|3A)/g,(Q,J)=>J==="25"?"%":":")}class S5{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Z){return F8.map((Q)=>E5(Z[Q])).join(":")}parseGlobalElementId(Z){let Q=Z.split(":");if(Q.length!==F8.length)return null;let[J,Y,X,G,j]=Q.map(o6);return{assessmentId:J,sectionId:Y,attemptId:X,itemId:G,elementId:j}}setState(Z,Q,J){let Y=this.elementStates.get(Z);if(!Y)Y=new Map,this.elementStates.set(Z,Y);Y.set(Q,J),this._notifyListeners(),this._notifyStateChange()}getState(Z,Q){return this.elementStates.get(Z)?.get(Q)}getElementState(Z){let Q=this.elementStates.get(Z);if(!Q)return{};return Object.fromEntries(Q.entries())}getAllState(){let Z={};for(let[Q,J]of this.elementStates.entries())Z[Q]=Object.fromEntries(J.entries());return Z}subscribe(Z){return this.listeners.add(Z),()=>this.listeners.delete(Z)}_notifyListeners(){if(this.listeners.size===0)return;let Z=new Map([...this.elementStates].map(([Q,J])=>[Q,new Map(J)]));for(let Q of this.listeners)try{Q(Z)}catch(J){console.warn("[ElementToolStateStore] listener failed:",J)}}setOnStateChange(Z){this.onStateChange=Z}_notifyStateChange(){if(!this.onStateChange)return;try{this.onStateChange(this.getAllState())}catch(Z){console.warn("[ElementToolStateStore] state-change callback failed:",Z)}}loadState(Z){this.elementStates.clear();for(let[Q,J]of Object.entries(Z)){let Y=new Map(Object.entries(J));this.elementStates.set(Q,Y)}this._notifyListeners()}clearElement(Z){this.elementStates.delete(Z),this._notifyListeners(),this._notifyStateChange()}clearTool(Z){for(let Q of this.elementStates.values())Q.delete(Z);this._notifyListeners(),this._notifyStateChange()}clearSection(Z,Q){let J=`${E5(Z)}:${E5(Q)}:`,Y=[];for(let X of this.elementStates.keys())if(X.startsWith(J))Y.push(X);for(let X of Y)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}function E0(Z){return{kind:Z.kind,severity:Z.severity??"error",source:Z.source,message:Z.message,details:[...Z.details||[]],recoverable:Z.recoverable===!0,scope:Z.scope??"runtime",...Z.cohort?{cohort:{...Z.cohort}}:{},cause:Z.cause}}function y5(Z){let Q=Z.error instanceof Error&&Z.error.message.trim().length>0?Z.error.message:String(Z.error||"Unknown framework error");return E0({kind:Z.kind,source:Z.source,message:Q,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort,cause:Z.error})}var a6={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose","tool-module-load":"tool-module-load","tool-request-open":"tool-request","tool-request-host-check":"tool-request","tool-visibility":"tool-registration","tool-applicability":"tool-registration","tool-state-load":"tool-state-load","tool-state-save":"tool-state-save","tool-playback":"tool-playback"};function z8(Z){let Q=a6[Z.context.phase],J=Z.context.toolId?`pie-toolkit-coordinator/${Z.context.toolId}`:`pie-toolkit-coordinator:${Z.context.phase}`;return y5({kind:Q,source:J,error:Z.error,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort})}function D8(Z){let Q=`[pie-framework:${Z.kind}:${Z.source}]`;if(Z.details.length===0)return`${Q} ${Z.message}`;return`${Q} ${Z.message}
3
+ ${J}`)}function M8(Z,Q={}){let J=b5(Z,Q.toolRegistry);return E5(J.diagnostics,Q),J}function b5(Z,Q){let J=j6(Q),Y=n0(Z),X=[],G=Object.values(Y.placement).some((V)=>V.length>0)||Object.keys(Y.providers).length>0||(Y.policy.allowed?.length??0)>0||(Y.policy.blocked?.length??0)>0;if(J.size===0&&G)X.push(o({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated, and a coordinator without one registers no tool providers. Pass `toolRegistry` to the coordinator or the toolkit it is bound to — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let j={...Y.providers||{}};for(let V of Object.keys(j).sort()){let q=J.get(V);j[V]=B6(V,j[V],q,X),W6(V,j[V],q,X)}let B={...Y,providers:j};return V6(B,J,X),K6(B,J,X),q6(B,J,X),{config:B,diagnostics:X}}function E5(Z,Q={}){let J=C5(Q.strictness),Y=Q.source??"tools";if(J==="warn")D8(Z,Y);let X=Z.filter((G)=>G.severity==="error");if(J==="error"&&X.length>0)U6(X,Y);if(J==="error"&&X.length===0)D8(Z,Y)}import{languageTagScriptLookupSequence as D6,languageTagScriptsMatch as _6,normalizeLanguageTag as k5}from"@pie-players/pie-players-shared/i18n/language-tags";import{isCloudMetadataHostname as $6,isPrivateHostname as F6}from"@pie-players/pie-players-shared/security/private-hosts";var T5=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),O8=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),L8=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),P8=new Set(["break","mark","lexicon"]);function z6(Z){let Q=Z;for(let J of P8){let Y=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Q=Q.replace(Y,(X,G)=>{let j=G?G.replace(/\s+$/,""):"";return`<${J}${j}></${J}>`})}return Q}function A6(Z){if(typeof Z!=="string"||Z.length===0)return!1;let Q;try{Q=new URL(Z)}catch{return!1}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;return!$6(Q.hostname)&&!F6(Q.hostname)}function S5(Z){let Q=Array.from(Z.children);for(let Y of Q){let X=Y.tagName.toLowerCase();if(O8.has(X)){Y.remove();continue}if(S5(Y),!T5.has(X)){let G=Z.ownerDocument.createTextNode(Y.textContent??"");Y.replaceWith(G)}}let J=Array.from(Z.attributes).map((Y)=>Y.name);for(let Y of J)if(!L8.has(Y.toLowerCase()))Z.removeAttribute(Y);if(Z.tagName.toLowerCase()==="audio"){let Y=Z.getAttribute("src");if(Y!==null&&!A6(Y))Z.removeAttribute("src")}}function y5(Z){let Q=Z.tagName.toLowerCase(),J=Array.from(Z.attributes).filter((X)=>L8.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${H6(X.value)}"`).join("");if(P8.has(Q))return`<${Q}${J}/>`;let Y=[];for(let X of Array.from(Z.childNodes))if(X.nodeType===3)Y.push(fZ(X.nodeValue??""));else if(X.nodeType===1){let G=X,j=G.tagName.toLowerCase();if(O8.has(j))continue;if(T5.has(j))Y.push(y5(G));else Y.push(fZ(G.textContent??""))}return`<${Q}${J}>${Y.join("")}</${Q}>`}function x5(Z){let Q=String(Z||"").trim();if(!Q||!Q.includes("<"))return Z;if(typeof DOMParser>"u")return Z;let Y=new DOMParser().parseFromString(z6(Q),"text/html"),X=Y.querySelector("speak");if(X)return S5(X),y5(X);let G=Y.createElement("speak");for(let j of Array.from(Y.body.childNodes))G.appendChild(j);return S5(G),Array.from(G.childNodes).map((j)=>{if(j.nodeType===3)return fZ(j.nodeValue??"");if(j.nodeType===1){let B=j;if(T5.has(B.tagName.toLowerCase()))return y5(B);return fZ(B.textContent??"")}return""}).join("")}function fZ(Z){return Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function H6(Z){return Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var S8=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),f5="ext:";function N8(Z){if(S8.has(Z))return!0;return Z.startsWith(f5)&&Z.length>f5.length}var w8=new Set;function I5(Z,Q=new Set){if(Z===null||typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z>"u")return Z;if(typeof Z!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Q.has(Z))throw TypeError("catalog cards must not contain cycles");Q.add(Z);try{if(Array.isArray(Z))return Object.freeze(Z.map((X)=>I5(X,Q)));let J=Object.getPrototypeOf(Z);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let Y={};for(let[X,G]of Object.entries(Z))Y[X]=I5(G,Q);return Object.freeze(Y)}finally{Q.delete(Z)}}function R8(Z,Q,J){let Y=`${Q}|${Z}`;if(w8.has(Y))return;w8.add(Y);let X=`${Array.from(S8).join(", ")}, or an "${f5}" prefixed vendor extension`;if(Q==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Z}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${X}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${Z}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var C8=(Z)=>Z.payload!==void 0?"payload":"content";class v5{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Z,Q="en-US"){this.defaultLanguage=Q,this.indexCatalogs(Z??[],"assessment")}setDefaultLanguage(Z){this.defaultLanguage=Z}onCatalogsChange(Z){return this.catalogChangeListeners.add(Z),()=>{this.catalogChangeListeners.delete(Z)}}emitCatalogsChange(Z){for(let Q of Array.from(this.catalogChangeListeners))try{Q(Z)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Z,Q){let J=Q==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let Y of this.sanitizeCatalogs(Z)){if(J.has(Y.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Q} catalog "${Y.identifier}" ignored`);continue}J.set(Y.identifier,Y)}}insertScopedCatalogs(Z,Q){if(!Q||Q.length===0)return null;let J=this.getOwnerKey(Z),Y=this.scopedCatalogs.get(J),X=Y?.catalogs??new Map,G=[];for(let j of this.sanitizeCatalogs(Q)){if(X.has(j.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${j.identifier}" ignored for ${J}`);continue}X.set(j.identifier,j),G.push(j.identifier)}if(!Y&&G.length>0)this.scopedCatalogs.set(J,{context:{...Z},catalogs:X});return{key:J,context:{...Z},catalogs:X,insertedIds:G}}removeScopedInsertion(Z){let Q=this.scopedCatalogs.get(Z.key);if(Q?.catalogs!==Z.catalogs)return!1;let J=!1;for(let Y of Z.insertedIds)J=Q.catalogs.delete(Y)||J;if(Q.catalogs.size===0)this.scopedCatalogs.delete(Z.key);return J}registerCatalogs(Z,Q){let J=this.insertScopedCatalogs(Z,Q);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Z});let Y=!0;return()=>{if(!Y)return;if(Y=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Z})}}registerOwner(Z){let{owner:Q,entity:J}=Z,Y=b8(Q),X=[],G=[];try{G=E8(J,Q)}catch(V){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",V)}for(let V of G)try{let q=this.insertScopedCatalogs(V.context,V.catalogs);if(q)X.push(q)}catch(q){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",q)}if(X.some((V)=>V.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:Y});let B=!0;return()=>{if(!B)return;B=!1;let V=!1;for(let q of X)V=this.removeScopedInsertion(q)||V;if(V)this.emitCatalogsChange({reason:"scoped-removed",context:Y})}}forOwner(Z){let Q={...Z};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Q),onChange:(J)=>this.onCatalogsChange((Y)=>{if(this.catalogChangeAffectsOwner(Y,Q))J()})})}addItemCatalogs(Z){if(!Z||Z.length===0)return;this.indexCatalogs(Z,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Z){return this.itemCatalogs.has(Z)||this.assessmentCatalogs.has(Z)||Array.from(this.scopedCatalogs.values()).some((Q)=>Q.catalogs.has(Z))}getAlternative(Z,Q){if(!N8(Q.type))R8(Q.type,"lookup",Z);let J=Q.context?this.scopedCatalogs.get(this.getOwnerKey(Q.context))?.catalogs.get(Z):null;if(J){let G=this.findMatchingCard(J,Q);if(G)return this.resolveCard(Z,G,"item")}if(Q.context){let G=this.findScopedCandidates(Z,Q.context);if(G.length===1){let j=this.findMatchingCard(G[0],Q);if(j)return this.resolveCard(Z,j,"item")}else if(G.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Z}" for owner context`,Q.context),null}let Y=this.itemCatalogs.get(Z);if(Y){let G=this.findMatchingCard(Y,Q);if(G)return this.resolveCard(Z,G,"item")}let X=this.assessmentCatalogs.get(Z);if(X){let G=this.findMatchingCard(X,Q);if(G)return this.resolveCard(Z,G,"assessment")}return null}resolveCard(Z,Q,J){return{catalogId:Z,type:Q.catalog,language:Q.language,content:Q.catalog==="spoken"&&Q.content!==void 0?this.ensureSpokenSanitized(Q.content):Q.content,payload:Q.payload,source:J}}ensureSpokenSanitized(Z){let Q=this.sanitizedSpokenCache.get(Z);if(Q!==void 0)return Q;let J=x5(Z);return this.sanitizedSpokenCache.set(Z,J),J}getOwnerKey(Z){return[Z.ownerKind,Z.assessmentId||"",Z.sectionId||"",Z.canonicalItemId||"",Z.itemId||"",Z.passageId||"",Z.modelId||""].join("|")}scopedCatalogEntries(){let Z=[];for(let Q of this.scopedCatalogs.values())for(let J of Q.catalogs.entries())Z.push(J);return Z}findScopedCandidates(Z,Q){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Q)).map((J)=>J.catalogs.get(Z)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Z,Q){if(Z.ownerKind!==Q.ownerKind)return!1;if(Q.assessmentId&&Z.assessmentId!==Q.assessmentId)return!1;if(Q.sectionId&&Z.sectionId!==Q.sectionId)return!1;if(Q.canonicalItemId&&Z.canonicalItemId!==Q.canonicalItemId)return!1;if(Q.itemId&&Z.itemId!==Q.itemId)return!1;if(Q.passageId&&Z.passageId!==Q.passageId)return!1;if(Q.modelId&&Z.modelId!==Q.modelId)return!1;return!0}ownerScopedCatalogEntries(Z){let Q=[],J=this.scopedCatalogs.get(this.getOwnerKey(Z));if(J)Q.push(...J.catalogs.entries());for(let Y of this.scopedCatalogs.values()){if(Y===J)continue;if(!this.isCompatibleOwnerContext(Y.context,Z))continue;Q.push(...Y.catalogs.entries())}return Q}createOwnerSnapshot(Z){let Q=[],J=this.ownerScopedCatalogEntries(Z);if(Z.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[Y,X]of J)for(let G of X.cards)try{Q.push(Object.freeze({catalogId:Y,card:I5(G)}))}catch(j){let B=`${this.getOwnerKey(Z)}\x00${Y}`;if(!this.reportedSnapshotProblems.has(B))this.reportedSnapshotProblems.add(B),console.warn(`[AccessibilityCatalogResolver] Catalog "${Y}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,j)}return Object.freeze({cards:Object.freeze(Q)})}catalogChangeAffectsOwner(Z,Q){if(!Z.context)return!1;if(this.isCompatibleOwnerContext(Z.context,Q))return!0;if(Q.ownerKind==="itemModel"&&Q.modelId&&Z.context.ownerKind==="itemModel"&&!Z.context.modelId)return this.isCompatibleOwnerContext({...Z.context,modelId:Q.modelId},Q);return!1}sanitizeCatalogs(Z){return Z.map((Q)=>({...Q,cards:Q.cards.map((J)=>{if(!N8(J.catalog))R8(J.catalog,"card",Q.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?x5(J.content):J.content}})}))}findMatchingCard(Z,Q){let{type:J,language:Y,useFallback:X=!0,form:G}=Q,j=[],B=(V)=>{let q=k5(V);for(let U of D6(V))j.push(($)=>k5($.language)===U&&(U===q||_6(V,$.language)))};if(Y)B(Y);if(X)B(this.defaultLanguage),j.push(()=>!0);for(let V of j){let q=Z.cards.filter((U)=>U.catalog===J&&V(U));if(q.length===0)continue;if(G){let U=q.find(($)=>C8($)===G);if(U)return U}return q[0]}return null}getAllAlternatives(Z){let Q=[],J=new Set,Y=(j,B)=>{let V=`${j.catalog}|${k5(j.language)}|${C8(j)}`;if(J.has(V))return;J.add(V),Q.push(this.resolveCard(Z,j,B))},X=this.itemCatalogs.get(Z);if(X)for(let j of X.cards)Y(j,"item");let G=this.assessmentCatalogs.get(Z);if(G)for(let j of G.cards)Y(j,"assessment");for(let[j,B]of this.scopedCatalogEntries()){if(j!==Z)continue;for(let V of B.cards)Y(V,"item")}return Q}getAllCatalogIds(){let Z=this.scopedCatalogEntries().map(([Q])=>Q);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Z]))}getStatistics(){let Z=new Set,Q=new Set;for(let J of this.assessmentCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.itemCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.scopedCatalogs.values())for(let Y of J.catalogs.values())for(let X of Y.cards)if(Z.add(X.catalog),X.language)Q.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),availableTypes:Z,availableLanguages:Q}}hasAlternativeType(Z,Q){return this.getAllAlternatives(Z).some((Y)=>Y.type===Q)}getCatalogsByType(Z){let Q=new Set;for(let[J,Y]of this.assessmentCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.itemCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.scopedCatalogEntries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);return Array.from(Q)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}var y8=["assessmentId","sectionId","attemptId","itemId","elementId"];function h5(Z){return Z.replace(/%/g,"%25").replace(/:/g,"%3A")}function M6(Z){return Z.replace(/%(25|3A)/g,(Q,J)=>J==="25"?"%":":")}class m5{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Z){return y8.map((Q)=>h5(Z[Q])).join(":")}parseGlobalElementId(Z){let Q=Z.split(":");if(Q.length!==y8.length)return null;let[J,Y,X,G,j]=Q.map(M6);return{assessmentId:J,sectionId:Y,attemptId:X,itemId:G,elementId:j}}setState(Z,Q,J){let Y=this.elementStates.get(Z);if(!Y)Y=new Map,this.elementStates.set(Z,Y);Y.set(Q,J),this._notifyListeners(),this._notifyStateChange()}getState(Z,Q){return this.elementStates.get(Z)?.get(Q)}getElementState(Z){let Q=this.elementStates.get(Z);if(!Q)return{};return Object.fromEntries(Q.entries())}getAllState(){let Z={};for(let[Q,J]of this.elementStates.entries())Z[Q]=Object.fromEntries(J.entries());return Z}subscribe(Z){return this.listeners.add(Z),()=>this.listeners.delete(Z)}_notifyListeners(){if(this.listeners.size===0)return;let Z=new Map([...this.elementStates].map(([Q,J])=>[Q,new Map(J)]));for(let Q of this.listeners)try{Q(Z)}catch(J){console.warn("[ElementToolStateStore] listener failed:",J)}}setOnStateChange(Z){this.onStateChange=Z}_notifyStateChange(){if(!this.onStateChange)return;try{this.onStateChange(this.getAllState())}catch(Z){console.warn("[ElementToolStateStore] state-change callback failed:",Z)}}loadState(Z){this.elementStates.clear();for(let[Q,J]of Object.entries(Z)){let Y=new Map(Object.entries(J));this.elementStates.set(Q,Y)}this._notifyListeners()}clearElement(Z){this.elementStates.delete(Z),this._notifyListeners(),this._notifyStateChange()}clearTool(Z){for(let Q of this.elementStates.values())Q.delete(Z);this._notifyListeners(),this._notifyStateChange()}clearSection(Z,Q){let J=`${h5(Z)}:${h5(Q)}:`,Y=[];for(let X of this.elementStates.keys())if(X.startsWith(J))Y.push(X);for(let X of Y)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}function IZ(Z){return{kind:Z.kind,severity:Z.severity??"error",source:Z.source,message:Z.message,details:[...Z.details||[]],recoverable:Z.recoverable===!0,scope:Z.scope??"runtime",...Z.cohort?{cohort:{...Z.cohort}}:{},cause:Z.cause}}function u5(Z){let Q=Z.error instanceof Error&&Z.error.message.trim().length>0?Z.error.message:String(Z.error||"Unknown framework error");return IZ({kind:Z.kind,source:Z.source,message:Q,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort,cause:Z.error})}var O6={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose","tool-module-load":"tool-module-load","tool-request-open":"tool-request","tool-request-host-check":"tool-request","tool-visibility":"tool-registration","tool-applicability":"tool-registration","tool-state-load":"tool-state-load","tool-state-save":"tool-state-save","tool-playback":"tool-playback"};function T8(Z){let Q=O6[Z.context.phase],J=Z.context.toolId?`pie-toolkit-coordinator/${Z.context.toolId}`:`pie-toolkit-coordinator:${Z.context.phase}`;return u5({kind:Q,source:J,error:Z.error,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort})}function x8(Z){let Q=`[pie-framework:${Z.kind}:${Z.source}]`;if(Z.details.length===0)return`${Q} ${Z.message}`;return`${Q} ${Z.message}
4
4
  - ${Z.details.join(`
5
- - `)}`}class W0{listeners=new Set;subscribeFrameworkErrors(Z){this.listeners.add(Z);let Q=!0;return()=>{if(!Q)return;Q=!1,this.listeners.delete(Z)}}reportFrameworkError(Z){let Q=Array.from(this.listeners);for(let J of Q)try{J(Z)}catch(Y){console.warn("[FrameworkErrorBus] listener failed:",Y)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}var t6=new Set(["pie-item-toolbar","pie-section-toolbar","pie-item-player-session-debugger"]),e6=["pie-tool-","pie-section-player-tools-"],Z4=new Set(["style","script","noscript","template"]),m=(Z)=>!!Z&&Z.nodeType===11&&Z.host?.nodeType===1,Q4=(Z)=>{let Q=Z.localName?.toLowerCase()||"";if(t6.has(Q))return!0;return e6.some((J)=>Q.startsWith(J))},J4=(Z)=>{let Q=Z.localName?.toLowerCase()||"";if(Z4.has(Q))return!0;if(Q4(Z))return!0;return m(Z.parentNode)&&Z.getAttribute("aria-hidden")==="true"},Y4=(Z)=>{if(!m(Z.getRootNode?.()))return null;let Q=Z.assignedNodes;if(typeof Q!=="function")return null;try{return Q.call(Z,{flatten:!0})}catch{return null}},KZ=(Z)=>{let Q=Z.childNodes;if(Z.nodeType===1){let Y=Z,X=Y.shadowRoot;if(X)Q=X.childNodes;else if(Y.localName?.toLowerCase()==="slot")Q=Y4(Y)??Y.childNodes}let J=[];for(let Y of Array.from(Q||[])){if(Y.nodeType===1&&J4(Y))continue;J.push(Y)}return J},V0=(Z,Q)=>{let J=(Y)=>{for(let X of KZ(Y)){let G=Q(X);if(G==="stop")return!1;if(G==="skip")continue;if(!J(X))return!1}return!0};J(Z)},RZ=(Z)=>{let Q=[];return V0(Z,(J)=>{if(J.nodeType===3)Q.push(J);return}),Q},H8=(Z)=>RZ(Z).map((Q)=>Q.data).join(""),_8=(Z,Q)=>{let J=[];return V0(Z,(Y)=>{if(Y.nodeType===1&&Y.matches(Q))J.push(Y);return}),J},CZ=(Z,Q)=>{let J=null;return V0(Z,(Y)=>{if(Y.nodeType===1&&Y.matches(Q))return J=Y,"stop";return}),J},A8=(Z)=>{let Q=Z.assignedSlot;if(Q)return Q;let J=Z.parentNode;if(m(J))return J.host;return J},p=(Z)=>{let Q=A8(Z);while(Q&&Q.nodeType!==1)Q=A8(Q);return Q},T5=(Z,Q)=>{let J=Z.nodeType===1?Z:p(Z);while(J){if(J.matches(Q))return J;J=p(J)}return null},g=(Z)=>{if(Z.parentElement)return Z.parentElement;let Q=Z.parentNode;return m(Q)?Q.host:null},S0=(Z,Q,J)=>{let Y=Z.nodeType===1?Z:g(Z);while(Y){if(Y.matches(Q))return Y;if(J&&Y===J)return null;Y=g(Y)}return null},ZZ=(Z,Q)=>{if(!Z||!Q)return!1;let J=Q;while(J){if(J===Z||Z.contains(J))return!0;let Y=J.getRootNode?.();J=m(Y)?Y.host:null}return!1},O8=(Z,Q)=>{let J=Z;while(J){let Y=J.getRootNode?.();if(Y===Q)return J;J=m(Y)?Y.host:null}return null},q0=(Z,Q,J)=>{try{let Y=Z.startContainer.getRootNode?.();if(!Y||Q.getRootNode?.()===Y)return Z.comparePoint(Q,J)===0&&Z.comparePoint(Q,Math.min(J+1,Q.length))===0;return L8(Z,O8(Q,Y))}catch{return!1}},YZ=(Z,Q)=>{try{let J=Z.startContainer.getRootNode?.();if(!J||Q.getRootNode?.()===J)return Z.intersectsNode(Q);return L8(Z,O8(Q,J))}catch{return!1}},L8=(Z,Q)=>{let J=Q?.parentNode;if(!Q||!J)return!1;let Y=Array.prototype.indexOf.call(J.childNodes,Q);if(Y<0)return!1;return Z.comparePoint(J,Y)===0&&Z.comparePoint(J,Y+1)===0};var x5=" >>> ";class k5{serialize(Z,Q){return{startContainer:this.getNodePath(Z.startContainer,Q),startOffset:Z.startOffset,endContainer:this.getNodePath(Z.endContainer,Q),endOffset:Z.endOffset,text:Z.toString()}}deserialize(Z,Q){let J=this.findNodeByPath(Z.startContainer,Q),Y=this.findNodeByPath(Z.endContainer,Q);if(!J||!Y)return null;try{let X=new Range;if(X.setStart(J,Z.startOffset),X.setEnd(Y,Z.endOffset),X.toString()===Z.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Z,Q){if(Z===Q)return"";if(Z.nodeType===Node.TEXT_NODE){let J=Z.parentNode;if(!J)throw Error("Text node has no parent");let X=Array.from(J.childNodes).filter((j)=>j.nodeType===Node.TEXT_NODE).indexOf(Z);return`${m(J)?this.getShadowRootPath(J,Q):this.getElementPath(J,Q)}::text[${X}]`}if(Z.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Z,Q);if(m(Z))return this.getShadowRootPath(Z,Q);throw Error(`Unsupported node type: ${Z.nodeType}`)}getElementPath(Z,Q){if(Z===Q)return"";let J=Q.getRootNode?.(),Y=[],X=[],G=Z,j=(B)=>{Y.unshift(X.join(" > ")),X=[],G=B.host};while(G&&G!==Q){if(G.id){X.unshift(`#${G.id}`);let L=G.getRootNode?.();if(m(L)&&L!==J){j(L);continue}break}let{parentElement:B,parentNode:V}=G,K=B??(m(V)?V:null);if(!K)break;let U=G.tagName,$=Array.from(K.children).filter((L)=>L.tagName===U),z=$.indexOf(G),D=$.length>1?`${U.toLowerCase()}:nth-of-type(${z+1})`:U.toLowerCase();if(X.unshift(D),B)G=B;else j(K)}return Y.unshift(X.join(" > ")),Y.join(x5)}getShadowRootPath(Z,Q){return`${this.getElementPath(Z.host,Q)}${x5}`}resolveElementPath(Z,Q){let J=Q,Y=Z.split(x5);for(let X=0;X<Y.length;X++){if(X>0){let B=m(J)?null:J.shadowRoot;if(!B)return null;J=B}let G=Y[X].trim();if(!G)continue;let j=J.querySelector(G);if(!j)return null;J=j}return J}findNodeByPath(Z,Q){if(Z==="")return Q;if(Z.includes("::text[")){let J=Z.lastIndexOf("::text["),Y=Z.slice(0,J),X=Z.slice(J+7),G=Number.parseInt(X.replace("]",""),10),j;try{j=this.resolveElementPath(Y,Q)}catch(V){return console.warn("Invalid selector path:",Z,V),null}if(!j)return null;return Array.from(j.childNodes).filter((V)=>V.nodeType===Node.TEXT_NODE)[G]||null}try{return this.resolveElementPath(Z,Q)}catch(J){return console.warn("Invalid selector path:",Z,J),null}}}var v5;(function(Z){Z.TTS_WORD="tts-word",Z.TTS_SENTENCE="tts-sentence",Z.ANNOTATION="annotation"})(v5||(v5={}));var y0;(function(Z){Z.YELLOW="yellow",Z.GREEN="green",Z.BLUE="blue",Z.PINK="pink",Z.ORANGE="orange",Z.UNDERLINE="underline"})(y0||(y0={}));var R8=`
5
+ - `)}`}class UZ{listeners=new Set;subscribeFrameworkErrors(Z){this.listeners.add(Z);let Q=!0;return()=>{if(!Q)return;Q=!1,this.listeners.delete(Z)}}reportFrameworkError(Z){let Q=Array.from(this.listeners);for(let J of Q)try{J(Z)}catch(Y){console.warn("[FrameworkErrorBus] listener failed:",Y)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}var L6=new Set(["pie-item-toolbar","pie-section-toolbar","pie-item-player-session-debugger"]),P6=["pie-tool-","pie-section-player-tools-"],N6=new Set(["style","script","noscript","template"]),p=(Z)=>!!Z&&Z.nodeType===11&&Z.host?.nodeType===1,w6=(Z)=>{let Q=Z.localName?.toLowerCase()||"";if(L6.has(Q))return!0;return P6.some((J)=>Q.startsWith(J))},R6=(Z)=>{let Q=Z.localName?.toLowerCase()||"";if(N6.has(Q))return!0;if(w6(Z))return!0;return p(Z.parentNode)&&Z.getAttribute("aria-hidden")==="true"},C6=(Z)=>{if(!p(Z.getRootNode?.()))return null;let Q=Z.assignedNodes;if(typeof Q!=="function")return null;try{return Q.call(Z,{flatten:!0})}catch{return null}},F0=(Z)=>{let Q=Z.childNodes;if(Z.nodeType===1){let Y=Z,X=Y.shadowRoot;if(X)Q=X.childNodes;else if(Y.localName?.toLowerCase()==="slot")Q=C6(Y)??Y.childNodes}let J=[];for(let Y of Array.from(Q||[])){if(Y.nodeType===1&&R6(Y))continue;J.push(Y)}return J},$Z=(Z,Q)=>{let J=(Y)=>{for(let X of F0(Y)){let G=Q(X);if(G==="stop")return!1;if(G==="skip")continue;if(!J(X))return!1}return!0};J(Z)},C0=(Z)=>{let Q=[];return $Z(Z,(J)=>{if(J.nodeType===3)Q.push(J);return}),Q},f8=(Z)=>C0(Z).map((Q)=>Q.data).join(""),I8=(Z,Q)=>{let J=[];return $Z(Z,(Y)=>{if(Y.nodeType===1&&Y.matches(Q))J.push(Y);return}),J},b0=(Z,Q)=>{let J=null;return $Z(Z,(Y)=>{if(Y.nodeType===1&&Y.matches(Q))return J=Y,"stop";return}),J},k8=(Z)=>{let Q=Z.assignedSlot;if(Q)return Q;let J=Z.parentNode;if(p(J))return J.host;return J},d=(Z)=>{let Q=k8(Z);while(Q&&Q.nodeType!==1)Q=k8(Q);return Q},p5=(Z,Q)=>{let J=Z.nodeType===1?Z:d(Z);while(J){if(J.matches(Q))return J;J=d(J)}return null},i=(Z)=>{if(Z.parentElement)return Z.parentElement;let Q=Z.parentNode;return p(Q)?Q.host:null},vZ=(Z,Q,J)=>{let Y=Z.nodeType===1?Z:i(Z);while(Y){if(Y.matches(Q))return Y;if(J&&Y===J)return null;Y=i(Y)}return null},J0=(Z,Q)=>{if(!Z||!Q)return!1;let J=Q;while(J){if(J===Z||Z.contains(J))return!0;let Y=J.getRootNode?.();J=p(Y)?Y.host:null}return!1},v8=(Z,Q)=>{let J=Z;while(J){let Y=J.getRootNode?.();if(Y===Q)return J;J=p(Y)?Y.host:null}return null},FZ=(Z,Q,J)=>{try{let Y=Z.startContainer.getRootNode?.();if(!Y||Q.getRootNode?.()===Y)return Z.comparePoint(Q,J)===0&&Z.comparePoint(Q,Math.min(J+1,Q.length))===0;return h8(Z,v8(Q,Y))}catch{return!1}},G0=(Z,Q)=>{try{let J=Z.startContainer.getRootNode?.();if(!J||Q.getRootNode?.()===J)return Z.intersectsNode(Q);return h8(Z,v8(Q,J))}catch{return!1}},h8=(Z,Q)=>{let J=Q?.parentNode;if(!Q||!J)return!1;let Y=Array.prototype.indexOf.call(J.childNodes,Q);if(Y<0)return!1;return Z.comparePoint(J,Y)===0&&Z.comparePoint(J,Y+1)===0};var g5=" >>> ";class c5{serialize(Z,Q){return{startContainer:this.getNodePath(Z.startContainer,Q),startOffset:Z.startOffset,endContainer:this.getNodePath(Z.endContainer,Q),endOffset:Z.endOffset,text:Z.toString()}}deserialize(Z,Q){let J=this.findNodeByPath(Z.startContainer,Q),Y=this.findNodeByPath(Z.endContainer,Q);if(!J||!Y)return null;try{let X=new Range;if(X.setStart(J,Z.startOffset),X.setEnd(Y,Z.endOffset),X.toString()===Z.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Z,Q){if(Z===Q)return"";if(Z.nodeType===Node.TEXT_NODE){let J=Z.parentNode;if(!J)throw Error("Text node has no parent");let X=Array.from(J.childNodes).filter((j)=>j.nodeType===Node.TEXT_NODE).indexOf(Z);return`${p(J)?this.getShadowRootPath(J,Q):this.getElementPath(J,Q)}::text[${X}]`}if(Z.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Z,Q);if(p(Z))return this.getShadowRootPath(Z,Q);throw Error(`Unsupported node type: ${Z.nodeType}`)}getElementPath(Z,Q){if(Z===Q)return"";let J=Q.getRootNode?.(),Y=[],X=[],G=Z,j=(B)=>{Y.unshift(X.join(" > ")),X=[],G=B.host};while(G&&G!==Q){if(G.id){X.unshift(`#${G.id}`);let O=G.getRootNode?.();if(p(O)&&O!==J){j(O);continue}break}let{parentElement:B,parentNode:V}=G,q=B??(p(V)?V:null);if(!q)break;let U=G.tagName,$=Array.from(q.children).filter((O)=>O.tagName===U),z=$.indexOf(G),A=$.length>1?`${U.toLowerCase()}:nth-of-type(${z+1})`:U.toLowerCase();if(X.unshift(A),B)G=B;else j(q)}return Y.unshift(X.join(" > ")),Y.join(g5)}getShadowRootPath(Z,Q){return`${this.getElementPath(Z.host,Q)}${g5}`}resolveElementPath(Z,Q){let J=Q,Y=Z.split(g5);for(let X=0;X<Y.length;X++){if(X>0){let B=p(J)?null:J.shadowRoot;if(!B)return null;J=B}let G=Y[X].trim();if(!G)continue;let j=J.querySelector(G);if(!j)return null;J=j}return J}findNodeByPath(Z,Q){if(Z==="")return Q;if(Z.includes("::text[")){let J=Z.lastIndexOf("::text["),Y=Z.slice(0,J),X=Z.slice(J+7),G=Number.parseInt(X.replace("]",""),10),j;try{j=this.resolveElementPath(Y,Q)}catch(V){return console.warn("Invalid selector path:",Z,V),null}if(!j)return null;return Array.from(j.childNodes).filter((V)=>V.nodeType===Node.TEXT_NODE)[G]||null}try{return this.resolveElementPath(Z,Q)}catch(J){return console.warn("Invalid selector path:",Z,J),null}}}var s5;(function(Z){Z.TTS_WORD="tts-word",Z.TTS_SENTENCE="tts-sentence",Z.ANNOTATION="annotation"})(s5||(s5={}));var hZ;(function(Z){Z.YELLOW="yellow",Z.GREEN="green",Z.BLUE="blue",Z.PINK="pink",Z.ORANGE="orange",Z.UNDERLINE="underline"})(hZ||(hZ={}));var d5="pie-highlight-styles-v2",c8=`
6
6
  /* TTS highlights - temporary */
7
- ::highlight(tts-word) {
7
+ ::highlight(pie-tts-word) {
8
8
  background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
9
9
  text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
10
10
  text-underline-offset: 2px;
@@ -12,8 +12,8 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
12
12
  color: inherit;
13
13
  }
14
14
 
15
- /* tts-sentence registry id: coarse read-along band (visual line boxes in layout) */
16
- ::highlight(tts-sentence) {
15
+ /* pie-tts-sentence registry id: coarse read-along band (visual line boxes in layout) */
16
+ ::highlight(pie-tts-sentence) {
17
17
  background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));
18
18
  color: inherit;
19
19
  }
@@ -38,27 +38,27 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
38
38
  }
39
39
 
40
40
  /* Annotation highlights - persistent */
41
- ::highlight(annotation-yellow) {
41
+ ::highlight(pie-annotation-yellow) {
42
42
  background-color: var(--pie-annotation-yellow-highlight, rgba(253, 233, 149, 0.5));
43
43
  color: inherit;
44
44
  }
45
45
 
46
- ::highlight(annotation-green) {
46
+ ::highlight(pie-annotation-green) {
47
47
  background-color: var(--pie-annotation-green-highlight, rgba(166, 225, 197, 0.5));
48
48
  color: inherit;
49
49
  }
50
50
 
51
- ::highlight(annotation-blue) {
51
+ ::highlight(pie-annotation-blue) {
52
52
  background-color: var(--pie-annotation-blue-highlight, rgba(167, 224, 246, 0.5));
53
53
  color: inherit;
54
54
  }
55
55
 
56
- ::highlight(annotation-pink) {
56
+ ::highlight(pie-annotation-pink) {
57
57
  background-color: var(--pie-annotation-pink-highlight, rgba(255, 159, 174, 0.5));
58
58
  color: inherit;
59
59
  }
60
60
 
61
- ::highlight(annotation-orange) {
61
+ ::highlight(pie-annotation-orange) {
62
62
  background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.5));
63
63
  color: inherit;
64
64
  }
@@ -71,7 +71,7 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
71
71
  Each state has its own token so overriding one never silently moves the
72
72
  other, and so either can beat a host-set pie-primary: a var() fallback
73
73
  can never override a value the host actually set. */
74
- ::highlight(annotation-underline) {
74
+ ::highlight(pie-annotation-underline) {
75
75
  background-color: transparent;
76
76
  text-decoration: underline 2px solid var(--pie-annotation-underline, #4221d5);
77
77
  text-underline-offset: 2px;
@@ -94,22 +94,22 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
94
94
  check. Spell property names in full, or omit the dashes. */
95
95
 
96
96
  @media (prefers-color-scheme: dark) {
97
- ::highlight(annotation-yellow) {
97
+ ::highlight(pie-annotation-yellow) {
98
98
  background-color: var(--pie-annotation-yellow-highlight, rgba(139, 117, 0, 0.6));
99
99
  }
100
- ::highlight(annotation-green) {
100
+ ::highlight(pie-annotation-green) {
101
101
  background-color: var(--pie-annotation-green-highlight, rgba(45, 92, 63, 0.6));
102
102
  }
103
- ::highlight(annotation-blue) {
103
+ ::highlight(pie-annotation-blue) {
104
104
  background-color: var(--pie-annotation-blue-highlight, rgba(0, 102, 170, 0.6));
105
105
  }
106
- ::highlight(annotation-pink) {
106
+ ::highlight(pie-annotation-pink) {
107
107
  background-color: var(--pie-annotation-pink-highlight, rgba(139, 51, 74, 0.6));
108
108
  }
109
- ::highlight(annotation-orange) {
109
+ ::highlight(pie-annotation-orange) {
110
110
  background-color: var(--pie-annotation-orange-highlight, rgba(154, 99, 0, 0.6));
111
111
  }
112
- ::highlight(annotation-underline) {
112
+ ::highlight(pie-annotation-underline) {
113
113
  text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
114
114
  }
115
115
  }
@@ -125,17 +125,17 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
125
125
  All carry attribute selectors, which outrank the bare ::highlight() rules
126
126
  above -- including the one inside the media query, since a media query
127
127
  adds no specificity -- whatever the source order. */
128
- [data-theme="light"] ::highlight(annotation-underline) {
128
+ [data-theme="light"] ::highlight(pie-annotation-underline) {
129
129
  text-decoration-color: var(--pie-annotation-underline, #4221d5);
130
130
  }
131
131
 
132
- [data-theme="dark"] ::highlight(annotation-underline) {
132
+ [data-theme="dark"] ::highlight(pie-annotation-underline) {
133
133
  text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
134
134
  }
135
135
 
136
136
  /* A host or DaisyUI palette: follow its accent so the mark belongs to that
137
137
  theme, falling back to the light default when it declares none. */
138
- [data-theme]:not([data-theme="light"]):not([data-theme="dark"]) ::highlight(annotation-underline) {
138
+ [data-theme]:not([data-theme="light"]):not([data-theme="dark"]) ::highlight(pie-annotation-underline) {
139
139
  text-decoration-color: var(--pie-annotation-underline, var(--pie-primary, #4221d5));
140
140
  }
141
141
 
@@ -150,30 +150,30 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
150
150
  browser even had the file been loaded. Verified with matchMedia under
151
151
  emulation: "high" stays false where "more" flips true. */
152
152
  @media (prefers-contrast: more) {
153
- ::highlight(annotation-yellow) {
153
+ ::highlight(pie-annotation-yellow) {
154
154
  background-color: var(--pie-annotation-yellow-highlight, rgba(255, 255, 0, 0.7));
155
155
  }
156
- ::highlight(annotation-green) {
156
+ ::highlight(pie-annotation-green) {
157
157
  background-color: var(--pie-annotation-green-highlight, rgba(0, 255, 127, 0.7));
158
158
  }
159
- ::highlight(annotation-blue) {
159
+ ::highlight(pie-annotation-blue) {
160
160
  background-color: var(--pie-annotation-blue-highlight, rgba(0, 191, 255, 0.7));
161
161
  }
162
- ::highlight(annotation-pink) {
162
+ ::highlight(pie-annotation-pink) {
163
163
  background-color: var(--pie-annotation-pink-highlight, rgba(255, 105, 180, 0.7));
164
164
  }
165
- ::highlight(annotation-orange) {
165
+ ::highlight(pie-annotation-orange) {
166
166
  background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.85));
167
167
  }
168
- ::highlight(annotation-underline) {
168
+ ::highlight(pie-annotation-underline) {
169
169
  text-decoration-thickness: 3px;
170
170
  }
171
171
  }
172
172
 
173
173
  @media print {
174
174
  /* TTS highlighting is a transient read-along cue, not content. */
175
- ::highlight(tts-word),
176
- ::highlight(tts-sentence),
175
+ ::highlight(pie-tts-word),
176
+ ::highlight(pie-tts-sentence),
177
177
  [data-pie-tts-word-element="true"],
178
178
  [data-pie-tts-sentence-element="true"] {
179
179
  background-color: transparent;
@@ -185,20 +185,20 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
185
185
  /* Annotations are student work and must survive printing, but a fill
186
186
  that reads fine on screen can print as an illegible wash, so each
187
187
  becomes an underline that keeps its colour coding. */
188
- ::highlight(annotation-yellow),
189
- ::highlight(annotation-green),
190
- ::highlight(annotation-blue),
191
- ::highlight(annotation-pink),
192
- ::highlight(annotation-orange) {
188
+ ::highlight(pie-annotation-yellow),
189
+ ::highlight(pie-annotation-green),
190
+ ::highlight(pie-annotation-blue),
191
+ ::highlight(pie-annotation-pink),
192
+ ::highlight(pie-annotation-orange) {
193
193
  background-color: transparent;
194
194
  border-bottom: 2px solid currentColor;
195
195
  }
196
- ::highlight(annotation-yellow) { border-bottom-color: #ffeb3b; }
197
- ::highlight(annotation-green) { border-bottom-color: #a6e1c5; }
198
- ::highlight(annotation-blue) { border-bottom-color: #a7e0f6; }
199
- ::highlight(annotation-pink) { border-bottom-color: #ff9fae; }
200
- ::highlight(annotation-orange) { border-bottom-color: #ffa500; }
201
- ::highlight(annotation-underline) {
196
+ ::highlight(pie-annotation-yellow) { border-bottom-color: #ffeb3b; }
197
+ ::highlight(pie-annotation-green) { border-bottom-color: #a6e1c5; }
198
+ ::highlight(pie-annotation-blue) { border-bottom-color: #a7e0f6; }
199
+ ::highlight(pie-annotation-pink) { border-bottom-color: #ff9fae; }
200
+ ::highlight(pie-annotation-orange) { border-bottom-color: #ffa500; }
201
+ ::highlight(pie-annotation-underline) {
202
202
  text-decoration-color: #000;
203
203
  border-bottom: none;
204
204
  }
@@ -207,12 +207,12 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
207
207
  /* text-shadow is a direct property rather than a var(), so unlike the
208
208
  other TTS rules this one is not overridden by the adaptive path. */
209
209
  @media (prefers-reduced-motion: reduce) {
210
- ::highlight(tts-word),
210
+ ::highlight(pie-tts-word),
211
211
  [data-pie-tts-word-element="true"] {
212
212
  text-shadow: none;
213
213
  }
214
214
  }
215
- `,M8=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet"),P8=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet-adopted"),N8=(Z)=>!!Z&&typeof Z.replaceSync==="function",X4=()=>{let Z=globalThis,Q=Z[M8];if(N8(Q))return Q;let J=globalThis.CSSStyleSheet;if(typeof J!=="function")return null;try{let Y=new J;if(!N8(Y))return null;return Y.replaceSync(R8),Z[M8]=Y,Y}catch{return null}},K0=(Z)=>{let Q=Z?.getRootNode?.();if(!m(Q))return;let J=Q,Y=J.adoptedStyleSheets;if(!Y||typeof Y!=="object")return;let X=Array.from(Y),G=J[P8];if(G&&X.includes(G))return;let j=X4();if(!j)return;try{J.adoptedStyleSheets=[...X,j],J[P8]=j}catch{}},f5="tts-word",I5="tts-sentence",dZ=(Z)=>`annotation-${Z}`,bZ=(Z)=>{let Q=CSS.highlights.get(Z);if(Q)return Q;let J=new Highlight;return CSS.highlights.set(Z,J),J},U0=(Z,Q)=>{let J=CSS.highlights.get(Z);if(!J)return;for(let Y of Q)J.delete(Y)},w8=(Z)=>{let Q=Z[0]?.startContainer;if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:g(Q)},XZ={source:null,override:null};class $0{ttsWordRanges=new Set;ttsSentenceRanges=new Set;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;ttsStyleSource=null;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;constructor(){if(this.rangeSerializer=new k5,typeof CSS>"u"||!("highlights"in CSS)){console.warn("CSS Custom Highlight API not supported (SSR or unsupported browser)");return}this.supported=!0,this.initializeHighlights(),this.registerStyles(),this.applyAdaptiveTTSStyle(),this.setupThemeObservation()}setupThemeObservation(){if(typeof document>"u")return;if(typeof MutationObserver>"u")return;let Z=document.getElementsByTagName("pie-theme"),Q=new WeakSet,J=()=>{let X=!1;for(let G of Z){if(Q.has(G))continue;Q.add(G),Y.observe(G,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]}),X=!0}return X},Y=new MutationObserver((X)=>{if(J()||X.some((j)=>j.type==="attributes"))this.applyAdaptiveTTSStyle()});this.themeObserver=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]}),Y.observe(document,{childList:!0,subtree:!0}),J()}parseColor(Z){if(!Z)return null;let Q=Z.trim();if(!Q)return null;let J=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(Q);if(J){let X=J[1];if(X.length===3)return[parseInt(X[0]+X[0],16),parseInt(X[1]+X[1],16),parseInt(X[2]+X[2],16)];return[parseInt(X.slice(0,2),16),parseInt(X.slice(2,4),16),parseInt(X.slice(4,6),16)]}let Y=/^rgba?\((.+)\)$/i.exec(Q);if(Y){let G=Y[1].replace(/\//g,",").split(/[,\s]+/).map((K)=>K.trim()).filter(Boolean),j=Number(G[0]),B=Number(G[1]),V=Number(G[2]);if(Number.isFinite(j)&&Number.isFinite(B)&&Number.isFinite(V))return[j,B,V]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=Q,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let G=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let j=G.trim();if(j&&j!==Q)return this.parseColor(G)}}return null}relativeLuminance([Z,Q,J]){let Y=(B)=>{let V=B/255;return V<=0.03928?V/12.92:((V+0.055)/1.055)**2.4},X=Y(Z),G=Y(Q),j=Y(J);return 0.2126*X+0.7152*G+0.0722*j}contrastRatio(Z,Q){let J=this.relativeLuminance(Z),Y=this.relativeLuminance(Q),X=Math.max(J,Y),G=Math.min(J,Y);return(X+0.05)/(G+0.05)}blend(Z,Q,J){return[Math.round(Z[0]*J+Q[0]*(1-J)),Math.round(Z[1]*J+Q[1]*(1-J)),Math.round(Z[2]*J+Q[2]*(1-J))]}resolveAdaptiveTTSStyle(Z){let Q=[255,235,59],J=[17,24,39],Y=[255,255,255],X=Z||(typeof document<"u"?document.documentElement:null),G=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,j=this.parseColor(G?.getPropertyValue("--pie-background")||G?.backgroundColor)||Y,B=this.parseColor(G?.getPropertyValue("--pie-text"))||J,V=XZ.override,K=V?this.parseColor(V.color)||Q:this.parseColor(G?.getPropertyValue("--pie-missing"))||Q,U=V?[Math.max(0.3,Math.min(0.95,V.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],$=U[U.length-1],z=-1/0;for(let r of U){let s=this.blend(K,j,r),AZ=this.contrastRatio(s,j),HZ=this.contrastRatio(s,B),_Z=AZ*1.2+HZ*0.8;if(AZ>=1.25&&HZ>=2.4){$=r;break}if(_Z>z)z=_Z,$=r}let D=Math.max(0.24,Math.min(0.85,$*0.55)),L=Math.max(0.55,Math.min(0.95,$+0.2)),P=Math.max(0.22,Math.min(0.6,$*0.45)),A=B,N=this.blend(A,j,L),O=this.contrastRatio(N,j),S=this.relativeLuminance(j)>0.45?[0,0,0]:[255,255,255],C=O>=1.35?A:S,h=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${$})`,b=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${D})`,d=`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${L})`,VZ=`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${P})`;return{wordHighlight:h,sentenceHighlight:b,wordUnderline:d,wordShadow:VZ}}applyAdaptiveTTSStyle(Z){if(typeof document>"u")return;if(Z)this.ttsStyleSource=Z,XZ.source=Z;let Q=Z??(XZ.source?.isConnected?XZ.source:null),J=this.resolveAdaptiveTTSStyle(Q),Y=document.documentElement.style,X=[["--pie-tts-word-highlight",J.wordHighlight],["--pie-tts-sentence-highlight",J.sentenceHighlight],["--pie-tts-line-highlight",J.sentenceHighlight],["--pie-tts-word-underline",J.wordUnderline],["--pie-tts-word-shadow",J.wordShadow]];for(let[G,j]of X){if(Y.getPropertyValue?.(G)===j)continue;Y.setProperty(G,j)}}initializeHighlights(){if(!this.supported)return;bZ(f5),bZ(I5);for(let Z of Object.values(y0))bZ(dZ(Z))}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById("pie-highlight-styles"))return;let Z=document.createElement("style");Z.id="pie-highlight-styles",Z.textContent=R8,document.head.appendChild(Z)}highlightTTSWord(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(w8(Z)),this.clearTTSWord();let Q=bZ(f5);for(let J of Z)K0(J.startContainer),Q.add(J),this.ttsWordRanges.add(J);this.highlightTTSWordElementFallbacks(Z.filter((J)=>J.startContainer!==J.endContainer||J.startContainer.nodeType!==Node.TEXT_NODE))}highlightTTSWordElement(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(Z),K0(Z),this.clearTTSWord(),Z.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Z)}highlightTTSSentence(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(w8(Z)),this.clearTTSSentence();let Q=bZ(I5);for(let J of Z)K0(J.startContainer),Q.add(J),this.ttsSentenceRanges.add(J);this.highlightTTSElementFallbacks(Z)}highlightTTSSentenceElements(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(Z[0]||null),this.clearTTSSentence();for(let Q of Z)K0(Q),Q.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(Q)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Z){if(typeof Element>"u")return;this.highlightElementFallbacks(Z,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,$0.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Z){if(typeof Element>"u")return;this.highlightElementFallbacks(Z,"data-pie-tts-word-element",this.ttsWordElementHighlights,$0.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Z,Q,J,Y){let X=(G)=>G.nodeType===Node.ELEMENT_NODE?G:g(G);for(let G of Z){let j=G.commonAncestorContainer,B=m(j)?j:X(j);if(!B)continue;let V=[],K=X(G.startContainer),U=X(G.endContainer);for(let $ of[K,U]){let z=$;while(z){if(z.matches?.(Y))V.push(z);z=g(z)}}if(!m(B)&&B.matches?.(Y))V.push(B);V.push(...Array.from(B.querySelectorAll(Y)));for(let $ of new Set(V)){try{if(!G.intersectsNode($)&&!ZZ($,K)&&!ZZ($,U))continue}catch{continue}$.setAttribute(Q,"true"),J.add($)}}}clearTTSWord(){if(!this.supported)return;U0(f5,this.ttsWordRanges),this.ttsWordRanges.clear();for(let Z of this.ttsWordElementHighlights)Z.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.supported)return;U0(I5,this.ttsSentenceRanges),this.ttsSentenceRanges.clear();for(let Z of this.ttsSentenceElementHighlights)Z.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){if(this.clearTTSWord(),this.clearTTSSentence(),XZ.source===this.ttsStyleSource)XZ.source=null;this.ttsStyleSource=null}addAnnotation(Z,Q=y0.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,Y=Z.cloneRange();K0(Y.startContainer);let X={id:J,range:Y,type:v5.ANNOTATION,color:Q,timestamp:Date.now()};if(this.annotations.set(J,X),this.supported)bZ(dZ(Q)).add(Y);return J}removeAnnotation(Z){let Q=this.annotations.get(Z);if(!Q){console.warn(`[HighlightCoordinator] Annotation ${Z} not found`);return}if(this.supported)U0(dZ(Q.color),[Q.range]);this.annotations.delete(Z)}clearAnnotations(){if(this.supported)for(let Z of this.annotations.values())U0(dZ(Z.color),[Z.range]);this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Z){return this.annotations.get(Z)??null}changeAnnotationColor(Z,Q){let J=this.annotations.get(Z);if(!J)return;let Y=J.color;if(Y===Q)return;if(J.color=Q,this.supported)U0(dZ(Y),[J.range]),bZ(dZ(Q)).add(J.range)}exportAnnotations(Z=document.body){return this.getAnnotations().map((Q)=>({...this.rangeSerializer.serialize(Q.range,Z),id:Q.id,color:Q.color,timestamp:Q.timestamp}))}importAnnotations(Z,Q=document.body){let J=0;for(let Y of Z){let X=this.rangeSerializer.deserialize(Y,Q);if(X)this.addAnnotation(X,Y.color),J++}return J}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}updateTTSHighlightStyle(Z,Q){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById("pie-highlight-styles"))return;let X=((G)=>{let j=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(G);return j?{r:parseInt(j[1],16),g:parseInt(j[2],16),b:parseInt(j[3],16)}:null})(Z);if(!X)return;XZ.override={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,Q)),owner:this},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),XZ.override?.owner===this)XZ.override=null;this.themeObserver?.disconnect(),this.themeObserver=null}}import{applyMediaFragment as g3,enforceMediaFragment as c3}from"@pie-players/pie-players-shared/media";import{createPieLogger as d3,isTtsDebugEnabled as v9}from"@pie-players/pie-players-shared/pie";import{isUnsupportedMediaAssetVersion as G4,normalizeMediaFragment as j4,normalizeMediaSources as B4,trimmedOrUndefined as W4}from"@pie-players/pie-players-shared/media";function C8(Z){if(!Z)return null;let Q=Z.payload;if(!Q||typeof Q!=="object")return null;let J=Q.media;if(!J||typeof J!=="object")return console.warn("[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech"),null;if(G4(J.version))return console.warn(`[spoken-audio] card's media declares version ${String(J.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`),null;if(J.kind!==void 0&&J.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${J.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let Y=B4(J.sources);if(Y.length===0)return console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null;return{sources:Y,fragment:j4(Q.fragment),label:W4(J.label)}}var V4="[data-pie-shell-root]";var b8=(Z)=>Z?S0(Z,V4):null;var T0="en-US",h5=(Z,Q)=>{let J=!Z?null:Z.nodeType===1?Z:g(Z);while(J){let Y=J.getAttribute("lang")?.trim();if(Y)return Y;if(Q&&J===Q)return;J=g(J)}return},m5=(Z,Q={})=>{let J=Q.boundary!==void 0?Q.boundary:b8(Z);return(J?h5(Z,J):void 0)||Q.contentLanguage?.trim()||void 0},E8=(Z,Q={})=>m5(Z,Q)??T0;var T=(Z)=>Z.trim().replace(/\s+/g," "),x8=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,x0=(Z)=>{if(Z.hidden)return!0;if(Z.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Z.getAttribute("aria-hidden")==="true")return!0;if(Z.hasAttribute("inert"))return!0;let Q=Z.classList;if(Q?.contains("sr-only")||Q?.contains("pie-sr-only")||Q?.contains("visually-hidden"))return!0;if(typeof window<"u"){let J=window.getComputedStyle(Z);if(J.display==="none"||J.visibility==="hidden")return!0;let Y=Number.parseFloat(J.width||"0"),X=Number.parseFloat(J.height||"0"),G=Number.isFinite(Y)&&Number.isFinite(X)&&Y<=1&&X<=1,j=J.clipPath.includes("inset(50%")||J.clipPath.includes("inset(100%")||J.clip.includes("rect(0px, 0px, 0px, 0px)")||J.clip.includes("rect(0 0 0 0)");if((J.position==="absolute"||J.position==="fixed")&&G&&(J.overflow==="hidden"||j))return!0;if(J.opacity==="0"&&G)return!0}return!1},lZ=(Z,Q)=>{let J=Z.nodeType===1?Z:p(Z);while(J){if(x0(J))return!0;if(Q&&J===Q)break;J=p(J)}return!1},S8="data-tts-suppress",k8=new Set(["computer-read-aloud","all"]),y8=new Set([...k8,"screen-reader"]),T8=new Set,q4=(Z)=>{let Q=Z.getAttribute?.(S8);if(Q===null||Q===void 0)return!1;let J=Q.trim().toLowerCase();if(k8.has(J))return!0;if(y8.has(J))return!1;if(!T8.has(J))T8.add(J),console.warn(`[tts] ${S8}="${Q}" is not one of ${Array.from(y8).join(", ")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`);return!0},k0=(Z,Q)=>{let J=Z.nodeType===1?Z:p(Z);while(J){if(q4(J))return!0;if(Q&&J===Q)break;J=p(J)}return!1},UZ=(Z,Q)=>lZ(Z,Q)||k0(Z),u5=(Z,Q)=>{if(typeof Z.intersectsNode!=="function")return{text:Z.toString(),filtered:!1};let J=[],Y=!1;for(let X of RZ(Q))if(YZ(Z,X))if(UZ(X,Q))Y=!0;else J.push(p5(X,Z));return{text:J.join(""),filtered:Y}},p5=(Z,Q)=>{let J=Z.textContent||"",Y=Z===Q.startContainer?Q.startOffset:0,X=Z===Q.endContainer?Q.endOffset:J.length;return J.slice(Y,X)},F0=(Z,Q,J)=>{let Y=null,X=null;for(let G of RZ(Q)){if(UZ(G,J))continue;let j=G.textContent||"",B=j.search(/\S/);if(B===-1)continue;Y??={node:G,offset:B},X={node:G,offset:j.trimEnd().length-1}}if(!Y||!X)return YZ(Z,Q);return q0(Z,Y.node,Y.offset)&&q0(Z,X.node,X.offset)},g5=(Z,Q,J)=>{if(!Z||!Q)return!1;if(/\s/.test(Z)||/\s/.test(Q))return!1;let Y=J?.boundarySpacingMode??"segmenterPreferred";if(Y==="none")return!1;if(Y==="segmenterPreferred")try{let j=globalThis.Intl?.Segmenter;if(typeof j==="function"){let B=new j(J?.locale,{granularity:"word"});if(Array.from(B.segment(`${Z}${Q}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Z),G=/[A-Za-z0-9]/.test(Q);return X&&G},EZ=(Z,Q)=>{let J=new Map;if(typeof document>"u")return{text:"",map:J};let Y=[],X=0,G=!0,j=!1,B=null,V=null;for(let U of RZ(Z))if(p(U)&&!UZ(U,Z)){let z=U.textContent||"",D=z.match(/\S/),L=D?D[0]:null;if(!G&&!j&&g5(V,L,Q)){if(Y.push(" "),B)J.set(X,B);X++,j=!0}for(let P=0;P<z.length;P++){let A=z[P],N=/\s/.test(A);if(G){if(!N)G=!1,Y.push(A),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++,j=!1,V=A}else if(N){if(!j)Y.push(" "),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++;j=!0}else Y.push(A),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++,j=!1,V=A}}let K=Y.join("").trimEnd();while(J.has(K.length))J.delete(K.length);return{text:K,map:J}};var K4=/^\s*<speak[\s/>]/i,I0=(Z)=>K4.test(Z),U4=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),f8=new Set(["audio","phoneme"]),v8=(Z)=>Z.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),f0=(Z,Q,J)=>{for(let Y=0;Y<Q.length;Y++)Z.push({char:Q[Y],rawOffset:J===null?null:J+Y})},$4=(Z,Q,J)=>{let Y=Q.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!Y)return 0;return f0(Z,v8(Y[0]),J),Y[0].length},I8=(Z)=>{Z.push({char:" ",rawOffset:null})},F4=(Z)=>{let Q=new Map,J=[],Y=!0;for(let X of Z){if(/\s/.test(X.char)){if(!Y&&J.length>0){if(J.push(" "),X.rawOffset!==null)Q.set(X.rawOffset,J.length-1)}Y=!0;continue}if(J.push(X.char),X.rawOffset!==null)Q.set(X.rawOffset,J.length-1);Y=!1}while(J.length>0&&J[J.length-1]===" ")J.pop();for(let[X,G]of Q)if(G>=J.length)Q.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Q}},z4=(Z)=>{return Z.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},D4=(Z,Q)=>{let J=new RegExp(`${Q}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),Y=Z.match(J);return v8(Y?.[2]??Y?.[3]??"")||null},v0=(Z)=>{let Q=[],J=!1,Y=!1,X=0;while(X<Z.length){let j=Z[X];if(j!=="<"){if(j==="&"){let z=$4(Q,Z,X);if(z>0){X+=z;continue}}f0(Q,j,X),X++;continue}let B=Z.indexOf(">",X+1);if(B<0){f0(Q,j,X),X++;continue}Y=!0;let V=Z.slice(X,B+1),K=z4(V),U=/^<\s*\//.test(V),$=/\/\s*>$/.test(V);if(!U&&K==="sub"){let z=D4(V,"alias");if(!z){J=!0,X=B+1;continue}f0(Q,z,null);let D=Z.toLowerCase().indexOf("</sub>",B+1);X=D>=0?D+6:B+1;continue}if(!U&&K==="break"){I8(Q),X=B+1;continue}if(!U&&f8.has(K)){if(J=!0,$){X=B+1;continue}}if(K&&!U4.has(K)&&!f8.has(K)&&K!=="break"&&K!=="sub")J=!0;if(!U&&(K==="p"||K==="s"))I8(Q);X=B+1}let G=F4(Q);return{spokenText:T(G.text),rawToSpokenOffsetMap:G.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:Y}};var A4=x8(),H4=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),_4=(Z)=>{let Q=Z.toLowerCase();return H4.get(Q)||Q},l5=(Z)=>{let Q=[];for(let J of Z.matchAll(A4)){let Y=J[0],X=J.index??0;Q.push({text:Y,normalized:_4(Y),start:X,end:X+Y.length})}return Q},O4=(Z)=>l5(Z).map((Q,J)=>({...Q,id:`speech-token-${J}`,sourceStart:Q.start,sourceEnd:Q.end,coordinateSystem:"normalized-speech"})),SZ=(Z)=>{let Q=v0(Z.speechText);return{speechText:Z.speechText,spokenText:Q.spokenText,tokens:O4(Q.spokenText),rawToSpokenOffsetMap:Q.rawToSpokenOffsetMap,boundaryOffsetSpace:Q.unsupportedSemantic?"unsupported":Q.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Q.unsupportedSemantic,hasMarkup:Q.hasMarkup}},i5=(Z)=>Boolean(Z&&/^<[^>]+>$/.test(Z.trim())),iZ=(Z)=>{if(!Z||i5(Z))return null;return SZ({speechText:Z}).tokens[0]?.normalized??null},L4=(Z,Q)=>Z.find((J)=>J.start<=Q&&Q<J.end)||null,M4=(Z,Q)=>{let J=Z.rawToSpokenOffsetMap.get(Q);if(J!==void 0)return J;for(let Y=Q;Y<Z.speechText.length;Y++){let X=Z.rawToSpokenOffsetMap.get(Y);if(X!==void 0)return X;if(Z.speechText[Y]===">")break}return null},c5=(Z,Q,J)=>{if(Q===null)return null;let Y=L4(Z.tokens,Q);if(!Y)return null;return{token:Y,start:Q,length:Math.max(1,Math.min(J,Y.end-Q)),confidence:0.75}},d5=(Z,Q)=>Boolean(Z&&Q&&Z.token.normalized===Q),s5=(Z)=>{if(Z.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Z.position)||i5(Z.boundaryWord))return null;let Q=Math.max(1,Number.isFinite(Z.length)?Z.length:1),J=iZ(Z.boundaryWord),Y=c5(Z.tokenization,M4(Z.tokenization,Z.position),Q),X=c5(Z.tokenization,Z.position>=0&&Z.position<Z.tokenization.spokenText.length?Z.position:null,Q);if(d5(Y,J))return{...Y,confidence:1};if(d5(X,J))return{...X,confidence:1};if(J)return null;return Z.tokenization.boundaryOffsetSpace==="raw-ssml"?Y||X:X||Y},h8=(Z)=>{if(Z.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Z.position)||i5(Z.boundaryWord))return null;let Q=Math.max(1,Number.isFinite(Z.length)?Z.length:1),J=iZ(Z.boundaryWord),Y=c5(Z.tokenization,Z.position>=0&&Z.position<Z.tokenization.spokenText.length?Z.position:null,Q);if(d5(Y,J))return{...Y,confidence:1};if(J)return null;return Y};var n5=10,P4=0.12,N4=[{phrase:["plus","or","minus"],visible:"±",score:8},{phrase:["square","root"],visible:"√",score:8},{phrase:["divided","by"],visible:"/",score:7},{phrase:["all","over"],visible:"/",score:7},{phrase:["equals"],visible:"=",score:7},{phrase:["equal"],visible:"=",score:7},{phrase:["times"],visible:"⁢",score:7},{phrase:["multiplied","by"],visible:"⁢",score:7},{phrase:["over"],visible:"/",score:6},{phrase:["squared"],visible:"²",score:6},{phrase:["squared"],visible:"2",score:4},{phrase:["negative"],visible:"-",score:5},{phrase:["minus"],visible:"-",score:5},{phrase:["plus"],visible:"+",score:5}],w4=(Z,Q)=>{let J=[];for(let Y=0;Y<Z.length;Y++){for(let X=0;X<Q.length;X++)if(Z[Y].normalized===Q[X].normalized)J.push({spokenStartToken:Y,spokenEndToken:Y+1,visibleToken:X,score:n5});for(let X of N4){let G=Z.slice(Y,Y+X.phrase.length);if(G.length!==X.phrase.length)continue;if(!G.every((j,B)=>j.normalized===X.phrase[B]))continue;for(let j=0;j<Q.length;j++){if(Q[j].text!==X.visible)continue;J.push({spokenStartToken:Y,spokenEndToken:Y+X.phrase.length,visibleToken:j,score:X.score})}}}return J},R4=(Z,Q)=>{let J=w4(Z,Q).sort((V,K)=>Z[V.spokenStartToken].start-Z[K.spokenStartToken].start||Q[V.visibleToken].start-Q[K.visibleToken].start),Y=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let V=0;V<J.length;V++){let K=J[V];Y[V]=K.score;for(let U=0;U<V;U++){let $=J[U];if($.spokenEndToken<=K.spokenStartToken&&$.visibleToken<K.visibleToken){let z=K.spokenStartToken-$.spokenEndToken,D=K.visibleToken-$.visibleToken-1,L=Math.max(0,Math.abs(z-D)-2),P=Y[U]+K.score-L;if(P>Y[V])Y[V]=P,X[V]=U}}}let G=-1;for(let V=0;V<Y.length;V++)if(G<0||Y[V]>Y[G])G=V;if(G<0)return[];let j=[],B=G;while(B>=0)j.unshift(J[B]),B=X[B];return j.map((V)=>{let K=Z[V.spokenStartToken],U=Z[V.spokenEndToken-1],$=Q[V.visibleToken];return{spokenStart:K.start,spokenEnd:U.end,visibleStart:$.start,visibleEnd:$.end,score:V.score}})},C4=(Z,Q,J)=>{if(Z.length===0)return 0;let Y=Z.length/Math.max(1,Math.min(Q.length,J.length)),X=Z.reduce((G,j)=>G+j.score,0)/Z.length/n5;return Math.min(1,Y*X)},h0=(Z)=>{let Q=SZ({speechText:Z.speechText}),J=T(Z.visibleText),Y=Q.tokens,X=l5(J),G=Q.unsupportedSemantic?[]:R4(Y,X),j=C4(G,Y,X),B=Q.spokenText===J&&Q.spokenText.length>0,V=G.length===1&&G[0].score===n5&&Y.length<=2&&X.length<=2,K=(G.length>=2||V)&&j>=P4,U=Q.unsupportedSemantic?"region-fallback":B?"exact-word":K?"anchor-span":"region-fallback";return{speech:Q,visibleText:J,playbackMode:U,anchors:G,confidence:j}},m8=(Z,Q)=>{if(Z.playbackMode==="region-fallback")return null;let J=Z.anchors.find((G)=>G.spokenStart<=Q&&Q<G.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let Y=null,X=null;for(let G of Z.anchors){if(G.spokenEnd<=Q){Y=G;continue}if(G.spokenStart>Q){X=G;break}}if(Y&&X)return{start:Math.min(Y.visibleStart,X.visibleStart),end:Math.max(Y.visibleEnd,X.visibleEnd)};return null};var b4=new Map([["+",["plus"]],["-",["minus","negative"]],["−",["minus","negative"]],["×",["times","multiplied by"]],["÷",["divided by"]],["=",["equals","equal to"]],["≠",["is not equal to","not equal to"]],["≈",["approximately equals"]],["≤",["less than or equal to"]],["≥",["greater than or equal to"]],["<",["less than"]],[">",["greater than"]],["∠",["angle"]],["△",["triangle"]],["□",["box"]],["○",["circle"]],["°",["degrees","degree"]],["%",["percent"]],["'",["prime"]],["′",["prime"]],["•",["times"]],["·",["times"]],["⁢",["times","multiplied by"]]]),E4=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),u8=new Map([["2",["squared"]],["3",["cubed"]]]),S4=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),y4=(Z)=>Z.replace(/\s+/g," ").trim(),yZ=(Z)=>(Z.localName||Z.tagName||"").toLowerCase(),T4=(Z)=>Z.nodeType===Node.ELEMENT_NODE,sZ=(Z)=>Array.from(Z.childNodes).filter(T4),r5=(Z)=>y4(Z.textContent||""),GZ=(Z,Q)=>({type:"element-range",quality:Q,element:Z}),x4=(Z)=>{switch(Z){case"mi":return"identifier";case"mn":return"number";case"mo":return"operator";case"mtext":case"ms":return"text";case"mspace":return"space";default:return"unknown"}},k4=(Z,Q)=>{if(Q==="operator"){if(Z==="−")return"-";return Z}return Z.toLowerCase()},f4=(Z,Q,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return u8.get(Z)??[];if(Z==="|")return["absolute value"];if(Q==="operator")return b4.get(Z)||[];return[]},TZ=(Z)=>{let Q=Z.normalized??k4(Z.text,Z.kind||"unknown");return{id:`math-token-${Z.state.nextId++}`,kind:Z.kind,role:Z.role,text:Z.text,normalized:Q,spokenAliases:f4(Z.text,Z.kind,Z.role),sourceElement:Z.sourceElement,path:Z.path,target:Z.target||GZ(Z.sourceElement,"element-range"),optional:Z.optional}},xZ=(Z,Q,J="tokens")=>{Z[J].push(Q)},p8=(Z,Q,J)=>{sZ(Z).forEach((Y,X)=>jZ(Y,Q,`${J}/${yZ(Y)}[${X}]`))},I4=(Z,Q,J)=>{let Y=sZ(Z);if(Y[0])jZ(Y[0],Q,`${J}/numerator`);if(xZ(Q,TZ({state:Q,kind:"structure",role:"fraction",text:"/",sourceElement:Z,path:J,target:GZ(Z,"element-range")})),Y[1])jZ(Y[1],Q,`${J}/denominator`)},v4=(Z,Q,J)=>{let Y=Z.getAttribute("open")||"(",X=Z.getAttribute("close")||")";xZ(Q,TZ({state:Q,kind:"operator",role:Y==="|"?"absolute-value-fence":"open-fence",text:Y,sourceElement:Z,path:`${J}/open`,target:GZ(Z,"element-range")})),p8(Z,Q,J),xZ(Q,TZ({state:Q,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Z,path:`${J}/close`,target:GZ(Z,"element-range")}))},h4=(Z,Q,J)=>{let Y=sZ(Z);if(Y[0])jZ(Y[0],Q,`${J}/base`);let X=Y[1];if(!X)return;let G=r5(X);if(u8.has(G)){xZ(Q,TZ({state:Q,kind:"structure",role:"superscript",text:G,normalized:G,sourceElement:X,path:`${J}/exponent`,target:GZ(Z,"element-range")}));return}jZ(X,Q,`${J}/exponent`)},m4=(Z,Q,J,Y)=>{xZ(Q,TZ({state:Q,kind:"structure",role:Y,text:r5(Z)||Y,normalized:`\x00${Y}`,sourceElement:Z,path:J,target:GZ(Z,"element-range")}))},u4=(Z,Q,J)=>{let Y=0;for(let X of sZ(Z)){if(yZ(X)==="mtr"||yZ(X)==="mlabeledtr")Y++,xZ(Q,TZ({state:Q,kind:"layout",role:"table-row",text:`row-${Y}`,normalized:`row-${Y}`,sourceElement:X,path:`${J}/row[${Y}]`,target:GZ(X,"region-fallback")}),"layoutTargets");jZ(X,Q,`${J}/${yZ(X)}[${Y}]`)}},p4=(Z,Q,J)=>{let Y=r5(Z);if(!Y)return;let X=x4(yZ(Z)),G=X==="operator"?E4.get(Y):void 0,j=G??(X==="operator"&&(Y==="("||Y===")")?"grouping-fence":X);xZ(Q,TZ({state:Q,kind:X,role:j,text:Y,sourceElement:Z,path:J,target:G&&Z.parentElement?GZ(Z.parentElement,"region-fallback"):void 0,optional:Boolean(G)||j==="grouping-fence"}))},jZ=(Z,Q,J)=>{let Y=yZ(Z);switch(Y){case"annotation":case"annotation-xml":return;case"semantics":{let X=sZ(Z).find((G)=>{let j=yZ(G);return j!=="annotation"&&j!=="annotation-xml"});if(X)jZ(X,Q,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":p4(Z,Q,J);return;case"mfrac":I4(Z,Q,J);return;case"msup":h4(Z,Q,J);return;case"mfenced":v4(Z,Q,J);return;case"mtable":u4(Z,Q,J);return;case"mphantom":return;case"maction":{let X=sZ(Z)[0];if(X)jZ(X,Q,`${J}/action`);return}default:{let X=S4.get(Y);if(X){m4(Z,Q,J,X);return}p8(Z,Q,J)}}},g8=(Z)=>{let Q={tokens:[],layoutTargets:[],nextId:0};return jZ(Z,Q,"/math"),{tokens:Q.tokens,layoutTargets:Q.layoutTargets,expressionTarget:GZ(Z,"region-fallback")}};var c8=(Z)=>{if(!Z.boundary)return null;return Z.alignment.segments.find((J)=>J.speechTokenIds.includes(Z.boundary.token.id))?.target||null};var g4=(Z)=>{let Q=[],J=new Set,Y=(X)=>{let G=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(G.length===0)return;let j=G.join(" ");if(J.has(j))return;J.add(j),Q.push(G)};Y(Z.normalized);for(let X of Z.spokenAliases)Y(X);return Q},d8=(Z,Q,J)=>{let Y=0;for(let X of J){if(X.length<=Y)continue;let G=!0;for(let j=0;j<X.length;j++){let B=Z[Q+j];if(!B||B.normalized.toLowerCase()!==X[j]){G=!1;break}}if(G)Y=X.length}return Y},c4=(Z,Q)=>{let J=[],Y=0;for(let X of Q){let G=g4(X);if(X.optional){let j=d8(Z,Y,G);if(j>0)J.push({speechTokens:Z.slice(Y,Y+j),math:X}),Y+=j;continue}while(Y<Z.length){let j=d8(Z,Y,G);if(j>0){J.push({speechTokens:Z.slice(Y,Y+j),math:X}),Y+=j;break}Y++}}return J},d4=(Z,Q,J)=>{let Y=J.filter((j)=>!j.optional).length,X=Z.filter((j)=>!j.math.optional).length,G=Z.reduce((j,B)=>j+B.speechTokens.length,0);return Y>0&&X===Y&&G===Q.length},l4=(Z)=>Z.map(({speechTokens:Q,math:J})=>({speechTokenIds:Q.map((Y)=>Y.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),l8=(Z)=>{let Q=Z.minExactWordConfidence??0.95,J=c4(Z.speech.tokens,Z.math.tokens),Y=d4(J,Z.speech.tokens,Z.math.tokens)?1:0;return{segments:Y>=Q?l4(J):[],confidence:Y,fallbackTarget:Z.math.expressionTarget}};var nZ=(Z)=>{let Q=SZ({speechText:Z.speechText}),J=g8(Z.mathElement);return{speech:Q,math:J,result:l8({speech:Q,math:J})}};var i8=(Z,Q)=>{let J=h8({tokenization:Z.speech,position:Q.position,length:Q.length,boundaryWord:Q.boundaryWord});return c8({alignment:Z.result,boundary:J})},s8=(Z,Q)=>{let J=iZ(Q.boundaryWord);if(!J)return null;let Y=Z.math.tokens.filter((X)=>X.normalized.toLowerCase()===J||X.spokenAliases.some((G)=>G.toLowerCase()===J));return Y.length===1?Y[0].target:null};var i4=new Set(["math","maction","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","none","semantics","annotation","annotation-xml"]),s4=new Set(["accent","accentunder","align","bevelled","class","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","encoding","fence","height","href","id","largeop","length","linethickness","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","width","xmlns","xml:lang"]),n8=(Z)=>Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),n4=(Z)=>n8(Z).replace(/"/g,"&quot;"),r4=(Z,Q)=>{let J=Z.toLowerCase(),Y=Q.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!s4.has(J))return!0;if(Y.includes("javascript:"))return!0;if(Y.includes("data:text/html"))return!0;return!1},o4=(Z)=>{let Q=Z.localName.toLowerCase();if(!i4.has(Q))return!1;let J=Z.namespaceURI;return!J||J==="http://www.w3.org/1998/Math/MathML"||J==="http://www.w3.org/1999/xhtml"},r8=(Z)=>{if(Z.nodeType===Node.TEXT_NODE)return n8(Z.textContent||"");if(Z.nodeType===Node.COMMENT_NODE)return"";if(Z.nodeType!==Node.ELEMENT_NODE)return null;let Q=Z;if(!o4(Q))return null;let J=Q.localName.toLowerCase(),Y=[];for(let j of Array.from(Q.attributes)){let B=j.name.toLowerCase();if(r4(B,j.value))continue;if(B==="xmlns"&&j.value!=="http://www.w3.org/1998/Math/MathML")return null;Y.push(`${B}="${n4(j.value)}"`)}if(J==="math"&&!Y.some((j)=>j.startsWith("xmlns=")))Y.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let j of Array.from(Q.childNodes)){let B=r8(j);if(B===null)return null;X.push(B)}let G=Y.length>0?` ${Y.join(" ")}`:"";return`<${J}${G}>${X.join("")}</${J}>`},a4=(Z)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Z,"application/xml");return null},rZ=(Z)=>{let Q=String(Z||"").trim();if(!Q)return null;let J=a4(Q);if(!J)return null;if(J.getElementsByTagName("parsererror").length>0)return null;let Y=J.documentElement;if(!Y||Y.localName.toLowerCase()!=="math")return null;return r8(Y)};var a8=(Z)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Z}),o5=(Z)=>Z.classList?.contains("MathJax")||Z.tagName?.toLowerCase()==="mjx-container",t8=(Z)=>Z.tagName?.toLowerCase()==="mjx-assistive-mml",a5=(Z)=>{let Q=Z.tagName?.toLowerCase();return Q==="annotation"||Q==="annotation-xml"},t4=(Z)=>{let Q=Z.getAttribute("data-mathml");return Q&&Q.trim()?Q:null},e4=(Z)=>{return CZ(Z,"mjx-assistive-mml math")?.outerHTML||null},Z3=(Z)=>{if(Z.tagName.toLowerCase()==="math")return rZ(Z.outerHTML);let Q=t4(Z);if(Q){let J=rZ(Q);if(J)return J}if(o5(Z)){let J=e4(Z);if(J){let Y=rZ(J);if(Y)return Y}}return null},Q3=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),J3=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),Y3=(Z,Q)=>{let J=p(Z);while(J&&J!==Q){let Y=(J.getAttribute("role")||"").toLowerCase(),X=J.tagName.toUpperCase();if(Q3.has(X)||J3.has(Y))return J;J=p(J)}return Q},X3=(Z)=>Boolean(typeof Z.querySelector==="function"&&CZ(Z,"math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Z.tagName?.toLowerCase()==="math"||Z.hasAttribute?.("data-mathml")||o5(Z),kZ=(Z,Q,J)=>{if(/[.,;:!?]/.test(Q)&&Z.chars.length>0&&Z.chars[Z.chars.length-1]===" ")Z.chars.pop(),Z.position--,Z.map.delete(Z.position);if(Z.chars.push(Q),J)Z.map.set(Z.position,J),Z.lastMapped=J;else if(Z.lastMapped)Z.map.set(Z.position,Z.lastMapped);Z.position++},e8=(Z,Q)=>{if(Z.inLeadingWhitespace||Z.lastCharWasWhitespace||Z.chars.length===0)return!1;let J=Z.chars[Z.chars.length-1];return g5(J,Q,Z.options)},Z9=(Z,Q,J=0,Y=(Q.textContent||"").length)=>{let X=Q.textContent||"",G=!1;for(let j=J;j<Y;j++){let B=X[j],V=/\s/.test(B);if(Z.inLeadingWhitespace){if(!V)Z.inLeadingWhitespace=!1,kZ(Z,B,{node:Q,offset:j}),G=!0,Z.lastCharWasWhitespace=!1;continue}if(V){if(!Z.lastCharWasWhitespace)kZ(Z," ",{node:Q,offset:j});Z.lastCharWasWhitespace=!0;continue}if(!G&&e8(Z,B))kZ(Z," ",{node:Q,offset:j});kZ(Z,B,{node:Q,offset:j}),G=!0,Z.lastCharWasWhitespace=!1}},G3=(Z,Q)=>{for(let J=0;J<Q.text.length;J++){let Y=Q.text[J],X=/\s/.test(Y),G=Q.map.get(J),j=G?{node:G.node,offset:G.offset}:Z.lastMapped?{node:Z.lastMapped.node,offset:Z.lastMapped.offset}:null;if(Z.inLeadingWhitespace){if(X)continue;Z.inLeadingWhitespace=!1}if(X){if(!Z.lastCharWasWhitespace)kZ(Z," ",j);Z.lastCharWasWhitespace=!0;continue}if(J===0&&e8(Z,Y))kZ(Z," ",j);kZ(Z,Y,j),Z.lastCharWasWhitespace=!1}},j3=(Z)=>{if(typeof DOMParser>"u")return"";let Q=new DOMParser().parseFromString(Z,"application/xml");if(Q.getElementsByTagName("parsererror").length>0)return"";let J=[],Y=(X)=>{if(X.nodeType===3){let j=X.textContent||"";if(j.trim())J.push(j);return}if(X.nodeType!==1)return;let G=X;if(a5(G))return;for(let j of Array.from(G.childNodes))Y(j)};return Y(Q.documentElement),T(J.join(" "))},B3=(Z,Q)=>{let J=new Map,Y=o5(Z)?CZ(Z,"mjx-assistive-mml math"):null;if(!Y)return J;let X=[],G=(B)=>{if(B.nodeType===3){let V=B.textContent||"";for(let K=0;K<V.length;K++)if(!/\s/.test(V[K]))X.push({node:B,offset:K});return}if(B.nodeType!==1||a5(B))return;for(let V of KZ(B))G(V)};G(Y);let j=0;for(let B=0;B<Q.length;B++){if(/\s/.test(Q[B]))continue;let V=X[j];if(V?.node.textContent?.[V.offset]!==Q[B])return new Map;J.set(B,V),j++}return j===X.length?J:new Map},W3=(Z,Q,J)=>{let Y=a8(J),X=(B)=>{if(UZ(B,Z))return;if(B.nodeType===3){Z9(Y,B);return}if(B.nodeType!==1)return;let V=B;if(t8(V)||a5(V))return;for(let K of KZ(V))X(K)};X(Z),Q9(Y);let G=T(Y.chars.join(""));if(G)return{text:G,map:Y.map};let j=j3(Q);if(!j)return EZ(Z,J);return{text:j,map:B3(Z,j)}},Q9=(Z)=>{while(Z.chars.length>0&&/\s/.test(Z.chars[Z.chars.length-1]))Z.chars.pop(),Z.position--,Z.map.delete(Z.position)},o8=(Z,Q,J)=>{let Y=a8(Q),X=[],G=0,j,B=!1,V=()=>{let $=T(Y.chars.slice(G,Y.chars.length).join(""));if($)X.push({type:"text",text:$,sourceElement:j});G=Y.chars.length,j=void 0},K=($)=>{if(UZ($,Z))return;if(J&&!YZ(J,$))return;if($.nodeType===3){let L=Y3($,Z);if(j&&L!==j)V();j=L;let P=$;Z9(Y,P,J?.startContainer===P?J.startOffset:void 0,J?.endContainer===P?J.endOffset:void 0);return}if($.nodeType!==1)return;let z=$;if(t8(z))return;let D=Z3(z);if(D&&(!J||F0(J,z,Z))){V();let L=W3(z,D,Q);G3(Y,L);let P=T(L.text);X.push({type:"math",mathml:D,fallbackText:P,sourceElement:z}),G=Y.chars.length,B=!0;return}for(let L of KZ(z))K(L)};for(let $ of KZ(Z))K($);return Q9(Y),V(),{visibleText:Y.chars.join(""),map:Y.map,chunks:X,containsMathMarkup:B}},$Z=(Z,Q,J)=>{if(J)return o8(Z,Q,J);if(!X3(Z)){let{text:Y,map:X}=EZ(Z,Q);return{visibleText:Y,map:X,chunks:Y?[{type:"text",text:Y}]:[],containsMathMarkup:!1}}return o8(Z,Q)};import{createPieLogger as q3,isTtsDebugEnabled as K3}from"@pie-players/pie-players-shared/pie";var m0=q3("tts-math-speech",K3),J9=Promise.resolve(),U3=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",$3=(Z)=>{let Q=null,J=!1;return(Y)=>{if(!Q){j9(Y);let X=Z();Q=X,X.catch((G)=>{if(Q===X)Q=null;if(J){m0.debug("speech-rule-engine failed to load again",G);return}J=!0,m0.warn("speech-rule-engine failed to load; math reads as its visible text until a later read loads it.",G)})}return Q}},F3=$3(()=>import("./chunks/sre-engine-bj997w4b.js").then(({default:Z})=>{if(!Z||typeof Z.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return Z})),t5=(Z)=>{let Q=null;return()=>{return Q??=F3(BZ(Z)?.engineOptions),Q}},z3=(Z)=>Z==="en"?"clearspeak":"mathspeak",Y9=(Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z),X9=(Z)=>typeof Z==="string"&&Z.trim()?Z.trim():void 0,BZ=(Z)=>{if(!Y9(Z))return;let Q=X9(Z.domain),J=X9(Z.style),Y=Y9(Z.engineOptions)?Z.engineOptions:void 0;if(!Q&&!J&&!Y)return;return{...Q?{domain:Q}:{},...J?{style:J}:{},...Y?{engineOptions:Y}:{}}},D3=async(Z,Q,J,Y)=>{let X=U3(Q),G=BZ(Y),j=G?.engineOptions||{};await Z.setupEngine?.({...G9(j),...j,locale:X,domain:G?.domain||z3(X),style:G?.style||"default",modality:"speech",markup:J}),await Z.engineReady?.()},A3=async(Z)=>{let Q=J9.then(Z,Z);return J9=Q.then(()=>{return},()=>{return}),Q},B9=async(Z,Q,J,Y,X)=>A3(async()=>{return await D3(Z,J,Y,X),Z.toSpeech(Q)}),H3=(Z)=>Z.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),_3=async(Z,Q,J,Y)=>{try{let X=H3(await B9(Z,Q,J,"ssml",Y));return X.includes("<speak")?X:null}catch(X){return m0.debug("math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},oZ=async(Z,Q={})=>{if(!Z.some((K)=>K.type==="math"))return{speechText:T(Z.map((K)=>K.type==="text"?K.text:K.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,Y=!1,X=!1,G=Q.loadSre||t5(Q.mathSpeech),j=[];for(let K of Z){if(K.type==="text"){j.push(K.text);continue}try{if(!J)J=await G();let U=T(await B9(J,K.mathml,Q.language,"none",Q.mathSpeech));if(U){j.push(U),Y=!0;continue}X=!0,j.push(K.fallbackText)}catch(U){X=!0,m0.debug("math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),j.push(K.fallbackText)}}let B=T(j.join(" ")),V;if(Q.produceSsml&&J&&Y&&Z.length===1&&Z[0].type==="math")V=await _3(J,Z[0].mathml,Q.language,Q.mathSpeech)??void 0;return{speechText:B,usedMathSpeech:Y,usedFallback:X,ssml:V}};var O3=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",L3="sre-v1",M3=256,e5=(Z)=>{if(Array.isArray(Z))return`array:[${Z.map(e5).join(",")}]`;if(Z&&typeof Z==="object")return`object:{${Object.entries(Z).sort(([Q],[J])=>Q.localeCompare(J)).map(([Q,J])=>`${JSON.stringify(Q)}:${e5(J)}`).join(",")}}`;if(Z===null)return"null:null";if(typeof Z>"u")return"undefined:";if(typeof Z==="function")return`function:${Z.name||"anonymous"}`;if(typeof Z==="symbol")return`symbol:${String(Z)}`;if(typeof Z==="bigint")return`bigint:${Z.toString()}`;if(typeof Z==="number")return Number.isFinite(Z)?`number:${Z}`:`number:${String(Z)}`;return`${typeof Z}:${JSON.stringify(Z)}`},W9=(Z,Q,J,Y)=>`${L3}\x00${O3(Z)}\x00${Q?"ssml":"plain"}\x00${e5(J??null)}\x00${Y}`,Z7=(Z={})=>{let Q=Math.max(1,Z.maxEntries??M3),J=Z.resolve??((G,j)=>oZ([G],j)),Y=new Map,X=(G,j)=>{Y.delete(G),Y.set(G,j);while(Y.size>Q){let B=Y.keys().next().value;if(B!==void 0)Y.delete(B)}};return async(G,j)=>{let B=BZ(j.mathSpeech),V=j.produceSsml===!0,K=W9(j.language,V,B,G.mathml),U=Y.get(K);if(U)return Y.delete(K),Y.set(K,U),U;let $=await J(G,{...j,mathSpeech:B});if($.usedFallback)return $;if(V&&$.ssml&&Q>1)X(W9(j.language,!1,B,G.mathml),{speechText:$.speechText,usedMathSpeech:$.usedMathSpeech,usedFallback:$.usedFallback});return X(K,$),$}};var V9=(Z,Q)=>{let J=iZ(Q.word);if(Z.id!==Q.chunkId)return{chunkId:Q.chunkId,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(Q.providerOffsetSpace==="unknown"||Z.offsetSpace==="unsupported")return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let Y=s5({tokenization:Z.catalogAlignment?.speech??SZ({speechText:Z.speechText}),position:Q.position,length:Q.length,boundaryWord:Q.word});if(!Y)return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:Y.start,chunkSpokenEnd:Y.start+Y.length,confidence:Y.confidence,reason:Z.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var fZ=(Z)=>{if(Z.semanticTarget)return{activeTarget:Z.semanticTarget,regionTarget:Z.regionTarget,quality:Z.semanticTarget.quality==="exact-word"?"exact-word":Z.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Z.confidence,reason:Z.reason};if(Z.expressionTarget)return{activeTarget:Z.expressionTarget,regionTarget:Z.regionTarget,quality:"expression",confidence:Z.confidence,reason:Z.reason};return{activeTarget:null,regionTarget:Z.regionTarget,quality:"region",confidence:Z.confidence,reason:Z.reason}};var K9=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),Q7="mi,mn,mo,mtext",U9="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",$9=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),F9=(Z)=>{if(Z.type==="text-range")return Z.node.parentElement;return Z.element},u0=(Z)=>{let Q=Z;while(Q){if(Q.localName?.toLowerCase()==="mjx-container")return Q;Q=Q.parentElement}return null},q9=(Z)=>{if(!Z)return!1;if(u0(Z))return!1;return!lZ(Z)},z9=(Z)=>{let Q=Z.getBoundingClientRect?.();return Boolean(Q&&Q.width>0&&Q.height>0)},J7=(Z)=>{let Q=Z;while(Q){if(Q.localName?.toLowerCase()==="math")return Q;Q=Q.parentElement}return null},D9=(Z,Q)=>{if(Z.length===0)return!1;if(Z.length!==Q.length)return!1;for(let J=0;J<Z.length;J+=1){let Y=K9.get(Z[J].localName.toLowerCase());if(!Y)return!1;if(Q[J].localName.toLowerCase()!==Y)return!1}return!0},P3=(Z,Q)=>{if(!Z)return null;if(!K9.has(Z.localName.toLowerCase()))return null;if(Q.querySelector($9))return null;let J=J7(Z),Y=Q.querySelector("mjx-math");if(!J||!Y)return null;let X=Array.from(J.querySelectorAll(Q7)),G=X.indexOf(Z);if(G<0)return null;let j=Array.from(Y.querySelectorAll(U9));if(!D9(X,j))return null;let B=j[G];if(!B||!z9(B))return null;return B},A9=(Z)=>{let Q=u0(Z);if(Q){if(Q.querySelector($9))return"expression";let X=J7(Z)??Z,G=Q.querySelector("mjx-math");if(!G)return"expression";let j=Array.from(X.querySelectorAll(Q7)),B=Array.from(G.querySelectorAll(U9));if(!D9(j,B))return"expression";return B.some((V)=>z9(V))?"token":"expression"}let J=J7(Z)??Z;return Array.from(J.querySelectorAll(Q7)).some((X)=>!lZ(X))?"token":"expression"},Y7=(Z)=>{let Q=F9(Z),J=u0(Q);if(J){let Y=P3(Q,J);if(Y)return{type:"element",quality:"semantic-token",element:Y};return{type:"element",quality:"expression",element:J}}if(Z.type==="text-range"){if(!q9(Z.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Z.node,startOffset:Z.startOffset,endOffset:Z.endOffset}}if(!q9(Z.element))return null;return{type:"element",quality:Z.quality==="region-fallback"?"expression":"semantic-token",element:Z.element}},H9=Y7,_9=()=>{let Z=new WeakMap;return(Q)=>{let J=F9(Q),Y=u0(J);if(!J||!Y)return Y7(Q);if(Z.has(J))return Z.get(J)??null;let X=Y7(Q);return Z.set(J,X),X}};var O9=(Z,Q,J,Y=Z.mathAlignments,X=H9)=>{if(Q.chunkSpokenStart===null||Q.chunkSpokenEnd===null)return null;let G=null;for(let j of Y){let B=i8(j.alignment,{position:Q.chunkSpokenStart,length:Math.max(1,Q.chunkSpokenEnd-Q.chunkSpokenStart),boundaryWord:J.word})||s8(j.alignment,{boundaryWord:J.word});if(!B)continue;let V=X(B);if(!V)continue;if(V.quality==="semantic-token")return V;G??=V}return G};var FZ=(Z)=>Z.node.getRootNode?.()??Z.node,L9=(Z,Q)=>{try{let J=document.createRange();return J.setStart(Z.node,Z.offset),J.setEnd(Q.node,Q.offset+1),J}catch{return null}},X7=(Z,Q,J)=>{if(!Z||typeof document>"u")return null;if(J<=Q)return null;let Y=Z.get(Q),X=Z.get(Math.max(Q,J-1));if(!Y)return null;if(!X)X=Y;if(FZ(X)!==FZ(Y)){let G=FZ(Y);X=Y;for(let j=Q+1;j<J;j++){let B=Z.get(j);if(B&&FZ(B)===G)X=B}}return L9(Y,X)},zZ=(Z,Q,J)=>{if(!Z||typeof document>"u"||J<=Q)return[];let Y=Z.get(Q);if(!Y)return[];let X=FZ(Y),G=!1;for(let U=Q+1;U<J&&!G;U++){let $=Z.get(U);if($&&FZ($)!==X)G=!0}if(!G){let U=X7(Z,Q,J);return U?[U]:[]}let j=[],B=null,V=null,K=()=>{if(B&&V){let U=L9(B,V);if(U)j.push(U)}B=null,V=null};for(let U=Q;U<J;U++){let $=Z.get(U);if(!$)continue;if(B&&FZ(B)!==FZ($))K();if(!B)B=$;V=$}return K(),j};var M9=(Z,Q)=>{if(!Z.catalogAlignment||Q.chunkSpokenStart===null)return null;let J=m8(Z.catalogAlignment,Q.chunkSpokenStart);if(!J)return null;let Y=zZ(Z.visibleMap,J.start,J.end);if(Y.length===0)return null;return{type:"range",quality:Z.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:Y[0],ranges:Y.length>1?Y:void 0}};var N3=(Z)=>{let Q=zZ(Z.visibleMap,0,Z.visibleText.length);return Q.length>1?Q:void 0},w3=(Z)=>Z.regionRange?{type:"range",quality:"region",range:Z.regionRange,ranges:N3(Z)}:Z.regionElement?{type:"element",quality:"region",element:Z.regionElement}:null,P9=(Z,Q=Z.chunk.mathAlignments)=>{if(Q.length!==1)return null;let J=Q[0]?.alignment.result.fallbackTarget;return J?Z.renderedMathTargetResolver(J):null},R3=(Z,Q)=>{if(!Z)return Q.mathAlignments;return Q.mathAlignments.filter(({element:J})=>{try{if(Z.type==="range")return(Z.ranges??[Z.range]).some((Y)=>YZ(Y,J));if(Z.type==="element")return ZZ(Z.element,J);return ZZ(g(Z.node),J)}catch{return!1}})},N9=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),G7=(Z)=>Z.length===1?Z[0].element:null,C3=(Z,Q)=>Q.length>0&&Q.every(({element:J})=>Z.mathCapabilityByElement.get(J)==="token"),w9=3,b3=(Z,Q,J)=>{if(!Q||Q.type!=="range")return!1;let{startContainer:Y,endContainer:X}=Q.range;if(Y===X&&Y.nodeType===w9)return!1;return J.some(({element:j})=>Z.mathCapabilityByElement.get(j)==="token"&&j.contains(Y)&&j.contains(X))},R9=(Z)=>Z?.type==="range"&&lZ(Z.range.startContainer),E3=(Z,Q)=>{if(!R9(Q))return null;let{startContainer:J,endContainer:Y,startOffset:X,endOffset:G}=Q.range;if(J!==Y||J.nodeType!==w9)return null;return Z.renderedMathTargetResolver({type:"text-range",quality:"exact-word",node:J,startOffset:X,endOffset:G})},S3=(Z,Q)=>({chunk:Z,regionTarget:w3(Z),renderedMathTargetResolver:_9(),mathCapabilityByElement:new Map(Z.mathAlignments.map(({element:J})=>[J,Q?A9(J):"expression"])),heldTokenByElement:new Map}),C9=(Z)=>{let Q=Z.mathTokenHighlighting!==!1,J=new Map(Z.chunks.map((Y)=>[Y.id,S3(Y,Q)]));return{chunks:Z.chunks,resolveInitial(Y){let X=J.get(Y);if(!X)return N9();let G=G7(X.chunk.mathAlignments),j=G?X.mathCapabilityByElement.get(G):null;if(j==="expression")return fZ({semanticTarget:null,expressionTarget:P9(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return fZ({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:j==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(Y){let X=J.get(Y.chunkId);if(!X)return N9();let{chunk:G}=X,j=V9(G,Y),B=M9(G,j),V=R3(B,G),K=!B||V.length>0?O9(G,j,Y,V,X.renderedMathTargetResolver):null,U=K?.quality==="semantic-token"?K:E3(X,B)??K,$=Q&&U&&U.quality!=="expression"?U:null,z=U&&U.quality==="expression"?U:null;if($){let D=G7(V);if(D)X.heldTokenByElement.set(D,$);return fZ({semanticTarget:$,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}if(B&&!R9(B)&&(Q?!b3(X,B,V):V.length===0))return fZ({semanticTarget:B,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason});if(C3(X,V)){let D=G7(V),L=D?X.heldTokenByElement.get(D)??null:null;return fZ({semanticTarget:L,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:L?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return fZ({semanticTarget:null,expressionTarget:z??P9(X,V),regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}}};var y3=(Z)=>{return Z.alignment?.speech.boundaryOffsetSpace??Z.mathAlignment?.speech.boundaryOffsetSpace??"plain-spoken-text"},T3=(Z)=>{if(Z.mathAlignments?.length)return Z.mathAlignments;if(Z.mathAlignment&&Z.sourceElement)return[{element:Z.sourceElement,alignment:Z.mathAlignment}];return[]},b9=(Z)=>{return(Z.chunks&&Z.chunks.length?Z.chunks:[{speechText:Z.speechText||"",visibleText:Z.visibleText||Z.speechText||"",sourceElement:Z.sourceElement||Z.contentRoot,regionElement:Z.regionElement||Z.sourceElement||Z.contentRoot,regionRange:Z.regionRange,visibleMap:Z.visibleMap}]).map((J,Y)=>({id:`tts-chunk-${Y}`,speechText:J.speechText,visibleText:J.visibleText,sourceElement:J.sourceElement,contentRoot:Z.contentRoot,regionElement:J.regionElement??J.sourceElement,regionRange:J.regionRange,visibleMap:J.visibleMap,catalogAlignment:J.alignment,mathAlignments:T3(J),offsetSpace:y3(J)}))};var x3=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),p0=(Z,Q)=>{let J=S0(Z,x3);if(J&&ZZ(Q,J))return J;return Z};var IZ=(Z,Q)=>{let J=Q?.useSentenceSegmenter===!1?void 0:globalThis.Intl?.Segmenter;if(typeof J==="function")try{let B=new J(Q?.locale,{granularity:"sentence"}),V=Array.from(B.segment(Z)).map((K)=>({text:K.segment,offset:K.index})).filter((K)=>K.text.trim().length>0);if(V.length>0)return V}catch{}let Y=/[^.!?]+(?:[.!?]+|$)/g,X=Z.match(Y)||[Z],G=[],j=0;for(let B of X){let V=Z.indexOf(B,j);if(V===-1)continue;G.push({text:B,offset:V}),j=V+B.length}return G.length>0?G:[{text:Z,offset:0}]},j7=(Z,Q,J)=>{let Y=Math.max(1,Math.floor(Q)),X=[],G=-1,j=-1,B=()=>{if(G>=0)X.push({text:Z.slice(G,j),offset:G});G=-1},V=(K,U)=>{if(G>=0&&U-G<=Y){j=U;return}B();let $=K;while(U-$>Y){let D=Z.slice($,$+Y+1).search(/\s\S*$/),L=D>0?$+D:$+Y;X.push({text:Z.slice($,L).trimEnd(),offset:$}),$=L;while($<U&&/\s/.test(Z[$]))$++}if($<U)G=$,j=U};for(let K of IZ(Z,J)){let U=K.text.search(/\S/);if(U===-1)continue;let $=K.offset+U;V($,K.offset+K.text.trimEnd().length)}return B(),X};var k3=(Z,Q)=>oZ([Z],Q),f3=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",I3=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),v3=new Set(["heading","listitem","option","radio"]),h3=(Z)=>{if(Z.type!=="text"||!Z.sourceElement)return!1;let Q=Z.sourceElement.tagName.toUpperCase(),J=(Z.sourceElement.getAttribute("role")||"").toLowerCase();return I3.has(Q)||v3.has(J)},E9=async(Z)=>{let Q=Z.resolveMathSpeech??k3,J=t5(Z.mathSpeech),{visibleText:Y}=Z,X=[],G=0,j=(V)=>{let K=T(V),U=Y.indexOf(K,G),$=U>=0?U:G,z=$+K.length;return G=z,{start:$,end:z}},B=[];for(let V=0;V<Z.chunks.length;V++){let K=Z.chunks[V];if(K.type==="text"){let L=h3(K)?[{text:K.text,offset:0}]:IZ(K.text,{locale:Z.language});for(let P of L){let A=T(P.text);if(!A)continue;let N=j(A);X.push({sourceChunkIndex:V,segment:{kind:"prose",spokenText:A,visibleText:A,visibleSpan:N}}),B.push(A)}continue}let U=j(K.fallbackText),$=await Q(K,{language:Z.language,produceSsml:Z.produceSsml,mathSpeech:Z.mathSpeech,loadSre:J}),z=!$.speechText,D=$.speechText||K.fallbackText;X.push({sourceChunkIndex:V,segment:{kind:"math",spokenText:D,mathml:K.mathml,fallbackText:K.fallbackText,visibleSpan:U,usedFallback:z,ssml:$.ssml}}),B.push(D)}return{segments:X,locale:f3(Z.language),visibleText:Y,plainSpeechText:T(B.join(" "))}};var m3=(Z,Q,J)=>{let Y=new Map;for(let X=Q;X<J;X++){let G=Z.get(X);if(G)Y.set(X-Q,G)}return Y},B7=async(Z)=>{let Q=$Z(Z.contentRoot,Z.textProcessingOptions,Z.range),J=await E9({chunks:Q.chunks,visibleText:Q.visibleText,language:Z.language,mathSpeech:Z.mathSpeech,produceSsml:Z.produceSsml,resolveMathSpeech:Z.resolveMathSpeech});return{plan:{items:J.segments.map(({segment:X,sourceChunkIndex:G})=>{let j=Q.chunks[G];if(X.kind==="prose"){let V=j?.type==="text"?j.sourceElement??Z.contentRoot:Z.contentRoot;return{segment:X,anchor:{sourceElement:V,regionElement:p0(V,Z.contentRoot),visibleMap:m3(Q.map,X.visibleSpan.start,X.visibleSpan.end)}}}let B=j?.type==="math"?j.sourceElement??null:null;return{segment:X,anchor:{sourceElement:B,regionElement:B}}}),locale:J.locale,visibleText:J.visibleText,plainSpeechText:J.plainSpeechText},containsMathMarkup:Q.containsMathMarkup,visibleText:Q.visibleText}};var u3=(Z,Q)=>{let J=h0({speechText:Z.spokenText,visibleText:Z.spokenText});return{speechText:Z.spokenText,visibleText:Z.visibleText,sourceElement:Q.sourceElement,regionElement:Q.regionElement,regionRange:X7(Q.visibleMap,0,Z.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Q.visibleMap}},S9=(Z,Q)=>{let J=Q.sourceElement;return{speechText:Z.spokenText,visibleText:Z.fallbackText,sourceElement:J,regionElement:Q.regionElement,speechMatchesVisibleText:Z.spokenText===Z.fallbackText,mathAlignment:J?nZ({mathElement:J,speechText:Z.spokenText}):void 0}},p3=(Z,Q,J)=>{let Y=Q.sourceElement;return{speechText:J,visibleText:Z.fallbackText,sourceElement:Y,regionElement:Q.regionElement,speechMatchesVisibleText:!1,mathAlignment:Y?nZ({mathElement:Y,speechText:J}):void 0,plainFallback:S9(Z,Q)}},W7=(Z,Q={})=>Z.items.map(({segment:J,anchor:Y})=>{if(J.kind==="prose")return u3(J,Y);if(Q.format==="ssml"&&J.ssml)return p3(J,Y,J.ssml);return S9(J,Y)});function g0(Z){let Q=Z instanceof Error?Z:Error(String(Z));return Q.code="tts-start-failed",Q}var t=d3("tts-service",v9),R;(function(Z){Z.IDLE="idle",Z.LOADING="loading",Z.PLAYING="playing",Z.PAUSED="paused",Z.ERROR="error"})(R||(R={}));var l3={baseMs:280,units:{minor:0.65,section:1,major:1.35},minMs:120,maxMs:900},y9=0.25,T9=4,vZ=(Z)=>typeof Z==="string"&&Z.trim()?Z.trim():void 0,x9=(Z,Q={})=>{if(!Z)return Q;return{locale:"locale"in Z?vZ(Z.locale):Q.locale,textNormalization:Z.textNormalization&&"locale"in Z.textNormalization?vZ(Z.textNormalization.locale):Q.textNormalization,segmenter:Z.segmenter&&"locale"in Z.segmenter?vZ(Z.segmenter.locale):Q.segmenter}},k9=(Z)=>("commonAncestorContainer"in Z),h9=(Z,Q)=>Z===Q||Z.startContainer===Q.startContainer&&Z.startOffset===Q.startOffset&&Z.endContainer===Q.endContainer&&Z.endOffset===Q.endOffset,i3=(Z,Q)=>{if(Z===Q)return!0;if(!Z||!Q||Z.type!==Q.type||Z.quality!==Q.quality)return!1;if(Z.type==="range"&&Q.type==="range")return h9(Z.range,Q.range);if(Z.type==="element"&&Q.type==="element")return Z.element===Q.element;if(Z.type==="text-range"&&Q.type==="text-range")return Z.node===Q.node&&Z.startOffset===Q.startOffset&&Z.endOffset===Q.endOffset;return!1},s3=(Z,Q)=>{for(let J=0;J<Math.min(Z.length,Q.length);J++)if(Z[J]!==Q[J])return{index:J,spokenChar:Z[J],normalizedChar:Q[J],spokenContext:Z.substring(Math.max(0,J-20),J+20),normalizedContext:Q.substring(Math.max(0,J-20),J+20)};return null},f9=(Z)=>{let Q=Number(Z.getAttribute("data-tts-break-ms"));return Number.isFinite(Q)&&Q>0?Q:null},n3=(Z)=>{if(typeof window>"u")return!1;let Q=window.getComputedStyle(Z).display;return Q==="block"||Q==="list-item"||Q.startsWith("table")||Q==="flex"||Q==="grid"},I9=(Z,Q,J)=>{let Y=Z.substring(Q,J);return{start:Q+(Y.match(/^\s*/)?.[0].length||0),end:J-(Y.match(/\s*$/)?.[0].length||0)}};class V7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=R.IDLE;resumeState=R.PLAYING;ttsConfig={};hostLocales={};readLocale=T0;disposed=!1;readinessGate=null;mathSpeechSource=null;currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Set;lastError=null;speakRunId=0;runOwner=null;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;pauseHold=null;structuralPause=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";wordlessPartHighlight=null;lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=Z7();clearPlaybackStartBarrier(Z=this.playbackStartBarrierCleanup){if(Z?.(),this.playbackStartBarrierCleanup===Z)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Z,Q){if(this.playbackStartDeferredRunId!==Z||Z!==this.speakRunId)return;if(this.state===R.PAUSED)this.activeRecordedAudio?.element.pause(),this.provider?.pause();this.markPlaying();let J=this.pendingPlaybackStartHighlights.splice(0);for(let Y of J)Y();if(Q?.wordBoundaries===!1)this.highlightWordlessPlayback()}highlightWordlessPlayback(){let Z=this.wordlessPartHighlight;if(!Z||this.activeHighlightMode!=="word")return;this.highlightCoordinator?.clearTTSWord(),Z()}installPlaybackStartBarrier(Z,Q=!1){this.clearPlaybackStartBarrier();let J=this.provider,Y=J&&"onPlaybackStart"in J?J:null;if(!Y&&!Q)return null;let X=Y?.onPlaybackStart,G=(B)=>{try{this.notifyPlaybackStarted(Z,B)}finally{X?.(B)}};if(Y)Y.onPlaybackStart=G;this.playbackStartDeferredRunId=Z;let j=()=>{if(Y?.onPlaybackStart===G)Y.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Z)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=j,j}runWhenPlaybackStarts(Z,Q){if(this.playbackStartDeferredRunId===Z){this.pendingPlaybackStartHighlights.push(Q);return}Q()}async waitWhilePaused(Z){while(this.state===R.PAUSED&&Z===this.speakRunId){if(!this.pauseHold){let Q=()=>{},J=new Promise((Y)=>{Q=Y});this.pauseHold={promise:J,release:Q}}await this.pauseHold.promise}}releasePauseHold(){let Z=this.pauseHold;this.pauseHold=null,Z?.release()}waitStructuralPause(Z){return this.cancelStructuralPause(),new Promise((Q)=>{let J=()=>{if(this.structuralPause?.finish===J)clearTimeout(this.structuralPause.timer),this.structuralPause=null;Q()};this.structuralPause={timer:setTimeout(J,Z),finish:J}})}cancelStructuralPause(){this.structuralPause?.finish()}abandonRun(){this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.cancelStructuralPause(),this.releasePauseHold()}beginRun(Z){let Q=this.state===R.LOADING||this.state===R.PLAYING||this.state===R.PAUSED,J=++this.speakRunId;if(this.runOwner=Z,this.abandonRun(),Q)this.provider?.stop();return this.setState(R.LOADING,!0),J}markPlaying(){if(this.state===R.PAUSED){this.resumeState=R.PLAYING;return}this.setState(R.PLAYING)}assertNotDisposed(){if(this.disposed)throw g0(Error("TTS service disposed"))}async emitTelemetry(Z,Q){try{await this.telemetryReporter?.(Z,Q)}catch(J){console.warn("[TTSService] telemetry callback failed:",J)}}async initialize(Z,Q={}){if(this.disposed)throw Error("TTS service disposed");this.currentProvider=Z,this.ttsConfig={...Q},this.hostLocales=x9(Q.providerOptions);let J=this.providerOptions().__pieTelemetry;this.telemetryReporter=typeof J==="function"?J:null,this.provider=await Z.initialize(Q)}async updateSettings(Z){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Q={...Z,...Z.providerOptions?{providerOptions:{...this.providerOptions(),...Z.providerOptions}}:{}};await this.provider.updateSettings(Q),this.ttsConfig={...this.ttsConfig,...Q},this.hostLocales=x9(Z.providerOptions,this.hostLocales)}setHighlightCoordinator(Z){this.highlightCoordinator=Z}setReadinessGate(Z){this.readinessGate=Z}setMathSpeechSource(Z){this.mathSpeechSource=Z}pendingReadiness(){if(this.provider||!this.readinessGate)return null;return this.readinessGate().catch((Z)=>{throw g0(Z)})}setHighlightTargetResolverProvider(Z){return this.highlightTargetResolverProvider=Z,()=>{if(this.highlightTargetResolverProvider===Z)this.highlightTargetResolverProvider=null}}setCatalogResolver(Z){this.catalogResolver=Z}getHighlightResolverRuntime(){let Z=null;try{Z=this.highlightTargetResolverProvider?.()??null}catch{Z=null}let Q=Z?.context??{},J=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...Q,scopeElement:Q.scopeElement??J},resolver:Z?.resolver??null}}getNodeElement(Z){if(!Z)return null;return Z.nodeType===Node.ELEMENT_NODE?Z:g(Z)}isElementWithinScope(Z,Q){if(!Q)return!0;return ZZ(Q,Z)}isRangeWithinScope(Z,Q){let J=this.getNodeElement(Z.startContainer),Y=this.getNodeElement(Z.endContainer);if(!J||!Y)return!1;return this.isElementWithinScope(J,Q)&&this.isElementWithinScope(Y,Q)}resolveWordHighlightRange(Z){let{context:Q,resolver:J}=this.getHighlightResolverRuntime(),Y=Q.scopeElement??this.currentContentElement;try{let X=J?.resolveWordRange?.(Z,Q);if(X&&this.isRangeWithinScope(X,Y))return{range:X,remapped:!h9(Z,X)}}catch{}return{range:Z,remapped:!1}}resolveSentenceHighlightTargets(Z){let{context:Q,resolver:J}=this.getHighlightResolverRuntime(),Y=Q.scopeElement??this.currentContentElement;try{let X=J?.resolveSentenceRanges?.(Z,Q);if(!X)return{ranges:Z,elements:[]};let G=[],j=[];for(let B of X){if(typeof Range<"u"&&B instanceof Range){if(!this.isRangeWithinScope(B,Y))return{ranges:Z,elements:[]};G.push(B);continue}if(typeof Element<"u"&&B instanceof Element){if(!this.isElementWithinScope(B,Y))return{ranges:Z,elements:[]};j.push(B);continue}return{ranges:Z,elements:[]}}return{ranges:G,elements:j}}catch{return{ranges:Z,elements:[]}}}createTextRange(Z,Q,J){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let Y=document.createRange();if(Y.setStart(Z,Q),Y.setEnd(Z,J),Y.startContainer!==Z||Y.endContainer!==Z)return null;return Y}catch{return null}}paintTTSWord(Z){if(!this.highlightCoordinator||Z.length===0)return;this.highlightCoordinator.highlightTTSWord(Z.map((Q)=>this.resolveWordHighlightRange(Q).range))}paintTTSSentenceRanges(Z){if(!this.highlightCoordinator)return;let{ranges:Q,elements:J}=this.resolveSentenceHighlightTargets(Z);if(J.length>0&&Q.length===0){this.highlightCoordinator.highlightTTSSentenceElements(J);return}let Y=[...Q];for(let X of J){let G=document.createRange();G.selectNodeContents(X),Y.push(G)}this.highlightCoordinator.highlightTTSSentence(Y)}providerOptions(){let Z=this.ttsConfig.providerOptions;return Z&&typeof Z==="object"?Z:{}}maxTextLength(){let Z=this.currentProvider?.getCapabilities?.().maxTextLength;return typeof Z==="number"&&Z>0?Z:void 0}async speakWithinLimit(Z,Q){let J=this.provider;if(!J)return;let Y=this.maxTextLength();if(!Y||Z.length<=Y){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==J)return;await J.speak(Z);return}if(I0(Z))throw Error(`[tts] SSML of ${Z.length} characters exceeds the provider's limit of ${Y}`);let X=J.onWordBoundary;try{for(let G of j7(Z,Y,{locale:this.readLocale})){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==J)return;J.onWordBoundary=X?(j,B,V)=>X(j,B+G.offset,V):void 0,await J.speak(G.text)}}finally{if(this.provider===J&&Q===this.speakRunId)J.onWordBoundary=X}}segmentsWithinLimit(Z){let Q=this.maxTextLength();if(!Q)return Z;return Z.flatMap((J)=>{if(J.text.length<=Q)return[J];let Y=j7(J.text,Q,{locale:this.readLocale});return Y.map((X,G)=>({text:X.text,startOffset:J.startOffset+X.offset,pauseMsAfter:G===Y.length-1?J.pauseMsAfter:void 0}))})}getTextProcessingOptions(Z){let Q=this.providerOptions().textNormalization?.boundarySpacingMode;return{locale:Z,boundarySpacingMode:Q==="none"||Q==="alnum"||Q==="segmenterPreferred"?Q:void 0}}resolveReadLanguage(Z,Q){let J=m5(Z,{contentLanguage:Q})??vZ(this.providerOptions().lang_id);return{contentLanguage:J,locale:J??this.hostLocales.locale??this.hostLocales.textNormalization??T0}}getMathSpeechOptions(){if(this.mathSpeechSource)return BZ(this.mathSpeechSource());return BZ(this.providerOptions().mathSpeech)}buildPositionMap(Z,Q,J){this.normalizedToDOM.clear();let{text:Y,map:X}=EZ(Z,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!v9())return;t.debug("Text comparison:",{spokenLength:Q.length,normalizedDomLength:Y.length,match:Q===Y,spokenPreview:Q.substring(0,150),normalizedPreview:Y.substring(0,150),differAtIndex:Q===Y?null:s3(Q,Y)}),t.debug("Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:Q.length,normalizedDomLength:Y.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===Q.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([G,{node:j,offset:B}])=>({pos:G,offset:B,char:j.textContent?.[B],expected:Q[G]}))})}getStructuralPauseProfile(){let Z=this.providerOptions().structuralPauses||{},Q=Z.units||{},J=(X,G)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let j=Number(X);return Number.isFinite(j)?j:G}return G},Y=l3;return{baseMs:J(Z.baseMs,Y.baseMs),units:{minor:J(Q.minor,Y.units.minor),section:J(Q.section,Y.units.section),major:J(Q.major,Y.units.major)},minMs:J(Z.minMs,Y.minMs),maxMs:J(Z.maxMs,Y.maxMs)}}resolvePauseMsFromUnits(Z){let Q=this.getStructuralPauseProfile(),J=Math.max(y9,Math.min(T9,Number(this.ttsConfig.rate||1))),Y=Q.baseMs*Math.max(0,Z)/J;return Math.max(Q.minMs,Math.min(Q.maxMs,Math.round(Y)))}resolveHighlightMode(){let Z=this.providerOptions().highlightMode;if(Z==="word"||Z==="sentence")return Z;let Q=this.currentProvider?.getCapabilities();if(Q?.defaultHighlightMode)return Q.defaultHighlightMode;return Q?.supportsWordBoundary?"word":"sentence"}hasExplicitBreakSemantics(Z){if(!Z.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Z)}getBoundaryStrength(Z){if(f9(Z)!==null)return"major";let Q=Z.tagName.toUpperCase();if(Q.match(/^H[1-6]$/))return"major";let J=(Z.getAttribute("role")||"").toLowerCase();if(J==="heading")return"major";if(J==="listitem"||J==="row"||J==="option"||J==="radio"||Q==="LI")return"section";return"minor"}getBoundaryAnchor(Z,Q){let J=p(Z),Y=null;while(J&&J!==Q){if(x0(J))return null;let G=f9(J);if(G!==null)return{anchor:J,units:G/this.getStructuralPauseProfile().baseMs};let j=(J.getAttribute("role")||"").toLowerCase(),B=J.tagName.toUpperCase();if(B.match(/^H[1-6]$/)||j==="heading"||j==="listitem"||B==="LI"){Y=J;break}if(!Y&&n3(J))Y=J;J=p(J)}if(!Y)return null;let X=this.getBoundaryStrength(Y);return{anchor:Y,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Z,Q,J,Y){let X=this.collectSpeechPlanBoundaries(Z,Y);if(J===0)return this.createSpeechPlanSegments(Q,X);let G=new Map;for(let[j,B]of X)G.set(j-J,B);return this.createSpeechPlanSegments(Q,G)}collectSpeechPlanBoundaries(Z,Q){let J=new Map,{map:Y}=EZ(Z,this.getTextProcessingOptions(Q)),X=this.createNodeStartOffsets(Y),G=null;for(let j of RZ(Z)){let B=p(j);if(B&&!x0(B)&&!k0(j)){let V=this.getBoundaryAnchor(j,Z),K=X.get(j);if(V&&K!==void 0&&V.anchor!==G&&K>0)J.set(K,Math.max(J.get(K)||0,V.units)),G=V.anchor}}return J}createNodeStartOffsets(Z){let Q=new Map;for(let[J,Y]of Z.entries())if(!Q.has(Y.node))Q.set(Y.node,J);return Q}createSpeechPlanSegments(Z,Q){let J=Array.from(Q.keys()).filter((V)=>V>0&&V<Z.length).sort((V,K)=>V-K),Y=[],X=0;for(let V of J){let{start:K,end:U}=I9(Z,X,V);if(U>K){let $=Z.substring(K,U);Y.push({text:$,startOffset:K,pauseMsAfter:this.resolvePauseMsFromUnits(Q.get(V)||0)})}X=V}let j=Z.substring(X).match(/^\s*/)?.[0].length||0,B=X+j;if(B<Z.length)Y.push({text:Z.substring(B).trimEnd(),startOffset:B,pauseMsAfter:0});return Y.filter((V)=>V.text.trim().length>0)}segmentSentences(Z){return IZ(Z,{locale:this.readLocale})}createSeekSegmentsFromText(Z){return this.segmentSentences(Z).map((Q)=>{let J=Q.text.match(/^\s*/)?.[0].length||0;return{text:Q.text.trim(),startOffset:Q.offset+J,pauseMsAfter:0}}).filter((Q)=>Q.text.length>0)}splitSegmentsAtBoundaries(Z,Q,J){if(Z.length===0||Q.length===0)return Z;let Y=Array.from(new Set(Q)).filter((G)=>Number.isFinite(G)&&G>0).sort((G,j)=>G-j);if(Y.length===0)return Z;let X=[];for(let G of Z){let j=G.startOffset,B=G.startOffset+G.text.length,V=Y.filter((U)=>U>j&&U<B);if(V.length===0){X.push(G);continue}let K=j;for(let U of[...V,B]){let{start:$,end:z}=I9(J,K,U);if(z>$)X.push({text:J.substring($,z),startOffset:$,pauseMsAfter:0});K=U}}return X}createSentenceHighlightSegments(Z){let Q=this.createSeekSegmentsFromText(Z.contentToSpeak);if(!Z.shouldUsePlan||Z.playbackSegments.length===0)return Q;let J=Z.playbackSegments.map((Y)=>Y.startOffset).filter((Y)=>Y>0);return this.splitSegmentsAtBoundaries(Q,J,Z.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Z){let Q=0;return Z.map((J)=>{let Y=J.plainFallback?.speechText||(this.hasExplicitBreakSemantics(J.speechText)?J.visibleText:J.speechText)||J.visibleText,X=T(Y)||J.visibleText||"",G={text:X,startOffset:Q,pauseMsAfter:0};return Q+=X.length+1,G})}getCurrentSeekSegmentIndex(){return Math.max(0,this.getSegmentIndexForOffset(this.seekSegments,this.currentBoundaryOffset))}async speakWithPlan(Z,Q,J){if(!this.provider||Z.length===0)return;let Y=J?.highlightMode==="sentence",X=this.provider;if(!Y&&typeof X.speakSegments==="function"){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==X)return;this.currentBoundaryOffset=0;let G=this.provider.onWordBoundary;this.provider.onWordBoundary=(j,B,V)=>{if(G?.(j,B,V),Number.isFinite(B))this.currentBoundaryOffset=B};try{await X.speakSegments(this.segmentsWithinLimit(Z))}finally{if(Q===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=G}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let G of Z){if(await this.waitWhilePaused(Q),Q!==this.speakRunId)return;this.currentBoundaryOffset=G.startOffset;let j=()=>{this.highlightSentenceSegment(G.startOffset,G.text)};if(Y)this.runWhenPlaybackStarts(Q,j);this.wordlessPartHighlight=j;try{await this.speakWithinLimit(G.text,Q)}finally{if(this.wordlessPartHighlight===j)this.wordlessPartHighlight=null}let B=G.pauseMsAfter??0;if(B>0&&Q===this.speakRunId)await this.waitStructuralPause(B)}}highlightSentenceSegment(Z,Q){if(!this.highlightCoordinator||typeof document>"u")return;let J=Q.trimEnd().length;if(J<=0)return;let Y=Z+this.activeWordBoundaryOffset,X=this.normalizedToDOM.get(Y),G=this.normalizedToDOM.get(Y+J-1);if(!X||!G)return;let j=zZ(this.normalizedToDOM,Y,Y+J);if(j.length===0)return;this.paintTTSSentenceRanges(j),this.activeSentenceStartOffset=Z}getSegmentIndexForOffset(Z,Q){if(Z.length===0)return-1;let J=-1;for(let Y=0;Y<Z.length;Y++)if(Z[Y].startOffset<=Q)J=Y;else break;return J}highlightSentenceForOffset(Z){let Q=this.sentenceHighlightSegments;if(!this.highlightCoordinator||Q.length===0)return;let J=this.getSegmentIndexForOffset(Q,Z);if(J<0)return;let Y=Q[J];if(!Y)return;if(this.activeSentenceStartOffset===Y.startOffset)return;this.highlightSentenceSegment(Y.startOffset,Y.text)}async speak(Z,Q={}){this.assertNotDisposed();let J=this.pendingReadiness(),Y=Q.ownerId??null,X=J?this.beginRun(Y):null;if(J){try{await J}catch(V){if(X===this.speakRunId)this.setState(R.IDLE);throw V}if(this.assertNotDisposed(),X!==this.speakRunId)return}if(!this.provider){if(X!==null)this.setState(R.IDLE);throw g0(Error("TTS service not initialized"))}let G=this.resolveReadLanguage(k9(Z)?Z.startContainer:Z,Q.language),j=k9(Z)?this.resolveRangeTarget(Z,Q,G):this.resolveElementTarget(Z,Q,G);if(!j){if(X!==null)this.setState(R.IDLE);return}let B=X??this.beginRun(Y);if(Q.rate!==void 0){if(await this.applyRunRate(Q.rate),B!==this.speakRunId)return}await this.speakContent(j.text,j.options,B)}async applyRunRate(Z){await this.playbackRateWriteQueue;let Q=this.normalizePlaybackRate(Z),J=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Q===J)return;await this.updateSettings({rate:Q})}isSuppressedTarget(Z){if(!k0(Z))return!1;return console.warn("[tts] the content to read lies inside content marked not-to-be-spoken; nothing was spoken."),!0}resolveElementTarget(Z,Q,J){if(this.isSuppressedTarget(Z))return null;let Y={catalogId:Q.catalogId,catalogContext:Q.catalogContext,language:J.locale,contentLanguage:J.contentLanguage,contentElement:Z},X=$Z(Z,this.getTextProcessingOptions(J.locale)).visibleText.trim();if(!X&&!this.holdsSpokenCard(Z,Y))return console.warn("[tts] the content to read holds no speakable text; nothing was spoken."),null;return{text:X,options:Y}}holdsSpokenCard(Z,Q){if(!this.catalogResolver)return!1;if(Q.catalogId){if(this.catalogResolver.getAlternative(Q.catalogId,{type:"spoken",language:Q.language,useFallback:!0,context:Q.catalogContext,form:"content"})?.content!==void 0)return!0}return this.collectCatalogSpeechChunks(Z,Q).some((J)=>J.sourceElement)}resolveRangeTarget(Z,Q,J){if(this.isSuppressedTarget(Z.commonAncestorContainer))return null;let Y=Z.commonAncestorContainer,X=Q.contentRoot||(Y.nodeType===Node.ELEMENT_NODE?Y:g(Y));if(!X)return null;let G=u5(Z,X),j=G.text.trim();if(!j){if(G.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return null}let B=this.selectMappedRangeText(Z,X,J.locale),V=j,K=B?.offset??0;if(B)V=B.text;else{let U=document.createRange();U.selectNodeContents(X),U.setEnd(Z.startContainer,Z.startOffset);let $=u5(U,X).text,z=T($);K=z.length+(/\s$/.test($)&&z?1:0)}return t.debug("selection offset calculation:",{selectedText:V,mapped:!!B,offset:K,rootTag:X.tagName}),{text:V,options:{catalogId:Q.catalogId&&F0(Z,X,X)?Q.catalogId:void 0,catalogContext:Q.catalogContext,language:J.locale,contentLanguage:J.contentLanguage,contentElement:X,contentRange:Z,wordBoundaryOffset:K}}}async speakContent(Z,Q,J){let Y=null;try{if(await this.applyLanguageSettings(Q),J!==this.speakRunId)return;let X=await this.resolveSpeechContent(Z,Q);if(J!==this.speakRunId)return;let{contentToSpeak:G,speechText:j,highlightText:B,normalizedText:V,usedCatalogSpoken:K,speechSource:U,speechMatchesVisibleText:$,speechChunks:z}=X;this.logResolvedSpeechContent({contentToSpeak:G,speechSource:U,catalogId:Q.catalogId}),this.initializeSpeakTracking(B,Q);let D=$?this.resolveHighlightMode():"sentence";this.activeHighlightMode=D;let L=Q.wordBoundaryOffset||0;this.activeWordBoundaryOffset=L;let P=this.hasExplicitBreakSemantics(G),A=!!this.currentContentElement&&!K&&!P&&$;if(this.playbackChunks=z?.length?z:[],this.playbackChunks.length)this.seekSegments=this.createSeekSegmentsFromSpeechChunks(this.playbackChunks);else if(P||!$)this.seekSegments=[];else if(A&&this.currentContentElement)this.seekSegments=this.createSpeechPlan(this.currentContentElement,V,L,Q.language);else this.seekSegments=this.createSeekSegmentsFromText(B);if(this.sentenceHighlightSegments=P?[]:this.createSentenceHighlightSegments({contentToSpeak:B,shouldUsePlan:A,playbackSegments:this.seekSegments}),Y=this.installPlaybackStartBarrier(J,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:B,options:Q,highlightMode:D,shouldUsePlan:A,runId:J}),$)this.configureWordBoundaryHighlighting({highlightMode:D,wordBoundaryOffset:L});else this.clearWordBoundaryHighlighting();if(!Y)this.markPlaying();if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:A,runId:J,highlightMode:D,contentToSpeak:j,speechChunks:z}),J!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(X){if(J!==this.speakRunId)return;throw console.error("TTS error:",X),this.lastError=X instanceof Error?X.message:String(X),this.setState(R.ERROR),this.clearHighlightsAndTracking(),X}finally{this.clearPlaybackStartBarrier(Y)}}async applyLanguageSettings(Z){if(!this.provider)return;this.readLocale=Z.language;let Q=Z.contentLanguage,J=this.providerOptions(),Y={locale:Q??this.hostLocales.locale,textNormalization:Q??this.hostLocales.textNormalization,segmenter:Q??this.hostLocales.segmenter};if(J.contentLanguage===Q&&vZ(J.locale)===Y.locale&&vZ(J.textNormalization?.locale)===Y.textNormalization&&vZ(J.segmenter?.locale)===Y.segmenter)return;let X={...J,locale:Y.locale,textNormalization:{...J.textNormalization,locale:Y.textNormalization},segmenter:{...J.segmenter,locale:Y.segmenter},contentLanguage:Q};this.ttsConfig={...this.ttsConfig,providerOptions:X},await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Z,Q){let J=T(Z);if(Q.catalogId&&this.catalogResolver){let G=this.catalogResolver.getAlternative(Q.catalogId,{type:"spoken",language:Q.language,useFallback:!0,context:Q.catalogContext,form:"content"}),j=G?.content;if(G&&j!==void 0){let B=$Z(Q.contentElement,this.getTextProcessingOptions(Q.language)).visibleText||J,V=T(j);return t.debug(`Using catalog content for "${Q.catalogId}" (${G.language})`),{contentToSpeak:j,speechText:j,visibleText:B,highlightText:B,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:B,containsMathMarkup:!1,speechMatchesVisibleText:V===B}}t.debug(`No catalog found for "${Q.catalogId}", falling back to generated TTS`)}let Y=this.resolveCatalogComposedSpeechContent(Q.contentElement,J,Q);if(Y)return Y;return{...await this.resolveGeneratedSpeechContent(Q.contentElement,J,Q.language,Q.contentRange),usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Z,Q,J){if(!this.catalogResolver)return null;let Y=this.collectCatalogSpeechChunks(Z,J);if(!Y.some((j)=>j.sourceElement))return null;let X=T(Y.map((j)=>j.speechText).join(" ")),G=J.contentRange?Q:$Z(Z,this.getTextProcessingOptions(J.language)).visibleText||Q;return{contentToSpeak:X,speechText:X,visibleText:G,highlightText:G,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:G,containsMathMarkup:!1,speechMatchesVisibleText:Y.every((j)=>j.speechMatchesVisibleText),speechChunks:Y}}collectCatalogSpeechChunks(Z,Q){let J=this.catalogResolver;if(!J)return[];let Y=[],X="",G=()=>{let $=T(X);if(X="",!$)return;Y.push({speechText:$,visibleText:$,sourceElement:null,speechMatchesVisibleText:!0})},j=Q.contentRange,B=($)=>{let z=$.getAttribute("data-catalog-idref");if(!z)return null;if(j&&!F0(j,$,Z))return null;let D={type:"spoken",language:h5($,Z)||Q.language,useFallback:!0,context:Q.catalogContext},L=J.getAlternative(z,{...D,form:"payload"}),P=L?.payload?C8({payload:L.payload})??void 0:void 0,N=J.getAlternative(z,{...D,form:"content"})?.content;if(P===void 0&&N===void 0)return null;return{script:N,audio:P}},V=($,z)=>{let D=K($);if(D.length!==1)return null;let L=D[0],P=$Z(L,this.getTextProcessingOptions(Q.language)).visibleText||T(L.textContent||""),A=(N)=>T(N).replace(/\s+/g,"");return A(P)===A(z)?L:null},K=($)=>{let z=_8($,"math");if($.localName?.toLowerCase()==="math")return[$,...z];return z},U=($)=>{if(UZ($,Z))return;if($.nodeType===Node.TEXT_NODE){if(!j)X+=` ${$.textContent||""}`;else if(YZ(j,$))X+=` ${p5($,j)}`;return}if($.nodeType!==Node.ELEMENT_NODE)return;let z=$,D=B(z);if(D){G();let L=$Z(z,this.getTextProcessingOptions(Q.language)),P=L.visibleText||T(H8(z)),A=p0(z,Z),N=null;if(D.script!==void 0){let O=D.script,S=h0({speechText:O,visibleText:P}),C=V(z,P),h=C?nZ({mathElement:C,speechText:O}):void 0,b=h?void 0:K(z).map((d)=>({element:d,alignment:nZ({mathElement:d,speechText:O})}));N={speechText:O,visibleText:P,sourceElement:z,regionElement:A,speechMatchesVisibleText:T(O)===P,playbackMode:S.playbackMode,alignment:S,mathAlignment:h,mathAlignments:b,visibleMap:L.map}}if(D.audio){Y.push(N?{...N,audio:D.audio,plainFallback:N}:{speechText:P,visibleText:P,sourceElement:z,regionElement:A,speechMatchesVisibleText:!1,visibleMap:L.map,audio:D.audio});return}if(N)Y.push(N);return}for(let L of KZ(z))U(L)};return U(Z),G(),Y}resolveGeneratedPlaybackFormat(){let Z=this.currentProvider;if(!Z)return"plain";return Z.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Z,Q,J,Y){let X=this.resolveGeneratedPlaybackFormat(),{plan:G,containsMathMarkup:j,visibleText:B}=await B7({contentRoot:Z,range:Y,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:X==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver});if(!j){let $=Y?Q:B||Q;return{contentToSpeak:$,speechText:$,visibleText:$,highlightText:$,normalizedText:$,containsMathMarkup:!1,speechMatchesVisibleText:!0}}let V=B||Q,K=W7(G,{format:X}),U=G.plainSpeechText;return{contentToSpeak:U,speechText:U,visibleText:V,highlightText:V,normalizedText:V,containsMathMarkup:!0,speechMatchesVisibleText:U===V,speechChunks:K}}logResolvedSpeechContent(Z){let Q=Z.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);t.debug("Speak resolved content",{source:Z.speechSource,catalogId:Z.catalogId||null,length:Z.contentToSpeak.length,preview:Q})}initializeSpeakTracking(Z,Q){this.currentText=Z,this.currentContentElement=Q.contentElement,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Z){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Z.contentToSpeak,Z.options.language),Z.highlightMode==="sentence"&&Z.shouldUsePlan)return;let Q=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Z.runId,()=>{if(Q)this.highlightSentenceSegment(Q.startOffset,Q.text),t.debug("Applied initial sentence highlighting");else try{let J=document.createRange();J.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([J])}catch{}})}configureWordBoundaryHighlighting(Z){if(!this.provider)return;if(Z.highlightMode==="sentence"){this.provider.onWordBoundary=void 0;return}if(!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(Q,J,Y)=>{let X=Y||Q.length,G=J+this.currentBoundaryOffset,j=G+Z.wordBoundaryOffset;this.highlightSentenceForOffset(G);let B=zZ(this.normalizedToDOM,j,j+X);if(B.length===0){t.debug(`no text at position ${j}, length ${X}, to highlight`);return}t.debug(`Highlighting "${B.join("")}" (word: "${Q}") at position ${j}`),this.paintTTSWord(B)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Z){let Q=Z.regionElement||Z.sourceElement;if(!Q&&!Z.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Z.regionRange){let Y=zZ(Z.visibleMap,0,Z.visibleText.length);this.highlightCoordinator.clearTTSWord(),this.paintTTSSentenceRanges(Y.length>1?Y:[Z.regionRange]);return}if(!Q)return;let J=document.createRange();J.selectNodeContents(Q),this.highlightCoordinator.clearTTSWord(),this.paintTTSSentenceRanges([J])}catch{}}highlightRenderableRegionTarget(Z){if(!this.highlightCoordinator||!Z||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&i3(this.lastRenderedRegionTarget,Z))return;try{let Q=document.createRange();if(Z.type==="element")Q.selectNodeContents(Z.element);else if(Z.type==="range"){this.paintTTSSentenceRanges(Z.ranges??[Z.range]),this.lastRenderedRegionTarget=Z;return}else Q.setStart(Z.node,Z.startOffset),Q.setEnd(Z.node,Z.endOffset);this.paintTTSSentenceRanges([Q]),this.lastRenderedRegionTarget=Z}catch{}}highlightRenderableActiveTarget(Z){if(!this.highlightCoordinator||typeof document>"u")return;if(!Z){this.highlightCoordinator.clearTTSWord();return}if(Z.type==="text-range"){let X=this.createTextRange(Z.node,Z.startOffset,Z.endOffset);if(X)this.paintTTSWord([X]);return}if(Z.type==="range"){this.paintTTSWord(Z.ranges??[Z.range]);return}let Q=document.createRange();Q.selectNodeContents(Z.element);let J=this.resolveWordHighlightRange(Q);if(J.remapped){this.highlightCoordinator.highlightTTSWord([J.range]);return}let Y=Z.element.childNodes.length===1?Z.element.firstChild:null;if(Z.quality==="semantic-token"&&Y?.nodeType===Node.TEXT_NODE){let X=document.createRange();X.selectNodeContents(Y),this.highlightCoordinator.highlightTTSWord([X]);return}this.highlightCoordinator.highlightTTSWordElement(Z.element)}renderHighlightDecision(Z){this.highlightRenderableRegionTarget(Z.regionTarget),this.highlightRenderableActiveTarget(Z.activeTarget)}async speakCatalogChunk(Z,Q){try{await this.speakCatalogChunkOnce(Z,Q)}catch(J){if(Z.plainFallback&&Q===this.speakRunId){if(t.debug("SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),this.playbackStartDeferredRunId===Q&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.markPlaying();await this.speakCatalogChunkOnce(Z.plainFallback,Q);return}throw J}}async playRecordedAudio(Z,Q){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let J=Z.sources[0],Y=document.createElement("audio");Y.preload="auto",Y.src=g3(J.src,Z.fragment),Y.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,G)=>{let j,B=!1,V=!1,K=()=>{if(V||B)return;B=!0,Q?.()},U=()=>{if(Y.removeEventListener("ended",$),Y.removeEventListener("error",z),Y.removeEventListener("playing",K),j?.(),this.activeRecordedAudio?.element===Y)this.activeRecordedAudio=null},$=()=>{if(V)return;V=!0,U(),X()},z=()=>{if(V)return;V=!0,U(),G(Error(`[tts] recorded audio failed to play: ${J.src}`))},D=()=>{Promise.resolve(Y.play()).then(K).catch((L)=>{if(L?.name==="AbortError"&&this.state===R.PAUSED)return;z()})};this.activeRecordedAudio={element:Y,cancel:()=>{if(V)return;V=!0,U(),Y.pause(),X()},play:D},Y.addEventListener("ended",$),Y.addEventListener("error",z),Y.addEventListener("playing",K),j=c3(Y,Z.fragment,$),D()}).finally(()=>{if(this.activeRecordedAudio?.element===Y)this.activeRecordedAudio=null;Y.pause(),Y.removeAttribute("src")})}cancelRecordedAudio(){let Z=this.activeRecordedAudio;if(!Z)return;this.activeRecordedAudio=null,Z.cancel()}async speakCatalogChunkOnce(Z,Q){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Z.audio){this.runWhenPlaybackStarts(Q,()=>{this.highlightCatalogRegion(Z)}),await this.playRecordedAudio(Z.audio,()=>{this.notifyPlaybackStarted(Q)});return}let J=Z.regionElement||Z.sourceElement||this.currentContentElement,Y=J?b9({contentRoot:J,chunks:[Z]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,G=Y?C9({chunks:[Y],mathTokenHighlighting:X}):null,j=!Y||Y.offsetSpace==="unsupported"?"unknown":Y.offsetSpace;if(this.runWhenPlaybackStarts(Q,()=>{if(G&&Y&&Z.mathAlignment)this.renderHighlightDecision(G.resolveInitial(Y.id));else this.highlightCatalogRegion(Z)}),!(this.resolveHighlightMode()==="word"&&Z.sourceElement&&(Z.mathAlignment&&Z.mathAlignment.speech.tokens.length>0||Z.mathAlignments&&Z.mathAlignments.length>0||Z.alignment&&Z.visibleMap&&(Z.playbackMode==="exact-word"||Z.playbackMode==="anchor-span")))){let $=this.provider,z=$.onWordBoundary;$.onWordBoundary=void 0;try{await this.speakWithinLimit(Z.speechText,Q)}finally{if(this.provider===$&&Q===this.speakRunId&&$.onWordBoundary===void 0)$.onWordBoundary=z}return}let V=this.provider,K=V.onWordBoundary,U=($,z,D)=>{if(Q!==this.speakRunId||!G||!Y)return;this.renderHighlightDecision(G.resolveBoundary({chunkId:Y.id,word:$,position:z,length:D,providerOffsetSpace:j}))};V.onWordBoundary=U;try{await this.speakWithinLimit(Z.speechText,Q)}finally{if(this.provider===V&&Q===this.speakRunId&&V.onWordBoundary===U)V.onWordBoundary=K}}async executeSpeakPlayback(Z){if(Z.speechChunks?.length&&this.provider){for(let Q=0;Q<Z.speechChunks.length;Q++){if(await this.waitWhilePaused(Z.runId),Z.runId!==this.speakRunId)return;let J=this.seekSegments[Q];if(J)this.currentBoundaryOffset=J.startOffset;let Y=Z.speechChunks[Q];await this.speakCatalogChunk(Y,Z.runId)}return}if(Z.shouldUsePlan&&this.currentContentElement&&this.seekSegments.length>0){await this.speakWithPlan(this.seekSegments,Z.runId,{highlightMode:Z.highlightMode});return}await this.speakWithinLimit(Z.contentToSpeak,Z.runId)}clearHighlightsAndTracking(){if(this.clearWordBoundaryHighlighting(),this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.activeSentenceStartOffset=null,this.wordlessPartHighlight=null}selectMappedRangeText(Z,Q,J){if(typeof Z.comparePoint!=="function")return null;let{text:Y,map:X}=EZ(Q,this.getTextProcessingOptions(J)),G=-1,j=-1;for(let[U,{node:$,offset:z}]of X){if(U>=Y.length)continue;if(!q0(Z,$,z))continue;if(G===-1||U<G)G=U;if(U>j)j=U}if(G===-1)return null;let B=Y.slice(G,j+1),V=B.length-B.trimStart().length,K=B.trim();return K?{text:K,offset:G+V}:null}pause(){if(this.state!==R.PLAYING&&this.state!==R.LOADING)return;this.resumeState=this.state,this.activeRecordedAudio?.element.pause(),this.provider?.pause(),this.setState(R.PAUSED)}resume(){if(this.state!==R.PAUSED)return;this.setState(this.resumeState),this.activeRecordedAudio?.play(),this.provider?.resume(),this.releasePauseHold()}normalizePlaybackRate(Z){if(!Number.isFinite(Z))return 1;return Math.max(y9,Math.min(T9,Z))}async restartFromSeekIndex(Z){if(!this.provider||this.seekSegments.length===0)return;let Q=Math.max(0,Math.min(this.seekSegments.length-1,Z)),J=this.playbackChunks.length?this.playbackChunks.slice(Q):null,Y=this.state===R.PAUSED;this.speakRunId+=1,this.abandonRun(),this.provider.onWordBoundary=void 0,this.provider.stop();let X=++this.speakRunId,G=this.seekSegments.slice(Q);if(this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.currentBoundaryOffset=this.seekSegments[Q].startOffset,!Y)this.setState(R.LOADING);let j=this.installPlaybackStartBarrier(X,!!J?.[0]?.audio);if(Y)this.resumeState=j?R.LOADING:R.PLAYING;else if(!j)this.setState(R.PLAYING);this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),J)for(let B=0;B<J.length;B++){if(await this.waitWhilePaused(X),X!==this.speakRunId)return;let V=Q+B,K=this.seekSegments[V];if(K)this.currentBoundaryOffset=K.startOffset;await this.speakCatalogChunk(J[B],X)}else await this.speakWithPlan(G,X,{highlightMode:this.activeHighlightMode});if(X!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(B){if(X!==this.speakRunId){t.debug("Superseded seek restart failed:",B);return}throw this.lastError=B instanceof Error?B.message:String(B),this.setState(R.ERROR),this.clearHighlightsAndTracking(),B}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Z){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Q=this.normalizePlaybackRate(Z),J=this.pendingPlaybackRateRequest;if(J?.rate===Q){await J.promise;return}let Y=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let B=this.speakRunId;if(Y!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:B};let V=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Q===V)return{didUpdate:!1,playbackRunId:B};return await this.updateSettings({rate:Q}),{didUpdate:!0,playbackRunId:B}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let G=X.then(async(B)=>{if(Y!==this.playbackRateRequestId||B.playbackRunId!==this.speakRunId)return;let V=this.activePlaybackRate!==null&&this.activePlaybackRate!==Q;if(!B.didUpdate&&!V)return;if(this.state!==R.PLAYING&&this.state!==R.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),j;j=G.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===j)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:Q,promise:j},await j}async seekBy(Z){if(!this.provider||!this.currentText)return;if(this.state!==R.PLAYING&&this.state!==R.PAUSED)return;if(this.hasExplicitBreakSemantics(this.currentText))return;if(this.seekSegments.length===0)return;let Q=Number.isFinite(Z)?Math.trunc(Z):0;if(Q===0)return;let J=this.getCurrentSeekSegmentIndex(),Y=Math.max(0,Math.min(this.seekSegments.length-1,J+Q));if(Y===J)return;await this.restartFromSeekIndex(Y)}async seekForward(Z=1){let Q=Number.isFinite(Z)?Math.max(1,Math.trunc(Z)):1;await this.seekBy(Q)}async seekBackward(Z=1){let Q=Number.isFinite(Z)?Math.max(1,Math.trunc(Z)):1;await this.seekBy(-Q)}stop(){this.speakRunId+=1,this.abandonRun(),this.provider?.stop(),this.clearHighlightsAndTracking(),this.currentText=null;let Z=this.runOwner!==null;this.runOwner=null,this.setState(R.IDLE,Z)}releaseProvider(){this.stop(),this.provider=null,this.currentProvider=null}dispose(){if(this.disposed)return;this.releaseProvider(),this.disposed=!0,this.speakRunId+=1,this.abandonRun(),this.playbackRateRequestId+=1,this.pendingPlaybackRateRequest=null,this.listeners.clear(),this.readinessGate=null,this.mathSpeechSource=null,this.highlightTargetResolverProvider=null,this.highlightCoordinator=null,this.catalogResolver=null,this.telemetryReporter=null}getState(){return this.state}getRunOwner(){return this.runOwner}onStateChange(Z){let Q=(J)=>Z(J);return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}setState(Z,Q=!1){let J=this.state;if(J===Z&&!Q)return;this.state=Z;for(let Y of[...this.listeners])Y(Z);if(J===Z)return;if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",previousState:J,state:Z}),Z===R.PLAYING){let Y=J===R.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(Y,{toolId:"textToSpeech",previousState:J,state:Z});return}if(Z===R.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",previousState:J,state:Z});return}if(Z===R.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",previousState:J,state:Z,message:this.lastError||void 0});return}if(Z===R.IDLE&&(J===R.PLAYING||J===R.PAUSED||J===R.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",previousState:J,state:Z})}}import{createPieLogger as r3,isTtsDebugEnabled as o3}from"@pie-players/pie-players-shared/pie";var m9=r3("browser-tts-provider",o3),u9=5000,c9=2000,p9=260,a3=80,t3=["__pieTelemetry","contentLanguage","highlightMode","locale","mathSpeech","segmenter","structuralPauses","textNormalization"],d9=(Z)=>{let Q={};if(Z.rate!==void 0)Q.rate=Z.rate;if(Z.pitch!==void 0)Q.pitch=Z.pitch;if(Z.mathTokenHighlighting!==void 0)Q.mathTokenHighlighting=Z.mathTokenHighlighting;let J=Z.providerOptions;if(J&&typeof J==="object"){let Y={};for(let X of t3)if(J[X]!==void 0)Y[X]=J[X];if(Object.keys(Y).length>0)Q.providerOptions=Y}return Q},g9=(Z)=>{if(!I0(Z))return{text:Z,sourceOffset:(X)=>X};let{spokenText:Q,rawToSpokenOffsetMap:J}=v0(Z),Y=[];for(let[X,G]of J){let j=Y[G];if(j===void 0||X<j)Y[G]=X}return{text:Q,sourceOffset:(X)=>{for(let G=X;G>=0;G--){let j=Y[G];if(j!==void 0)return j}return 0}}},q7=(Z)=>String(Z||"").trim().toLowerCase(),e3=()=>{let Z=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return q7(Z||"en-US")},Z2=(Z,Q)=>{let J=q7(Q)||e3(),Y=J.split("-")[0]||"en",X=q7(Z.lang);return X===J||X.startsWith(`${Y}-`)},Q2=(Z,Q,J)=>{if(Q)return Z.find((G)=>G.voiceURI===Q)||Z.find((G)=>G.name===Q)||null;let Y=(G)=>Z2(G,J),X=[(G)=>G.localService&&Y(G),(G)=>G.default&&Y(G),(G)=>Y(G),(G)=>G.localService,(G)=>G.default];for(let G of X){let j=Z.find(G);if(j)return j}return Z[0]||null},J2=(Z,Q,J=()=>!0)=>{if(Z.getVoices().length>0)return Promise.resolve(!0);let Y=typeof Z.addEventListener==="function"&&typeof Z.removeEventListener==="function";if(!Y&&!("onvoiceschanged"in Z))return Promise.resolve(!1);return new Promise((X)=>{let G=Y?null:Z.onvoiceschanged,j=!1,B=(z)=>{if(j)return;if(j=!0,clearTimeout($),Y)Z.removeEventListener("voiceschanged",K);else if(Z.onvoiceschanged===U)Z.onvoiceschanged=G;X(z)},V=()=>{if(!J())B(!1);else if(Z.getVoices().length>0)B(!0)},K=()=>V(),U=(z)=>{try{G?.call(Z,z)}finally{V()}},$=setTimeout(()=>B(!1),Q);if(Y)Z.addEventListener("voiceschanged",K);else Z.onvoiceschanged=U;V()})},Y2=(Z)=>!Z.default;class K7{providerId="browser";async initialize(Z){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");if(typeof Z.voice==="string"&&Z.voice.trim())await J2(window.speechSynthesis,c9);return new l9(Z)}getCapabilities(){return{supportsWordBoundary:!0,defaultHighlightMode:"sentence",supportsSSML:!1}}destroy(){}}class l9{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;activeRunId=null;releasePauseHold=null;settlePendingChunk=null;settlePendingGap=null;onPlaybackStart=void 0;constructor(Z){this.config=Z}async waitWhilePaused(Z){while(this._isPaused&&Z===this.speakRunId)await new Promise((Q)=>{this.releasePauseHold=Q});return Z===this.speakRunId}releaseHold(){let Z=this.releasePauseHold;this.releasePauseHold=null,Z?.()}resolveBrowserVoice(){let Z=typeof this.config?.voice==="string"?this.config.voice.trim():"",Q=speechSynthesis.getVoices();if(Z&&Q.length===0)throw Error(`Configured browser voice "${Z}" could not be resolved because the browser did not publish its voice inventory within ${c9/1000} seconds.`);let J=Q2(Q,Z||void 0,this.getContentLocale());if(Z&&!J)throw Error(`Configured browser voice "${Z}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return J}async speak(Z){if(!this.config)throw Error("TTS not initialized");this.stop();let Q=this.speakRunId;this.activeRunId=Q;try{let J=this.resolveBrowserVoice(),Y=g9(Z),X=this.splitIntoChunks(Y.text);for(let G of X){if(this._isPaused&&!await this.waitWhilePaused(Q))break;if(!await this.speakChunk(G.text,G.offset,Q,J,Y.sourceOffset))break}}finally{if(this.activeRunId===Q)this.activeRunId=null}}async speakSegments(Z){if(!this.config)throw Error("TTS not initialized");this.stop();let Q=this.speakRunId;this.activeRunId=Q;try{let J=this.resolveBrowserVoice();for(let Y of Z){if(Q!==this.speakRunId)break;let X=g9(Y.text),G=this.splitIntoChunks(X.text);for(let B of G){if(this._isPaused&&!await this.waitWhilePaused(Q))break;if(!await this.speakChunk(B.text,B.offset,Q,J,(K)=>Y.startOffset+X.sourceOffset(K)))break}let j=Math.max(0,Number(Y.pauseMsAfter||0));if(j>0&&Q===this.speakRunId){if(!await this.waitForPause(j,Q))break}}}finally{if(this.activeRunId===Q)this.activeRunId=null}}async waitForPause(Z,Q){return await new Promise((J)=>{let Y=()=>{if(clearTimeout(X),this.settlePendingGap===Y)this.settlePendingGap=null;J()},X=setTimeout(Y,Z);this.settlePendingGap=Y}),Q===this.speakRunId}splitIntoChunks(Z){if(Z.length<=p9)return[{text:Z,offset:0}];let Q=this.segmentSentences(Z),J=[],Y="",X=0;for(let G of Q){let j=G.text.trim();if(!j)continue;let B=G.text.search(/\S/),V=G.offset+(B===-1?0:B);if(!Y){Y=j,X=V;continue}let K=`${Y} ${j}`;if(K.length<=p9)Y=K;else J.push({text:Y,offset:X}),Y=j,X=V}if(Y)J.push({text:Y,offset:X});return J.length?J:[{text:Z,offset:0}]}getContentLocale(){let Z=this.config?.providerOptions?.contentLanguage;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}getSegmentationPolicy(){let Z=this.config?.providerOptions||{},Q=Z.segmenter||{},Y=Q.mode!=="regexOnly",X=typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:typeof Z.locale==="string"&&Z.locale.trim().length>0?Z.locale:void 0;return{useSentenceSegmenter:Y,locale:X}}segmentSentences(Z){let Q=this.getSegmentationPolicy();return IZ(Z,{locale:Q.locale,useSentenceSegmenter:Q.useSentenceSegmenter})}inferWordLength(Z,Q){let J=Math.max(0,Math.min(Q,Math.max(0,Z.length-1)));return Z.slice(J).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Z,Q,J,Y,X){return new Promise((G,j)=>{if(J!==this.speakRunId){G(!1);return}let B=new SpeechSynthesisUtterance(Z);this.utterance=B;let V=this.getContentLocale();if(V)B.lang=V;if(Y&&Y2(Y))B.voice=Y;if(this.config?.rate)B.rate=this.config.rate;if(this.config?.pitch)B.pitch=this.config.pitch;let K=!1,U=!1,$=null,z=null,D=()=>{if(this.utterance===B)this.utterance=null},L=()=>{if($!==null)clearTimeout($),$=null},P=()=>{B.onstart=null,B.onend=null,B.onerror=null,B.onpause=null,B.onresume=null,B.onboundary=null},A=(O,S)=>{if(U)return;if(U=!0,L(),P(),D(),z&&this.settlePendingChunk===z)this.settlePendingChunk=null;if(J===this.speakRunId)this._isPlaying=!1;if(S)j(S);else G(O)},N=(O)=>Error(O==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${u9/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);z=()=>A(!1),this.settlePendingChunk=z,B.onstart=()=>{if(J!==this.speakRunId){A(!1);return}if(K=!0,L(),this._isPlaying=!0,this._isPaused)speechSynthesis.pause();try{this.onPlaybackStart?.()}catch(O){console.error("Browser TTS playback-start callback failed",O)}},B.onend=()=>{if(J!==this.speakRunId){A(!1);return}if(!K){A(!1,N("ended"));return}A(!0)},B.onerror=(O)=>{if(J!==this.speakRunId){A(!1);return}if(O.error==="interrupted"||O.error==="canceled"){A(!1);return}A(!1,Error(`Speech synthesis error: ${O.error}`))},B.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},B.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},B.onboundary=(O)=>{if(J!==this.speakRunId)return;if(m9.debug(`boundary event: ${O.name}, charIndex ${O.charIndex}, charLength ${O.charLength}`),O.name!=="word"||!this.onWordBoundary)return;let S=Math.max(0,Math.min(O.charIndex,Math.max(0,Z.length-1))),C=Number(O.charLength||0),h=this.inferWordLength(Z,S),b=Number.isFinite(C)&&C>0&&C<=a3&&S+C<=Z.length?C:h,d=Z.substring(S,Math.min(Z.length,S+b)).trim(),VZ=Q+S,r=X(VZ),s=X(VZ+b-1)+1-r;m9.debug(`word boundary "${d}" at ${r}`),this.onWordBoundary(d,r,s)},$=setTimeout(()=>{if(U||K||J!==this.speakRunId)return;A(!1,N("timedOut")),speechSynthesis.cancel()},u9);try{speechSynthesis.speak(B)}catch(O){A(!1,O instanceof Error?O:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPaused)return;if(this._isPlaying)speechSynthesis.pause(),this._isPaused=!0;else if(this.activeRunId===this.speakRunId)this._isPaused=!0}resume(){if(!this._isPaused)return;if(this._isPaused=!1,this._isPlaying)speechSynthesis.resume();this.releaseHold()}stop(){let Z=this.utterance,Q=this._isPlaying||Z!==null;if(this.speakRunId+=1,this.activeRunId=null,this.settlePendingChunk?.(),this.settlePendingGap?.(),Q)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1,this.releaseHold()}updateSettings(Z){if(!this.config)this.config={};if(Z.rate!==void 0)this.config.rate=Z.rate;if(Z.pitch!==void 0)this.config.pitch=Z.pitch;if(Z.voice!==void 0)this.config.voice=Z.voice;if(Z.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Z.providerOptions||{}}}onWordBoundary}var X2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),i9=(Z)=>Z&&typeof Z==="object"?Z:{},WZ=(Z,Q)=>Z===void 0?Q:Z,s9=(Z)=>c0(Z)==="server"&&Z.serverProvider==="custom"?"custom":"pie",G2=(Z)=>typeof Z==="string"&&X2.has(Z)?Z:"left-aligned",GY=Object.freeze([{rate:0.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);var jY=Object.freeze([0.8,1,1.25]);var j2=(Z)=>{let Q={...Z,layoutMode:G2(Z.layoutMode)};if(Z.backend!=="server")return Q;let J={...Q,apiEndpoint:WZ(Q.apiEndpoint,"/api/tts"),transportMode:WZ(Q.transportMode,s9(Z)),endpointValidationMode:WZ(Q.endpointValidationMode,"voices"),includeAuthOnAssetFetch:WZ(Q.includeAuthOnAssetFetch,!1),rate:WZ(Q.rate,1),language:WZ(Q.language,"en-US")};if(Z.serverProvider==="polly")return{...J,engine:WZ(J.engine,"neural"),format:WZ(J.format,"mp3"),speechMarksMode:WZ(J.speechMarksMode,"word+sentence")};return J},U7=(Z)=>{let{enabled:Q,provider:J,...Y}=i9(Z);return j2(Y)},c0=(Z)=>Z.backend||"browser",$7=(Z)=>{let Q=c0(Z)==="server"?Z.serverProvider:void 0,J=Q==="polly",Y=Z.transportMode||s9(Z),X=BZ(Z.mathSpeech);return{voice:Z.defaultVoice,rate:Z.rate,pitch:Z.pitch,providerOptions:{...i9(Z.providerOptions),...Z.language?{locale:Z.language}:{},...J&&Z.engine?{engine:Z.engine}:{},...J&&typeof Z.sampleRate==="number"?{sampleRate:Z.sampleRate}:{},...J&&Z.format?{format:Z.format}:{},...J?{speechMarkTypes:Z.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...Y==="custom"&&typeof Z.cache==="boolean"?{cache:Z.cache}:{},...Y==="custom"&&Z.speedRate?{speedRate:Z.speedRate}:{},...Y==="custom"&&Z.lang_id?{lang_id:Z.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Z.apiEndpoint,provider:Q,language:Z.language,transportMode:Y,endpointMode:Z.endpointMode,endpointValidationMode:Z.endpointValidationMode,includeAuthOnAssetFetch:Z.includeAuthOnAssetFetch,assetOrigins:Z.assetOrigins,credentials:Z.credentials,headers:Z.headers,...typeof Z.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Z.mathTokenHighlighting}:{}}};import{createPieLogger as B2,isGlobalDebugEnabled as W2}from"@pie-players/pie-players-shared/pie";var aZ=B2("ToolProviderRegistry",W2);function tZ(Z){let Q=Z&&typeof Z==="object"?Z.backend:void 0;return typeof Q==="string"&&Q?Q:"unknown"}class d0{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Z,Q,J){try{await Z.onTelemetry?.(Q,J)}catch(Y){console.warn("[ToolProviderRegistry] Telemetry callback failed:",Y)}}register(Z,Q){let J=this.providers.get(Z),Y=this.initializationPromises.get(Z);if(this.providers.set(Z,Q.provider),this.configs.set(Z,Q),this.initialized.set(Z,!1),this.initializationPromises.delete(Z),J)if(Y)Y.catch(()=>{}).then(()=>this.destroyProvider(Z,J));else this.destroyProvider(Z,J);if(aZ.debug(`${J?"Replaced":"Registered"} provider "${Z}" (${Q.provider.providerName})`),Q.lazy===!1)this.initialize(Z).catch((X)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Z}":`,X)})}async initialize(Z){if(this.initialized.get(Z))return;let Q=this.initializationPromises.get(Z);if(Q)return Q;let J=this.providers.get(Z),Y=this._doInitialize(Z);this.initializationPromises.set(Z,Y);try{await Y}catch(X){if(!this.isReplaced(Z,J))throw X}finally{if(this.initializationPromises.get(Z)===Y)this.initializationPromises.delete(Z)}if(this.isReplaced(Z,J))return this.initialize(Z)}isReplaced(Z,Q){let J=this.providers.get(Z);return J!==void 0&&J!==Q}destroyProvider(Z,Q){try{Q.destroy()}catch(J){console.warn(`[ToolProviderRegistry] Failed to destroy provider "${Z}":`,J)}}async _doInitialize(Z){let Q=this.providers.get(Z),J=this.configs.get(Z);if(!Q||!J)throw Error(`[ToolProviderRegistry] Provider "${Z}" not registered`);let Y={...J.config},X=Date.now();if(await this.emitTelemetry(J,"pie-tool-init-start",{toolId:Z,backend:tZ(Y),operation:"provider-initialize"}),Q.requiresAuth&&J.authFetcher){let G=Date.now();await this.emitTelemetry(J,"pie-tool-backend-call-start",{toolId:Z,backend:tZ(Y),operation:"auth-fetch"}),aZ.debug(`Fetching auth for "${Z}"...`);try{let j=await J.authFetcher();Y={...Y,...j},await this.emitTelemetry(J,"pie-tool-backend-call-success",{toolId:Z,backend:tZ(Y),operation:"auth-fetch",duration:Date.now()-G})}catch(j){throw await this.emitTelemetry(J,"pie-tool-backend-call-error",{toolId:Z,backend:tZ(Y),operation:"auth-fetch",duration:Date.now()-G,errorType:"ProviderAuthFetchError",message:j instanceof Error?j.message:String(j)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Z}":`,j),Error(`Failed to fetch auth credentials for provider "${Z}"`)}}try{if(await Q.initialize(Y),this.providers.get(Z)===Q)this.initialized.set(Z,!0);await this.emitTelemetry(J,"pie-tool-init-success",{toolId:Z,backend:tZ(Y),operation:"provider-initialize",duration:Date.now()-X}),aZ.debug(`Provider "${Z}" initialized`)}catch(G){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Z,backend:tZ(Y),operation:"provider-initialize",duration:Date.now()-X,errorType:"ProviderInitializationError",message:G instanceof Error?G.message:String(G)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Z}":`,G),G}}async getProvider(Z,Q=!0){let J=this.providers.get(Z);if(!J)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Z,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Z}" not registered`);if(Q&&!this.initialized.get(Z))aZ.debug("Auto-initializing provider:",Z),await this.initialize(Z);return J}getProvidersByCategory(Z){return Array.from(this.providers.entries()).filter(([Q,J])=>J.category===Z).map(([Q])=>Q)}getProviderIds(){return Array.from(this.providers.keys())}has(Z){return this.providers.has(Z)}isInitialized(Z){return this.initialized.get(Z)===!0}isInitializing(Z){return this.initializationPromises.has(Z)}async unregister(Z){let Q=this.providers.get(Z);if(Q){let J=this.initializationPromises.get(Z);if(J){try{await J}catch{}if(this.providers.get(Z)!==Q)return}this.destroyProvider(Z,Q),this.providers.delete(Z),this.configs.delete(Z),this.initialized.delete(Z),this.initializationPromises.delete(Z),aZ.debug(`Unregistered provider "${Z}"`)}}async destroy(){let Z=Array.from(this.providers.keys());await Promise.all(Z.map((Q)=>this.unregister(Q))),aZ.debug("Registry destroyed")}}class F7{onTargetFailure;targets=new Set;changeListeners=new Set;constructor(Z=(Q,J,Y)=>console.error(`[ToolRequestRegistry] "${Q}" ${J} failed:`,Y)){this.onTargetFailure=Z}registerTarget(Z){return this.targets.add(Z),this.notifyTargetsChange(),()=>{if(!this.targets.delete(Z))return;this.notifyTargetsChange()}}canRequest(Z,Q,J){return this.findTarget(Z,Q,J)!==null}request(Z){let Q=this.findTarget(Z.toolId,Z.level,Z.scopeId);if(!Q)return!1;try{Q.open(Z.toolId,Z.params)}catch(J){return this.onTargetFailure(Z.toolId,"tool-request-open",J),!1}return!0}onTargetsChange(Z){return this.changeListeners.add(Z),()=>{this.changeListeners.delete(Z)}}findTarget(Z,Q,J){let Y=this.findTargetAtLevel(Z,Q??"section",J);if(Y||Q!==void 0)return Y;for(let X of this.targets){if(X.level==="section")continue;if(J!==void 0&&X.scopeId!==J)continue;if(this.hostsTool(X,Z))return X}return null}findTargetAtLevel(Z,Q,J){for(let Y of this.targets){if(Y.level!==Q)continue;if(J!==void 0&&Y.scopeId!==J)continue;if(this.hostsTool(Y,Z))return Y}return null}hostsTool(Z,Q){try{return Z.hostsTool(Q)===!0}catch(J){return this.onTargetFailure(Q,"tool-request-host-check",J),!1}}notifyTargetsChange(){for(let Z of this.changeListeners)try{Z()}catch(Q){console.warn("[ToolRequestRegistry] Target change listener threw:",Q)}}dispose(){this.targets.clear(),this.changeListeners.clear()}}function l0(Z,Q,J){let Y=Q?.settings,X=J?.settings.toolParameters?.[Z]??Y?.toolParameters?.[Z];return X&&typeof X==="object"&&!Array.isArray(X)?X:void 0}class z7{provenance;stepCounter=0;constructor(Z){this.provenance={contextId:Z,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Z,Q){let J={id:Q.id,name:Q.name??Q.id};switch(Z){case"organization":this.provenance.sources.organization={...J,pnpDefaults:Q.config};break;case"assessment":this.provenance.sources.assessment={...J,settings:Q.config};break;case"section":this.provenance.sources.section={...J,settings:Q.config};break;case"item":this.provenance.sources.item={...J,settings:Q.config};break;case"student":this.provenance.sources.student={id:Q.id,pnpProfile:Q.config};break;case"host":this.provenance.sources.host={id:Q.id,config:Q.config};break}return this}addDecision(Z){let Q={step:++this.stepCounter,precedence:Z.precedence,rule:Z.rule,featureId:Z.featureId,action:Z.action,source:{type:Z.sourceType,id:Z.sourceId,name:Z.sourceName},reason:Z.reason,value:Z.value,timestamp:new Date};this.provenance.decisionLog.push(Q);let J=this.provenance.features.get(Z.featureId);if(!J)J={featureId:Z.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Z.featureId,J);if(J.allDecisions.push(Q),Z.action==="advisory"){if(J.finalState==="not-configured")J.finalState="advisory-only"}else if(Z.action!=="skip"){if(!J.winningDecision||Q.precedence<J.winningDecision.precedence)J.winningDecision=Q,J.finalState=Q.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Z.sourceType]=(this.provenance.summary.bySource[Z.sourceType]||0)+1,this.provenance.summary.byRule[Z.rule]=(this.provenance.summary.byRule[Z.rule]||0)+1,this}reconcileFinalStates(Z){for(let Q of Z){let J=this.provenance.features.get(Q);if(!J){J={featureId:Q,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(Q,J);continue}J.finalState="enabled"}for(let Q of this.provenance.features.values()){if(Z.has(Q.featureId))continue;let J=Q.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),Y=Q.allDecisions.some((X)=>X.action==="advisory");if(J)Q.finalState="blocked";else if(Y)Q.finalState="advisory-only";else Q.finalState="not-configured"}return this}build(){for(let Z of this.provenance.features.values())Z.explanation=V2(Z);for(let Z of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Z.finalState==="enabled")this.provenance.summary.enabled++;else if(Z.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function V2(Z){if(!Z.winningDecision){if(Z.finalState==="advisory-only"){let G=Z.allDecisions.find((j)=>j.action==="advisory");return G?`Feature "${Z.featureId}" was kept in its host-decided state; ${G.reason}`:`Feature "${Z.featureId}" carries an advisory note.`}return`Feature "${Z.featureId}" was not configured at any level.`}let Q=Z.winningDecision,J=Q.source.name||Q.source.type,Y=`Feature "${Z.featureId}" is ${Z.finalState}.
215
+ `,m8=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet-v2"),u8=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet-v2-adopted"),p8=(Z)=>!!Z&&typeof Z.replaceSync==="function",b6=()=>{let Z=globalThis,Q=Z[m8];if(p8(Q))return Q;let J=globalThis.CSSStyleSheet;if(typeof J!=="function")return null;try{let Y=new J;if(!p8(Y))return null;return Y.replaceSync(c8),Z[m8]=Y,Y}catch{return null}},zZ=(Z)=>{let Q=Z?.getRootNode?.();if(!p(Q))return;let J=Q,Y=J.adoptedStyleSheets;if(!Y||typeof Y!=="object")return;let X=Array.from(Y),G=J[u8];if(G&&X.includes(G))return;let j=b6();if(!j)return;try{J.adoptedStyleSheets=[...X,j],J[u8]=j}catch{}},i5="pie-tts-word",l5="pie-tts-sentence",r0=(Z)=>`pie-annotation-${Z}`,E0=(Z)=>{let Q=CSS.highlights.get(Z);if(Q)return Q;let J=new Highlight;return CSS.highlights.set(Z,J),J},AZ=(Z,Q)=>{let J=CSS.highlights.get(Z);if(!J)return;for(let Y of Q)J.delete(Y)},g8=(Z)=>{let Q=Z[0]?.startContainer;if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:i(Q)},j0={source:null,override:null};class HZ{ttsWordRanges=new Set;ttsSentenceRanges=new Set;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;ttsStyleSource=null;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;constructor(){if(this.rangeSerializer=new c5,typeof CSS>"u"||!("highlights"in CSS)){console.warn("CSS Custom Highlight API not supported (SSR or unsupported browser)");return}this.supported=!0,this.initializeHighlights(),this.registerStyles(),this.applyAdaptiveTTSStyle(),this.setupThemeObservation()}setupThemeObservation(){if(typeof document>"u")return;if(typeof MutationObserver>"u")return;let Z=document.getElementsByTagName("pie-theme"),Q=new WeakSet,J=()=>{let X=!1;for(let G of Z){if(Q.has(G))continue;Q.add(G),Y.observe(G,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]}),X=!0}return X},Y=new MutationObserver((X)=>{if(J()||X.some((j)=>j.type==="attributes"))this.applyAdaptiveTTSStyle()});this.themeObserver=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]}),Y.observe(document,{childList:!0,subtree:!0}),J()}parseColor(Z){if(!Z)return null;let Q=Z.trim();if(!Q)return null;let J=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(Q);if(J){let X=J[1];if(X.length===3)return[parseInt(X[0]+X[0],16),parseInt(X[1]+X[1],16),parseInt(X[2]+X[2],16)];return[parseInt(X.slice(0,2),16),parseInt(X.slice(2,4),16),parseInt(X.slice(4,6),16)]}let Y=/^rgba?\((.+)\)$/i.exec(Q);if(Y){let G=Y[1].replace(/\//g,",").split(/[,\s]+/).map((q)=>q.trim()).filter(Boolean),j=Number(G[0]),B=Number(G[1]),V=Number(G[2]);if(Number.isFinite(j)&&Number.isFinite(B)&&Number.isFinite(V))return[j,B,V]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=Q,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let G=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let j=G.trim();if(j&&j!==Q)return this.parseColor(G)}}return null}relativeLuminance([Z,Q,J]){let Y=(B)=>{let V=B/255;return V<=0.03928?V/12.92:((V+0.055)/1.055)**2.4},X=Y(Z),G=Y(Q),j=Y(J);return 0.2126*X+0.7152*G+0.0722*j}contrastRatio(Z,Q){let J=this.relativeLuminance(Z),Y=this.relativeLuminance(Q),X=Math.max(J,Y),G=Math.min(J,Y);return(X+0.05)/(G+0.05)}blend(Z,Q,J){return[Math.round(Z[0]*J+Q[0]*(1-J)),Math.round(Z[1]*J+Q[1]*(1-J)),Math.round(Z[2]*J+Q[2]*(1-J))]}resolveAdaptiveTTSStyle(Z){let Q=[255,235,59],J=[17,24,39],Y=[255,255,255],X=Z||(typeof document<"u"?document.documentElement:null),G=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,j=this.parseColor(G?.getPropertyValue("--pie-background")||G?.backgroundColor)||Y,B=this.parseColor(G?.getPropertyValue("--pie-text"))||J,V=j0.override,q=V?this.parseColor(V.color)||Q:this.parseColor(G?.getPropertyValue("--pie-missing"))||Q,U=V?[Math.max(0.3,Math.min(0.95,V.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],$=U[U.length-1],z=-1/0;for(let r of U){let q0=this.blend(q,j,r),Z0=this.contrastRatio(q0,j),M0=this.contrastRatio(q0,B),O0=Z0*1.2+M0*0.8;if(Z0>=1.25&&M0>=2.4){$=r;break}if(O0>z)z=O0,$=r}let A=Math.max(0.24,Math.min(0.85,$*0.55)),O=Math.max(0.55,Math.min(0.95,$+0.2)),P=Math.max(0.22,Math.min(0.6,$*0.45)),D=B,N=this.blend(D,j,O),M=this.contrastRatio(N,j),C=this.relativeLuminance(j)>0.45?[0,0,0]:[255,255,255],E=M>=1.35?D:C,v=`rgba(${q[0]}, ${q[1]}, ${q[2]}, ${$})`,S=`rgba(${q[0]}, ${q[1]}, ${q[2]}, ${A})`,g=`rgba(${E[0]}, ${E[1]}, ${E[2]}, ${O})`,e=`rgba(${E[0]}, ${E[1]}, ${E[2]}, ${P})`;return{wordHighlight:v,sentenceHighlight:S,wordUnderline:g,wordShadow:e}}applyAdaptiveTTSStyle(Z){if(typeof document>"u")return;if(Z)this.ttsStyleSource=Z,j0.source=Z;let Q=Z??(j0.source?.isConnected?j0.source:null),J=this.resolveAdaptiveTTSStyle(Q),Y=document.documentElement.style,X=[["--pie-tts-word-highlight",J.wordHighlight],["--pie-tts-sentence-highlight",J.sentenceHighlight],["--pie-tts-line-highlight",J.sentenceHighlight],["--pie-tts-word-underline",J.wordUnderline],["--pie-tts-word-shadow",J.wordShadow]];for(let[G,j]of X){if(Y.getPropertyValue?.(G)===j)continue;Y.setProperty(G,j)}}initializeHighlights(){if(!this.supported)return;E0(i5),E0(l5);for(let Z of Object.values(hZ))E0(r0(Z))}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById(d5))return;let Z=document.createElement("style");Z.id=d5,Z.textContent=c8,document.head.appendChild(Z)}highlightTTSWord(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(g8(Z)),this.clearTTSWord();let Q=E0(i5);for(let J of Z)zZ(J.startContainer),Q.add(J),this.ttsWordRanges.add(J);this.highlightTTSWordElementFallbacks(Z.filter((J)=>J.startContainer!==J.endContainer||J.startContainer.nodeType!==Node.TEXT_NODE))}highlightTTSWordElement(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(Z),zZ(Z),this.clearTTSWord(),Z.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Z)}highlightTTSSentence(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(g8(Z)),this.clearTTSSentence();let Q=E0(l5);for(let J of Z)zZ(J.startContainer),Q.add(J),this.ttsSentenceRanges.add(J);this.highlightTTSElementFallbacks(Z)}highlightTTSSentenceElements(Z){if(!this.supported)return;this.applyAdaptiveTTSStyle(Z[0]||null),this.clearTTSSentence();for(let Q of Z)zZ(Q),Q.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(Q)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Z){if(typeof Element>"u")return;this.highlightElementFallbacks(Z,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,HZ.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Z){if(typeof Element>"u")return;this.highlightElementFallbacks(Z,"data-pie-tts-word-element",this.ttsWordElementHighlights,HZ.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Z,Q,J,Y){let X=(G)=>G.nodeType===Node.ELEMENT_NODE?G:i(G);for(let G of Z){let j=G.commonAncestorContainer,B=p(j)?j:X(j);if(!B)continue;let V=[],q=X(G.startContainer),U=X(G.endContainer);for(let $ of[q,U]){let z=$;while(z){if(z.matches?.(Y))V.push(z);z=i(z)}}if(!p(B)&&B.matches?.(Y))V.push(B);V.push(...Array.from(B.querySelectorAll(Y)));for(let $ of new Set(V)){try{if(!G.intersectsNode($)&&!J0($,q)&&!J0($,U))continue}catch{continue}$.setAttribute(Q,"true"),J.add($)}}}clearTTSWord(){if(!this.supported)return;AZ(i5,this.ttsWordRanges),this.ttsWordRanges.clear();for(let Z of this.ttsWordElementHighlights)Z.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.supported)return;AZ(l5,this.ttsSentenceRanges),this.ttsSentenceRanges.clear();for(let Z of this.ttsSentenceElementHighlights)Z.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){if(this.clearTTSWord(),this.clearTTSSentence(),j0.source===this.ttsStyleSource)j0.source=null;this.ttsStyleSource=null}addAnnotation(Z,Q=hZ.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,Y=Z.cloneRange();zZ(Y.startContainer);let X={id:J,range:Y,type:s5.ANNOTATION,color:Q,timestamp:Date.now()};if(this.annotations.set(J,X),this.supported)E0(r0(Q)).add(Y);return J}removeAnnotation(Z){let Q=this.annotations.get(Z);if(!Q){console.warn(`[HighlightCoordinator] Annotation ${Z} not found`);return}if(this.supported)AZ(r0(Q.color),[Q.range]);this.annotations.delete(Z)}clearAnnotations(){if(this.supported)for(let Z of this.annotations.values())AZ(r0(Z.color),[Z.range]);this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Z){return this.annotations.get(Z)??null}changeAnnotationColor(Z,Q){let J=this.annotations.get(Z);if(!J)return;let Y=J.color;if(Y===Q)return;if(J.color=Q,this.supported)AZ(r0(Y),[J.range]),E0(r0(Q)).add(J.range)}exportAnnotations(Z=document.body){return this.getAnnotations().map((Q)=>({...this.rangeSerializer.serialize(Q.range,Z),id:Q.id,color:Q.color,timestamp:Q.timestamp}))}importAnnotations(Z,Q=document.body){let J=0;for(let Y of Z){let X=this.rangeSerializer.deserialize(Y,Q);if(X)this.addAnnotation(X,Y.color),J++}return J}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}updateTTSHighlightStyle(Z,Q){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById(d5))return;let X=((G)=>{let j=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(G);return j?{r:parseInt(j[1],16),g:parseInt(j[2],16),b:parseInt(j[3],16)}:null})(Z);if(!X)return;j0.override={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,Q)),owner:this},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),j0.override?.owner===this)j0.override=null;this.themeObserver?.disconnect(),this.themeObserver=null}}import{applyMediaFragment as U2,enforceMediaFragment as $2}from"@pie-players/pie-players-shared/media";import{createPieLogger as F2,isTtsDebugEnabled as Q1}from"@pie-players/pie-players-shared/pie";import{isUnsupportedMediaAssetVersion as E6,normalizeMediaFragment as S6,normalizeMediaSources as y6,trimmedOrUndefined as T6}from"@pie-players/pie-players-shared/media";function d8(Z){if(!Z)return null;let Q=Z.payload;if(!Q||typeof Q!=="object")return null;let J=Q.media;if(!J||typeof J!=="object")return console.warn("[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech"),null;if(E6(J.version))return console.warn(`[spoken-audio] card's media declares version ${String(J.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`),null;if(J.kind!==void 0&&J.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${J.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let Y=y6(J.sources);if(Y.length===0)return console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null;return{sources:Y,fragment:S6(Q.fragment),label:T6(J.label)}}var x6="[data-pie-shell-root]";var i8=(Z)=>Z?vZ(Z,x6):null;var mZ="en-US",n5=(Z,Q)=>{let J=!Z?null:Z.nodeType===1?Z:i(Z);while(J){let Y=J.getAttribute("lang");if(Y!==null)return Y.trim()||void 0;if(Q&&J===Q)return;J=i(J)}return},l8=(Z)=>{let Q;for(let J of Z.querySelectorAll("[lang]")){let Y=J.parentElement?.closest("[lang]");if(Y&&Y!==Z&&Z.contains(Y))continue;let X=J.getAttribute("lang")?.trim();if(!X)return;if(Q===void 0)Q=X;else if(Q.toLowerCase()!==X.toLowerCase())return}return Q},r5=(Z,Q={})=>{let J=Q.boundary!==void 0?Q.boundary:i8(Z);return(J?n5(Z,J):void 0)||Q.contentLanguage?.trim()||void 0},s8=(Z,Q={})=>r5(Z,Q)??mZ;var T=(Z)=>Z.trim().replace(/\s+/g," "),o8=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,uZ=(Z)=>{if(Z.hidden)return!0;if(Z.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Z.getAttribute("aria-hidden")==="true")return!0;if(Z.hasAttribute("inert"))return!0;let Q=Z.classList;if(Q?.contains("sr-only")||Q?.contains("pie-sr-only")||Q?.contains("visually-hidden"))return!0;if(typeof window<"u"){let J=window.getComputedStyle(Z);if(J.display==="none"||J.visibility==="hidden")return!0;let Y=Number.parseFloat(J.width||"0"),X=Number.parseFloat(J.height||"0"),G=Number.isFinite(Y)&&Number.isFinite(X)&&Y<=1&&X<=1,j=J.clipPath.includes("inset(50%")||J.clipPath.includes("inset(100%")||J.clip.includes("rect(0px, 0px, 0px, 0px)")||J.clip.includes("rect(0 0 0 0)");if((J.position==="absolute"||J.position==="fixed")&&G&&(J.overflow==="hidden"||j))return!0;if(J.opacity==="0"&&G)return!0}return!1},a0=(Z,Q)=>{let J=Z.nodeType===1?Z:d(Z);while(J){if(uZ(J))return!0;if(Q&&J===Q)break;J=d(J)}return!1},n8="data-tts-suppress",t8=new Set(["computer-read-aloud","all"]),r8=new Set([...t8,"screen-reader"]),a8=new Set,k6=(Z)=>{let Q=Z.getAttribute?.(n8);if(Q===null||Q===void 0)return!1;let J=Q.trim().toLowerCase();if(t8.has(J))return!0;if(r8.has(J))return!1;if(!a8.has(J))a8.add(J),console.warn(`[tts] ${n8}="${Q}" is not one of ${Array.from(r8).join(", ")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`);return!0},pZ=(Z,Q)=>{let J=Z.nodeType===1?Z:d(Z);while(J){if(k6(J))return!0;if(Q&&J===Q)break;J=d(J)}return!1},z0=(Z,Q)=>a0(Z,Q)||pZ(Z),a5=(Z,Q)=>{if(typeof Z.intersectsNode!=="function")return{text:Z.toString(),filtered:!1};let J=[],Y=!1;for(let X of C0(Q))if(G0(Z,X))if(z0(X,Q))Y=!0;else J.push(o5(X,Z));return{text:J.join(""),filtered:Y}},o5=(Z,Q)=>{let J=Z.textContent||"",Y=Z===Q.startContainer?Q.startOffset:0,X=Z===Q.endContainer?Q.endOffset:J.length;return J.slice(Y,X)},DZ=(Z,Q,J)=>{let Y=null,X=null;for(let G of C0(Q)){if(z0(G,J))continue;let j=G.textContent||"",B=j.search(/\S/);if(B===-1)continue;Y??={node:G,offset:B},X={node:G,offset:j.trimEnd().length-1}}if(!Y||!X)return G0(Z,Q);return FZ(Z,Y.node,Y.offset)&&FZ(Z,X.node,X.offset)},t5=(Z,Q,J)=>{if(!Z||!Q)return!1;if(/\s/.test(Z)||/\s/.test(Q))return!1;let Y=J?.boundarySpacingMode??"segmenterPreferred";if(Y==="none")return!1;if(Y==="segmenterPreferred")try{let j=globalThis.Intl?.Segmenter;if(typeof j==="function"){let B=new j(J?.locale,{granularity:"word"});if(Array.from(B.segment(`${Z}${Q}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Z),G=/[A-Za-z0-9]/.test(Q);return X&&G},S0=(Z,Q)=>{let J=new Map;if(typeof document>"u")return{text:"",map:J};let Y=[],X=0,G=!0,j=!1,B=null,V=null;for(let U of C0(Z))if(d(U)&&!z0(U,Z)){let z=U.textContent||"",A=z.match(/\S/),O=A?A[0]:null;if(!G&&!j&&t5(V,O,Q)){if(Y.push(" "),B)J.set(X,B);X++,j=!0}for(let P=0;P<z.length;P++){let D=z[P],N=/\s/.test(D);if(G){if(!N)G=!1,Y.push(D),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++,j=!1,V=D}else if(N){if(!j)Y.push(" "),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++;j=!0}else Y.push(D),J.set(X,{node:U,offset:P}),B={node:U,offset:P},X++,j=!1,V=D}}let q=Y.join("").trimEnd();while(J.has(q.length))J.delete(q.length);return{text:q,map:J}};var f6=/^\s*<speak[\s/>]/i,cZ=(Z)=>f6.test(Z),I6=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),e8=new Set(["audio","phoneme"]),Q9=(Z)=>Z.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),gZ=(Z,Q,J)=>{for(let Y=0;Y<Q.length;Y++)Z.push({char:Q[Y],rawOffset:J===null?null:J+Y})},v6=(Z,Q,J)=>{let Y=Q.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!Y)return 0;return gZ(Z,Q9(Y[0]),J),Y[0].length},Z9=(Z)=>{Z.push({char:" ",rawOffset:null})},h6=(Z)=>{let Q=new Map,J=[],Y=!0;for(let X of Z){if(/\s/.test(X.char)){if(!Y&&J.length>0){if(J.push(" "),X.rawOffset!==null)Q.set(X.rawOffset,J.length-1)}Y=!0;continue}if(J.push(X.char),X.rawOffset!==null)Q.set(X.rawOffset,J.length-1);Y=!1}while(J.length>0&&J[J.length-1]===" ")J.pop();for(let[X,G]of Q)if(G>=J.length)Q.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Q}},m6=(Z)=>{return Z.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},u6=(Z,Q)=>{let J=new RegExp(`${Q}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),Y=Z.match(J);return Q9(Y?.[2]??Y?.[3]??"")||null},dZ=(Z)=>{let Q=[],J=!1,Y=!1,X=0;while(X<Z.length){let j=Z[X];if(j!=="<"){if(j==="&"){let z=v6(Q,Z,X);if(z>0){X+=z;continue}}gZ(Q,j,X),X++;continue}let B=Z.indexOf(">",X+1);if(B<0){gZ(Q,j,X),X++;continue}Y=!0;let V=Z.slice(X,B+1),q=m6(V),U=/^<\s*\//.test(V),$=/\/\s*>$/.test(V);if(!U&&q==="sub"){let z=u6(V,"alias");if(!z){J=!0,X=B+1;continue}gZ(Q,z,null);let A=Z.toLowerCase().indexOf("</sub>",B+1);X=A>=0?A+6:B+1;continue}if(!U&&q==="break"){Z9(Q),X=B+1;continue}if(!U&&e8.has(q)){if(J=!0,$){X=B+1;continue}}if(q&&!I6.has(q)&&!e8.has(q)&&q!=="break"&&q!=="sub")J=!0;if(!U&&(q==="p"||q==="s"))Z9(Q);X=B+1}let G=h6(Q);return{spokenText:T(G.text),rawToSpokenOffsetMap:G.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:Y}};var p6=o8(),g6=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),c6=(Z)=>{let Q=Z.toLowerCase();return g6.get(Q)||Q},Q7=(Z)=>{let Q=[];for(let J of Z.matchAll(p6)){let Y=J[0],X=J.index??0;Q.push({text:Y,normalized:c6(Y),start:X,end:X+Y.length})}return Q},d6=(Z)=>Q7(Z).map((Q,J)=>({...Q,id:`speech-token-${J}`,sourceStart:Q.start,sourceEnd:Q.end,coordinateSystem:"normalized-speech"})),y0=(Z)=>{let Q=dZ(Z.speechText);return{speechText:Z.speechText,spokenText:Q.spokenText,tokens:d6(Q.spokenText),rawToSpokenOffsetMap:Q.rawToSpokenOffsetMap,boundaryOffsetSpace:Q.unsupportedSemantic?"unsupported":Q.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Q.unsupportedSemantic,hasMarkup:Q.hasMarkup}},J7=(Z)=>Boolean(Z&&/^<[^>]+>$/.test(Z.trim())),o0=(Z)=>{if(!Z||J7(Z))return null;return y0({speechText:Z}).tokens[0]?.normalized??null},i6=(Z,Q)=>Z.find((J)=>J.start<=Q&&Q<J.end)||null,l6=(Z,Q)=>{let J=Z.rawToSpokenOffsetMap.get(Q);if(J!==void 0)return J;for(let Y=Q;Y<Z.speechText.length;Y++){let X=Z.rawToSpokenOffsetMap.get(Y);if(X!==void 0)return X;if(Z.speechText[Y]===">")break}return null},e5=(Z,Q,J)=>{if(Q===null)return null;let Y=i6(Z.tokens,Q);if(!Y)return null;return{token:Y,start:Q,length:Math.max(1,Math.min(J,Y.end-Q)),confidence:0.75}},Z7=(Z,Q)=>Boolean(Z&&Q&&Z.token.normalized===Q),Y7=(Z)=>{if(Z.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Z.position)||J7(Z.boundaryWord))return null;let Q=Math.max(1,Number.isFinite(Z.length)?Z.length:1),J=o0(Z.boundaryWord),Y=e5(Z.tokenization,l6(Z.tokenization,Z.position),Q),X=e5(Z.tokenization,Z.position>=0&&Z.position<Z.tokenization.spokenText.length?Z.position:null,Q);if(Z7(Y,J))return{...Y,confidence:1};if(Z7(X,J))return{...X,confidence:1};if(J)return null;return Z.tokenization.boundaryOffsetSpace==="raw-ssml"?Y||X:X||Y},J9=(Z)=>{if(Z.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Z.position)||J7(Z.boundaryWord))return null;let Q=Math.max(1,Number.isFinite(Z.length)?Z.length:1),J=o0(Z.boundaryWord),Y=e5(Z.tokenization,Z.position>=0&&Z.position<Z.tokenization.spokenText.length?Z.position:null,Q);if(Z7(Y,J))return{...Y,confidence:1};if(J)return null;return Y};var X7=10,s6=0.12,n6=[{phrase:["plus","or","minus"],visible:"±",score:8},{phrase:["square","root"],visible:"√",score:8},{phrase:["divided","by"],visible:"/",score:7},{phrase:["all","over"],visible:"/",score:7},{phrase:["equals"],visible:"=",score:7},{phrase:["equal"],visible:"=",score:7},{phrase:["times"],visible:"⁢",score:7},{phrase:["multiplied","by"],visible:"⁢",score:7},{phrase:["over"],visible:"/",score:6},{phrase:["squared"],visible:"²",score:6},{phrase:["squared"],visible:"2",score:4},{phrase:["negative"],visible:"-",score:5},{phrase:["minus"],visible:"-",score:5},{phrase:["plus"],visible:"+",score:5}],r6=(Z,Q)=>{let J=[];for(let Y=0;Y<Z.length;Y++){for(let X=0;X<Q.length;X++)if(Z[Y].normalized===Q[X].normalized)J.push({spokenStartToken:Y,spokenEndToken:Y+1,visibleToken:X,score:X7});for(let X of n6){let G=Z.slice(Y,Y+X.phrase.length);if(G.length!==X.phrase.length)continue;if(!G.every((j,B)=>j.normalized===X.phrase[B]))continue;for(let j=0;j<Q.length;j++){if(Q[j].text!==X.visible)continue;J.push({spokenStartToken:Y,spokenEndToken:Y+X.phrase.length,visibleToken:j,score:X.score})}}}return J},a6=(Z,Q)=>{let J=r6(Z,Q).sort((V,q)=>Z[V.spokenStartToken].start-Z[q.spokenStartToken].start||Q[V.visibleToken].start-Q[q.visibleToken].start),Y=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let V=0;V<J.length;V++){let q=J[V];Y[V]=q.score;for(let U=0;U<V;U++){let $=J[U];if($.spokenEndToken<=q.spokenStartToken&&$.visibleToken<q.visibleToken){let z=q.spokenStartToken-$.spokenEndToken,A=q.visibleToken-$.visibleToken-1,O=Math.max(0,Math.abs(z-A)-2),P=Y[U]+q.score-O;if(P>Y[V])Y[V]=P,X[V]=U}}}let G=-1;for(let V=0;V<Y.length;V++)if(G<0||Y[V]>Y[G])G=V;if(G<0)return[];let j=[],B=G;while(B>=0)j.unshift(J[B]),B=X[B];return j.map((V)=>{let q=Z[V.spokenStartToken],U=Z[V.spokenEndToken-1],$=Q[V.visibleToken];return{spokenStart:q.start,spokenEnd:U.end,visibleStart:$.start,visibleEnd:$.end,score:V.score}})},o6=(Z,Q,J)=>{if(Z.length===0)return 0;let Y=Z.length/Math.max(1,Math.min(Q.length,J.length)),X=Z.reduce((G,j)=>G+j.score,0)/Z.length/X7;return Math.min(1,Y*X)},iZ=(Z)=>{let Q=y0({speechText:Z.speechText}),J=T(Z.visibleText),Y=Q.tokens,X=Q7(J),G=Q.unsupportedSemantic?[]:a6(Y,X),j=o6(G,Y,X),B=Q.spokenText===J&&Q.spokenText.length>0,V=G.length===1&&G[0].score===X7&&Y.length<=2&&X.length<=2,q=(G.length>=2||V)&&j>=s6,U=Q.unsupportedSemantic?"region-fallback":B?"exact-word":q?"anchor-span":"region-fallback";return{speech:Q,visibleText:J,playbackMode:U,anchors:G,confidence:j}},Y9=(Z,Q)=>{if(Z.playbackMode==="region-fallback")return null;let J=Z.anchors.find((G)=>G.spokenStart<=Q&&Q<G.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let Y=null,X=null;for(let G of Z.anchors){if(G.spokenEnd<=Q){Y=G;continue}if(G.spokenStart>Q){X=G;break}}if(Y&&X)return{start:Math.min(Y.visibleStart,X.visibleStart),end:Math.max(Y.visibleEnd,X.visibleEnd)};return null};var t6=new Map([["+",["plus"]],["-",["minus","negative"]],["−",["minus","negative"]],["×",["times","multiplied by"]],["÷",["divided by"]],["=",["equals","equal to"]],["≠",["is not equal to","not equal to"]],["≈",["approximately equals"]],["≤",["less than or equal to"]],["≥",["greater than or equal to"]],["<",["less than"]],[">",["greater than"]],["∠",["angle"]],["△",["triangle"]],["□",["box"]],["○",["circle"]],["°",["degrees","degree"]],["%",["percent"]],["'",["prime"]],["′",["prime"]],["•",["times"]],["·",["times"]],["⁢",["times","multiplied by"]]]),e6=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),X9=new Map([["2",["squared"]],["3",["cubed"]]]),Z3=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),Q3=(Z)=>Z.replace(/\s+/g," ").trim(),T0=(Z)=>(Z.localName||Z.tagName||"").toLowerCase(),J3=(Z)=>Z.nodeType===Node.ELEMENT_NODE,t0=(Z)=>Array.from(Z.childNodes).filter(J3),G7=(Z)=>Q3(Z.textContent||""),B0=(Z,Q)=>({type:"element-range",quality:Q,element:Z}),Y3=(Z)=>{switch(Z){case"mi":return"identifier";case"mn":return"number";case"mo":return"operator";case"mtext":case"ms":return"text";case"mspace":return"space";default:return"unknown"}},X3=(Z,Q)=>{if(Q==="operator"){if(Z==="−")return"-";return Z}return Z.toLowerCase()},G3=(Z,Q,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return X9.get(Z)??[];if(Z==="|")return["absolute value"];if(Q==="operator")return t6.get(Z)||[];return[]},x0=(Z)=>{let Q=Z.normalized??X3(Z.text,Z.kind||"unknown");return{id:`math-token-${Z.state.nextId++}`,kind:Z.kind,role:Z.role,text:Z.text,normalized:Q,spokenAliases:G3(Z.text,Z.kind,Z.role),sourceElement:Z.sourceElement,path:Z.path,target:Z.target||B0(Z.sourceElement,"element-range"),optional:Z.optional}},k0=(Z,Q,J="tokens")=>{Z[J].push(Q)},G9=(Z,Q,J)=>{t0(Z).forEach((Y,X)=>W0(Y,Q,`${J}/${T0(Y)}[${X}]`))},j3=(Z,Q,J)=>{let Y=t0(Z);if(Y[0])W0(Y[0],Q,`${J}/numerator`);if(k0(Q,x0({state:Q,kind:"structure",role:"fraction",text:"/",sourceElement:Z,path:J,target:B0(Z,"element-range")})),Y[1])W0(Y[1],Q,`${J}/denominator`)},B3=(Z,Q,J)=>{let Y=Z.getAttribute("open")||"(",X=Z.getAttribute("close")||")";k0(Q,x0({state:Q,kind:"operator",role:Y==="|"?"absolute-value-fence":"open-fence",text:Y,sourceElement:Z,path:`${J}/open`,target:B0(Z,"element-range")})),G9(Z,Q,J),k0(Q,x0({state:Q,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Z,path:`${J}/close`,target:B0(Z,"element-range")}))},W3=(Z,Q,J)=>{let Y=t0(Z);if(Y[0])W0(Y[0],Q,`${J}/base`);let X=Y[1];if(!X)return;let G=G7(X);if(X9.has(G)){k0(Q,x0({state:Q,kind:"structure",role:"superscript",text:G,normalized:G,sourceElement:X,path:`${J}/exponent`,target:B0(Z,"element-range")}));return}W0(X,Q,`${J}/exponent`)},V3=(Z,Q,J,Y)=>{k0(Q,x0({state:Q,kind:"structure",role:Y,text:G7(Z)||Y,normalized:`\x00${Y}`,sourceElement:Z,path:J,target:B0(Z,"element-range")}))},K3=(Z,Q,J)=>{let Y=0;for(let X of t0(Z)){if(T0(X)==="mtr"||T0(X)==="mlabeledtr")Y++,k0(Q,x0({state:Q,kind:"layout",role:"table-row",text:`row-${Y}`,normalized:`row-${Y}`,sourceElement:X,path:`${J}/row[${Y}]`,target:B0(X,"region-fallback")}),"layoutTargets");W0(X,Q,`${J}/${T0(X)}[${Y}]`)}},q3=(Z,Q,J)=>{let Y=G7(Z);if(!Y)return;let X=Y3(T0(Z)),G=X==="operator"?e6.get(Y):void 0,j=G??(X==="operator"&&(Y==="("||Y===")")?"grouping-fence":X);k0(Q,x0({state:Q,kind:X,role:j,text:Y,sourceElement:Z,path:J,target:G&&Z.parentElement?B0(Z.parentElement,"region-fallback"):void 0,optional:Boolean(G)||j==="grouping-fence"}))},W0=(Z,Q,J)=>{let Y=T0(Z);switch(Y){case"annotation":case"annotation-xml":return;case"semantics":{let X=t0(Z).find((G)=>{let j=T0(G);return j!=="annotation"&&j!=="annotation-xml"});if(X)W0(X,Q,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":q3(Z,Q,J);return;case"mfrac":j3(Z,Q,J);return;case"msup":W3(Z,Q,J);return;case"mfenced":B3(Z,Q,J);return;case"mtable":K3(Z,Q,J);return;case"mphantom":return;case"maction":{let X=t0(Z)[0];if(X)W0(X,Q,`${J}/action`);return}default:{let X=Z3.get(Y);if(X){V3(Z,Q,J,X);return}G9(Z,Q,J)}}},j9=(Z)=>{let Q={tokens:[],layoutTargets:[],nextId:0};return W0(Z,Q,"/math"),{tokens:Q.tokens,layoutTargets:Q.layoutTargets,expressionTarget:B0(Z,"region-fallback")}};var B9=(Z)=>{if(!Z.boundary)return null;return Z.alignment.segments.find((J)=>J.speechTokenIds.includes(Z.boundary.token.id))?.target||null};var U3=(Z)=>{let Q=[],J=new Set,Y=(X)=>{let G=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(G.length===0)return;let j=G.join(" ");if(J.has(j))return;J.add(j),Q.push(G)};Y(Z.normalized);for(let X of Z.spokenAliases)Y(X);return Q},W9=(Z,Q,J)=>{let Y=0;for(let X of J){if(X.length<=Y)continue;let G=!0;for(let j=0;j<X.length;j++){let B=Z[Q+j];if(!B||B.normalized.toLowerCase()!==X[j]){G=!1;break}}if(G)Y=X.length}return Y},$3=(Z,Q)=>{let J=[],Y=0;for(let X of Q){let G=U3(X);if(X.optional){let j=W9(Z,Y,G);if(j>0)J.push({speechTokens:Z.slice(Y,Y+j),math:X}),Y+=j;continue}while(Y<Z.length){let j=W9(Z,Y,G);if(j>0){J.push({speechTokens:Z.slice(Y,Y+j),math:X}),Y+=j;break}Y++}}return J},F3=(Z,Q,J)=>{let Y=J.filter((j)=>!j.optional).length,X=Z.filter((j)=>!j.math.optional).length,G=Z.reduce((j,B)=>j+B.speechTokens.length,0);return Y>0&&X===Y&&G===Q.length},z3=(Z)=>Z.map(({speechTokens:Q,math:J})=>({speechTokenIds:Q.map((Y)=>Y.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),V9=(Z)=>{let Q=Z.minExactWordConfidence??0.95,J=$3(Z.speech.tokens,Z.math.tokens),Y=F3(J,Z.speech.tokens,Z.math.tokens)?1:0;return{segments:Y>=Q?z3(J):[],confidence:Y,fallbackTarget:Z.math.expressionTarget}};var e0=(Z)=>{let Q=y0({speechText:Z.speechText}),J=j9(Z.mathElement);return{speech:Q,math:J,result:V9({speech:Q,math:J})}};var K9=(Z,Q)=>{let J=J9({tokenization:Z.speech,position:Q.position,length:Q.length,boundaryWord:Q.boundaryWord});return B9({alignment:Z.result,boundary:J})},q9=(Z,Q)=>{let J=o0(Q.boundaryWord);if(!J)return null;let Y=Z.math.tokens.filter((X)=>X.normalized.toLowerCase()===J||X.spokenAliases.some((G)=>G.toLowerCase()===J));return Y.length===1?Y[0].target:null};var A3=new Set(["math","maction","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","none","semantics","annotation","annotation-xml"]),H3=new Set(["accent","accentunder","align","bevelled","class","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","encoding","fence","height","href","id","largeop","length","linethickness","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","width","xmlns","xml:lang"]),U9=(Z)=>Z.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),D3=(Z)=>U9(Z).replace(/"/g,"&quot;"),_3=(Z,Q)=>{let J=Z.toLowerCase(),Y=Q.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!H3.has(J))return!0;if(Y.includes("javascript:"))return!0;if(Y.includes("data:text/html"))return!0;return!1},M3=(Z)=>{let Q=Z.localName.toLowerCase();if(!A3.has(Q))return!1;let J=Z.namespaceURI;return!J||J==="http://www.w3.org/1998/Math/MathML"||J==="http://www.w3.org/1999/xhtml"},$9=(Z)=>{if(Z.nodeType===Node.TEXT_NODE)return U9(Z.textContent||"");if(Z.nodeType===Node.COMMENT_NODE)return"";if(Z.nodeType!==Node.ELEMENT_NODE)return null;let Q=Z;if(!M3(Q))return null;let J=Q.localName.toLowerCase(),Y=[];for(let j of Array.from(Q.attributes)){let B=j.name.toLowerCase();if(_3(B,j.value))continue;if(B==="xmlns"&&j.value!=="http://www.w3.org/1998/Math/MathML")return null;Y.push(`${B}="${D3(j.value)}"`)}if(J==="math"&&!Y.some((j)=>j.startsWith("xmlns=")))Y.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let j of Array.from(Q.childNodes)){let B=$9(j);if(B===null)return null;X.push(B)}let G=Y.length>0?` ${Y.join(" ")}`:"";return`<${J}${G}>${X.join("")}</${J}>`},O3=(Z)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Z,"application/xml");return null},ZZ=(Z)=>{let Q=String(Z||"").trim();if(!Q)return null;let J=O3(Q);if(!J)return null;if(J.getElementsByTagName("parsererror").length>0)return null;let Y=J.documentElement;if(!Y||Y.localName.toLowerCase()!=="math")return null;return $9(Y)};var z9=(Z)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Z}),j7=(Z)=>Z.classList?.contains("MathJax")||Z.tagName?.toLowerCase()==="mjx-container",A9=(Z)=>Z.tagName?.toLowerCase()==="mjx-assistive-mml",B7=(Z)=>{let Q=Z.tagName?.toLowerCase();return Q==="annotation"||Q==="annotation-xml"},L3=(Z)=>{let Q=Z.getAttribute("data-mathml");return Q&&Q.trim()?Q:null},P3=(Z)=>{return b0(Z,"mjx-assistive-mml math")?.outerHTML||null},N3=(Z)=>{if(Z.tagName.toLowerCase()==="math")return ZZ(Z.outerHTML);let Q=L3(Z);if(Q){let J=ZZ(Q);if(J)return J}if(j7(Z)){let J=P3(Z);if(J){let Y=ZZ(J);if(Y)return Y}}return null},w3=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),R3=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),C3=(Z,Q)=>{let J=d(Z);while(J&&J!==Q){let Y=(J.getAttribute("role")||"").toLowerCase(),X=J.tagName.toUpperCase();if(w3.has(X)||R3.has(Y))return J;J=d(J)}return Q},b3=(Z)=>Boolean(typeof Z.querySelector==="function"&&b0(Z,"math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Z.tagName?.toLowerCase()==="math"||Z.hasAttribute?.("data-mathml")||j7(Z),f0=(Z,Q,J)=>{if(/[.,;:!?]/.test(Q)&&Z.chars.length>0&&Z.chars[Z.chars.length-1]===" ")Z.chars.pop(),Z.position--,Z.map.delete(Z.position);if(Z.chars.push(Q),J)Z.map.set(Z.position,J),Z.lastMapped=J;else if(Z.lastMapped)Z.map.set(Z.position,Z.lastMapped);Z.position++},H9=(Z,Q)=>{if(Z.inLeadingWhitespace||Z.lastCharWasWhitespace||Z.chars.length===0)return!1;let J=Z.chars[Z.chars.length-1];return t5(J,Q,Z.options)},D9=(Z,Q,J=0,Y=(Q.textContent||"").length)=>{let X=Q.textContent||"",G=!1;for(let j=J;j<Y;j++){let B=X[j],V=/\s/.test(B);if(Z.inLeadingWhitespace){if(!V)Z.inLeadingWhitespace=!1,f0(Z,B,{node:Q,offset:j}),G=!0,Z.lastCharWasWhitespace=!1;continue}if(V){if(!Z.lastCharWasWhitespace)f0(Z," ",{node:Q,offset:j});Z.lastCharWasWhitespace=!0;continue}if(!G&&H9(Z,B))f0(Z," ",{node:Q,offset:j});f0(Z,B,{node:Q,offset:j}),G=!0,Z.lastCharWasWhitespace=!1}},E3=(Z,Q)=>{for(let J=0;J<Q.text.length;J++){let Y=Q.text[J],X=/\s/.test(Y),G=Q.map.get(J),j=G?{node:G.node,offset:G.offset}:Z.lastMapped?{node:Z.lastMapped.node,offset:Z.lastMapped.offset}:null;if(Z.inLeadingWhitespace){if(X)continue;Z.inLeadingWhitespace=!1}if(X){if(!Z.lastCharWasWhitespace)f0(Z," ",j);Z.lastCharWasWhitespace=!0;continue}if(J===0&&H9(Z,Y))f0(Z," ",j);f0(Z,Y,j),Z.lastCharWasWhitespace=!1}},S3=(Z)=>{if(typeof DOMParser>"u")return"";let Q=new DOMParser().parseFromString(Z,"application/xml");if(Q.getElementsByTagName("parsererror").length>0)return"";let J=[],Y=(X)=>{if(X.nodeType===3){let j=X.textContent||"";if(j.trim())J.push(j);return}if(X.nodeType!==1)return;let G=X;if(B7(G))return;for(let j of Array.from(G.childNodes))Y(j)};return Y(Q.documentElement),T(J.join(" "))},y3=(Z,Q)=>{let J=new Map,Y=j7(Z)?b0(Z,"mjx-assistive-mml math"):null;if(!Y)return J;let X=[],G=(B)=>{if(B.nodeType===3){let V=B.textContent||"";for(let q=0;q<V.length;q++)if(!/\s/.test(V[q]))X.push({node:B,offset:q});return}if(B.nodeType!==1||B7(B))return;for(let V of F0(B))G(V)};G(Y);let j=0;for(let B=0;B<Q.length;B++){if(/\s/.test(Q[B]))continue;let V=X[j];if(V?.node.textContent?.[V.offset]!==Q[B])return new Map;J.set(B,V),j++}return j===X.length?J:new Map},T3=(Z,Q,J)=>{let Y=z9(J),X=(B)=>{if(z0(B,Z))return;if(B.nodeType===3){D9(Y,B);return}if(B.nodeType!==1)return;let V=B;if(A9(V)||B7(V))return;for(let q of F0(V))X(q)};X(Z),_9(Y);let G=T(Y.chars.join(""));if(G)return{text:G,map:Y.map};let j=S3(Q);if(!j)return S0(Z,J);return{text:j,map:y3(Z,j)}},_9=(Z)=>{while(Z.chars.length>0&&/\s/.test(Z.chars[Z.chars.length-1]))Z.chars.pop(),Z.position--,Z.map.delete(Z.position)},F9=(Z,Q,J)=>{let Y=z9(Q),X=[],G=0,j,B=!1,V=()=>{let $=T(Y.chars.slice(G,Y.chars.length).join(""));if($)X.push({type:"text",text:$,sourceElement:j});G=Y.chars.length,j=void 0},q=($)=>{if(z0($,Z))return;if(J&&!G0(J,$))return;if($.nodeType===3){let O=C3($,Z);if(j&&O!==j)V();j=O;let P=$;D9(Y,P,J?.startContainer===P?J.startOffset:void 0,J?.endContainer===P?J.endOffset:void 0);return}if($.nodeType!==1)return;let z=$;if(A9(z))return;let A=N3(z);if(A&&(!J||DZ(J,z,Z))){V();let O=T3(z,A,Q);E3(Y,O);let P=T(O.text);X.push({type:"math",mathml:A,fallbackText:P,sourceElement:z}),G=Y.chars.length,B=!0;return}for(let O of F0(z))q(O)};for(let $ of F0(Z))q($);return _9(Y),V(),{visibleText:Y.chars.join(""),map:Y.map,chunks:X,containsMathMarkup:B}},A0=(Z,Q,J)=>{if(J)return F9(Z,Q,J);if(!b3(Z)){let{text:Y,map:X}=S0(Z,Q);return{visibleText:Y,map:X,chunks:Y?[{type:"text",text:Y}]:[],containsMathMarkup:!1}}return F9(Z,Q)};import{createPieLogger as k3,isTtsDebugEnabled as f3}from"@pie-players/pie-players-shared/pie";var lZ=k3("tts-math-speech",f3),M9=Promise.resolve(),I3=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",v3=(Z)=>{let Q=null,J=!1;return(Y)=>{if(!Q){N9(Y);let X=Z();Q=X,X.catch((G)=>{if(Q===X)Q=null;if(J){lZ.debug("speech-rule-engine failed to load again",G);return}J=!0,lZ.warn("speech-rule-engine failed to load; math reads as its visible text until a later read loads it.",G)})}return Q}},h3=v3(()=>import("./chunks/sre-engine-wazxma67.js").then(({default:Z})=>{if(!Z||typeof Z.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return Z})),W7=(Z)=>{let Q=null;return()=>{return Q??=h3(V0(Z)?.engineOptions),Q}},m3=(Z)=>Z==="en"?"clearspeak":"mathspeak",O9=(Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z),L9=(Z)=>typeof Z==="string"&&Z.trim()?Z.trim():void 0,V0=(Z)=>{if(!O9(Z))return;let Q=L9(Z.domain),J=L9(Z.style),Y=O9(Z.engineOptions)?Z.engineOptions:void 0;if(!Q&&!J&&!Y)return;return{...Q?{domain:Q}:{},...J?{style:J}:{},...Y?{engineOptions:Y}:{}}},u3=async(Z,Q,J,Y)=>{let X=I3(Q),G=V0(Y),j=G?.engineOptions||{};await Z.setupEngine?.({...P9(j),...j,locale:X,domain:G?.domain||m3(X),style:G?.style||"default",modality:"speech",markup:J}),await Z.engineReady?.()},p3=async(Z)=>{let Q=M9.then(Z,Z);return M9=Q.then(()=>{return},()=>{return}),Q},w9=async(Z,Q,J,Y,X)=>p3(async()=>{return await u3(Z,J,Y,X),Z.toSpeech(Q)}),g3=(Z)=>Z.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),c3=async(Z,Q,J,Y)=>{try{let X=g3(await w9(Z,Q,J,"ssml",Y));return X.includes("<speak")?X:null}catch(X){return lZ.debug("math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},QZ=async(Z,Q={})=>{if(!Z.some((q)=>q.type==="math"))return{speechText:T(Z.map((q)=>q.type==="text"?q.text:q.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,Y=!1,X=!1,G=Q.loadSre||W7(Q.mathSpeech),j=[];for(let q of Z){if(q.type==="text"){j.push(q.text);continue}try{if(!J)J=await G();let U=T(await w9(J,q.mathml,Q.language,"none",Q.mathSpeech));if(U){j.push(U),Y=!0;continue}X=!0,j.push(q.fallbackText)}catch(U){X=!0,lZ.debug("math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),j.push(q.fallbackText)}}let B=T(j.join(" ")),V;if(Q.produceSsml&&J&&Y&&Z.length===1&&Z[0].type==="math")V=await c3(J,Z[0].mathml,Q.language,Q.mathSpeech)??void 0;return{speechText:B,usedMathSpeech:Y,usedFallback:X,ssml:V}};var d3=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",i3="sre-v1",l3=256,V7=(Z)=>{if(Array.isArray(Z))return`array:[${Z.map(V7).join(",")}]`;if(Z&&typeof Z==="object")return`object:{${Object.entries(Z).sort(([Q],[J])=>Q.localeCompare(J)).map(([Q,J])=>`${JSON.stringify(Q)}:${V7(J)}`).join(",")}}`;if(Z===null)return"null:null";if(typeof Z>"u")return"undefined:";if(typeof Z==="function")return`function:${Z.name||"anonymous"}`;if(typeof Z==="symbol")return`symbol:${String(Z)}`;if(typeof Z==="bigint")return`bigint:${Z.toString()}`;if(typeof Z==="number")return Number.isFinite(Z)?`number:${Z}`:`number:${String(Z)}`;return`${typeof Z}:${JSON.stringify(Z)}`},R9=(Z,Q,J,Y)=>`${i3}\x00${d3(Z)}\x00${Q?"ssml":"plain"}\x00${V7(J??null)}\x00${Y}`,K7=(Z={})=>{let Q=Math.max(1,Z.maxEntries??l3),J=Z.resolve??((G,j)=>QZ([G],j)),Y=new Map,X=(G,j)=>{Y.delete(G),Y.set(G,j);while(Y.size>Q){let B=Y.keys().next().value;if(B!==void 0)Y.delete(B)}};return async(G,j)=>{let B=V0(j.mathSpeech),V=j.produceSsml===!0,q=R9(j.language,V,B,G.mathml),U=Y.get(q);if(U)return Y.delete(q),Y.set(q,U),U;let $=await J(G,{...j,mathSpeech:B});if($.usedFallback)return $;if(V&&$.ssml&&Q>1)X(R9(j.language,!1,B,G.mathml),{speechText:$.speechText,usedMathSpeech:$.usedMathSpeech,usedFallback:$.usedFallback});return X(q,$),$}};var C9=(Z,Q)=>{let J=o0(Q.word);if(Z.id!==Q.chunkId)return{chunkId:Q.chunkId,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(Q.providerOffsetSpace==="unknown"||Z.offsetSpace==="unsupported")return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let Y=Y7({tokenization:Z.catalogAlignment?.speech??y0({speechText:Z.speechText}),position:Q.position,length:Q.length,boundaryWord:Q.word});if(!Y)return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};return{chunkId:Z.id,normalizedWord:J,chunkSpokenStart:Y.start,chunkSpokenEnd:Y.start+Y.length,confidence:Y.confidence,reason:Z.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var I0=(Z)=>{if(Z.semanticTarget)return{activeTarget:Z.semanticTarget,regionTarget:Z.regionTarget,quality:Z.semanticTarget.quality==="exact-word"?"exact-word":Z.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Z.confidence,reason:Z.reason};if(Z.expressionTarget)return{activeTarget:Z.expressionTarget,regionTarget:Z.regionTarget,quality:"expression",confidence:Z.confidence,reason:Z.reason};return{activeTarget:null,regionTarget:Z.regionTarget,quality:"region",confidence:Z.confidence,reason:Z.reason}};var E9=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),q7="mi,mn,mo,mtext",S9="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",y9=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),T9=(Z)=>{if(Z.type==="text-range")return Z.node.parentElement;return Z.element},sZ=(Z)=>{let Q=Z;while(Q){if(Q.localName?.toLowerCase()==="mjx-container")return Q;Q=Q.parentElement}return null},b9=(Z)=>{if(!Z)return!1;if(sZ(Z))return!1;return!a0(Z)},x9=(Z)=>{let Q=Z.getBoundingClientRect?.();return Boolean(Q&&Q.width>0&&Q.height>0)},U7=(Z)=>{let Q=Z;while(Q){if(Q.localName?.toLowerCase()==="math")return Q;Q=Q.parentElement}return null},k9=(Z,Q)=>{if(Z.length===0)return!1;if(Z.length!==Q.length)return!1;for(let J=0;J<Z.length;J+=1){let Y=E9.get(Z[J].localName.toLowerCase());if(!Y)return!1;if(Q[J].localName.toLowerCase()!==Y)return!1}return!0},s3=(Z,Q)=>{if(!Z)return null;if(!E9.has(Z.localName.toLowerCase()))return null;if(Q.querySelector(y9))return null;let J=U7(Z),Y=Q.querySelector("mjx-math");if(!J||!Y)return null;let X=Array.from(J.querySelectorAll(q7)),G=X.indexOf(Z);if(G<0)return null;let j=Array.from(Y.querySelectorAll(S9));if(!k9(X,j))return null;let B=j[G];if(!B||!x9(B))return null;return B},f9=(Z)=>{let Q=sZ(Z);if(Q){if(Q.querySelector(y9))return"expression";let X=U7(Z)??Z,G=Q.querySelector("mjx-math");if(!G)return"expression";let j=Array.from(X.querySelectorAll(q7)),B=Array.from(G.querySelectorAll(S9));if(!k9(j,B))return"expression";return B.some((V)=>x9(V))?"token":"expression"}let J=U7(Z)??Z;return Array.from(J.querySelectorAll(q7)).some((X)=>!a0(X))?"token":"expression"},$7=(Z)=>{let Q=T9(Z),J=sZ(Q);if(J){let Y=s3(Q,J);if(Y)return{type:"element",quality:"semantic-token",element:Y};return{type:"element",quality:"expression",element:J}}if(Z.type==="text-range"){if(!b9(Z.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Z.node,startOffset:Z.startOffset,endOffset:Z.endOffset}}if(!b9(Z.element))return null;return{type:"element",quality:Z.quality==="region-fallback"?"expression":"semantic-token",element:Z.element}},I9=$7,v9=()=>{let Z=new WeakMap;return(Q)=>{let J=T9(Q),Y=sZ(J);if(!J||!Y)return $7(Q);if(Z.has(J))return Z.get(J)??null;let X=$7(Q);return Z.set(J,X),X}};var h9=(Z,Q,J,Y=Z.mathAlignments,X=I9)=>{if(Q.chunkSpokenStart===null||Q.chunkSpokenEnd===null)return null;let G=null;for(let j of Y){let B=K9(j.alignment,{position:Q.chunkSpokenStart,length:Math.max(1,Q.chunkSpokenEnd-Q.chunkSpokenStart),boundaryWord:J.word})||q9(j.alignment,{boundaryWord:J.word});if(!B)continue;let V=X(B);if(!V)continue;if(V.quality==="semantic-token")return V;G??=V}return G};var H0=(Z)=>Z.node.getRootNode?.()??Z.node,m9=(Z,Q)=>{try{let J=document.createRange();return J.setStart(Z.node,Z.offset),J.setEnd(Q.node,Q.offset+1),J}catch{return null}},F7=(Z,Q,J)=>{if(!Z||typeof document>"u")return null;if(J<=Q)return null;let Y=Z.get(Q),X=Z.get(Math.max(Q,J-1));if(!Y)return null;if(!X)X=Y;if(H0(X)!==H0(Y)){let G=H0(Y);X=Y;for(let j=Q+1;j<J;j++){let B=Z.get(j);if(B&&H0(B)===G)X=B}}return m9(Y,X)},D0=(Z,Q,J)=>{if(!Z||typeof document>"u"||J<=Q)return[];let Y=Z.get(Q);if(!Y)return[];let X=H0(Y),G=!1;for(let U=Q+1;U<J&&!G;U++){let $=Z.get(U);if($&&H0($)!==X)G=!0}if(!G){let U=F7(Z,Q,J);return U?[U]:[]}let j=[],B=null,V=null,q=()=>{if(B&&V){let U=m9(B,V);if(U)j.push(U)}B=null,V=null};for(let U=Q;U<J;U++){let $=Z.get(U);if(!$)continue;if(B&&H0(B)!==H0($))q();if(!B)B=$;V=$}return q(),j};var u9=(Z,Q)=>{if(!Z.catalogAlignment||Q.chunkSpokenStart===null)return null;let J=Y9(Z.catalogAlignment,Q.chunkSpokenStart);if(!J)return null;let Y=D0(Z.visibleMap,J.start,J.end);if(Y.length===0)return null;return{type:"range",quality:Z.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:Y[0],ranges:Y.length>1?Y:void 0}};var n3=(Z)=>{let Q=D0(Z.visibleMap,0,Z.visibleText.length);return Q.length>1?Q:void 0},r3=(Z)=>Z.regionRange?{type:"range",quality:"region",range:Z.regionRange,ranges:n3(Z)}:Z.regionElement?{type:"element",quality:"region",element:Z.regionElement}:null,p9=(Z,Q=Z.chunk.mathAlignments)=>{if(Q.length!==1)return null;let J=Q[0]?.alignment.result.fallbackTarget;return J?Z.renderedMathTargetResolver(J):null},a3=(Z,Q)=>{if(!Z)return Q.mathAlignments;return Q.mathAlignments.filter(({element:J})=>{try{if(Z.type==="range")return(Z.ranges??[Z.range]).some((Y)=>G0(Y,J));if(Z.type==="element")return J0(Z.element,J);return J0(i(Z.node),J)}catch{return!1}})},g9=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),z7=(Z)=>Z.length===1?Z[0].element:null,o3=(Z,Q)=>Q.length>0&&Q.every(({element:J})=>Z.mathCapabilityByElement.get(J)==="token"),c9=3,t3=(Z,Q,J)=>{if(!Q||Q.type!=="range")return!1;let{startContainer:Y,endContainer:X}=Q.range;if(Y===X&&Y.nodeType===c9)return!1;return J.some(({element:j})=>Z.mathCapabilityByElement.get(j)==="token"&&j.contains(Y)&&j.contains(X))},d9=(Z)=>Z?.type==="range"&&a0(Z.range.startContainer),e3=(Z,Q)=>{if(!d9(Q))return null;let{startContainer:J,endContainer:Y,startOffset:X,endOffset:G}=Q.range;if(J!==Y||J.nodeType!==c9)return null;return Z.renderedMathTargetResolver({type:"text-range",quality:"exact-word",node:J,startOffset:X,endOffset:G})},Z2=(Z,Q)=>({chunk:Z,regionTarget:r3(Z),renderedMathTargetResolver:v9(),mathCapabilityByElement:new Map(Z.mathAlignments.map(({element:J})=>[J,Q?f9(J):"expression"])),heldTokenByElement:new Map}),i9=(Z)=>{let Q=Z.mathTokenHighlighting!==!1,J=new Map(Z.chunks.map((Y)=>[Y.id,Z2(Y,Q)]));return{chunks:Z.chunks,resolveInitial(Y){let X=J.get(Y);if(!X)return g9();let G=z7(X.chunk.mathAlignments),j=G?X.mathCapabilityByElement.get(G):null;if(j==="expression")return I0({semanticTarget:null,expressionTarget:p9(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return I0({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:j==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(Y){let X=J.get(Y.chunkId);if(!X)return g9();let{chunk:G}=X,j=C9(G,Y),B=u9(G,j),V=a3(B,G),q=!B||V.length>0?h9(G,j,Y,V,X.renderedMathTargetResolver):null,U=q?.quality==="semantic-token"?q:e3(X,B)??q,$=Q&&U&&U.quality!=="expression"?U:null,z=U&&U.quality==="expression"?U:null;if($){let A=z7(V);if(A)X.heldTokenByElement.set(A,$);return I0({semanticTarget:$,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}if(B&&!d9(B)&&(Q?!t3(X,B,V):V.length===0))return I0({semanticTarget:B,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason});if(o3(X,V)){let A=z7(V),O=A?X.heldTokenByElement.get(A)??null:null;return I0({semanticTarget:O,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:O?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return I0({semanticTarget:null,expressionTarget:z??p9(X,V),regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}}};var Q2=(Z)=>{return Z.alignment?.speech.boundaryOffsetSpace??Z.mathAlignment?.speech.boundaryOffsetSpace??"plain-spoken-text"},J2=(Z)=>{if(Z.mathAlignments?.length)return Z.mathAlignments;if(Z.mathAlignment&&Z.sourceElement)return[{element:Z.sourceElement,alignment:Z.mathAlignment}];return[]},l9=(Z)=>{return(Z.chunks&&Z.chunks.length?Z.chunks:[{speechText:Z.speechText||"",visibleText:Z.visibleText||Z.speechText||"",sourceElement:Z.sourceElement||Z.contentRoot,regionElement:Z.regionElement||Z.sourceElement||Z.contentRoot,regionRange:Z.regionRange,visibleMap:Z.visibleMap}]).map((J,Y)=>({id:`tts-chunk-${Y}`,speechText:J.speechText,visibleText:J.visibleText,sourceElement:J.sourceElement,contentRoot:Z.contentRoot,regionElement:J.regionElement??J.sourceElement,regionRange:J.regionRange,visibleMap:J.visibleMap,catalogAlignment:J.alignment,mathAlignments:J2(J),offsetSpace:Q2(J)}))};var Y2=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),nZ=(Z,Q)=>{let J=vZ(Z,Y2);if(J&&J0(Q,J))return J;return Z};var v0=(Z,Q)=>{let J=Q?.useSentenceSegmenter===!1?void 0:globalThis.Intl?.Segmenter;if(typeof J==="function")try{let B=new J(Q?.locale,{granularity:"sentence"}),V=Array.from(B.segment(Z)).map((q)=>({text:q.segment,offset:q.index})).filter((q)=>q.text.trim().length>0);if(V.length>0)return V}catch{}let Y=/[^.!?]+(?:[.!?]+|$)/g,X=Z.match(Y)||[Z],G=[],j=0;for(let B of X){let V=Z.indexOf(B,j);if(V===-1)continue;G.push({text:B,offset:V}),j=V+B.length}return G.length>0?G:[{text:Z,offset:0}]},A7=(Z,Q,J)=>{let Y=Math.max(1,Math.floor(Q)),X=[],G=-1,j=-1,B=()=>{if(G>=0)X.push({text:Z.slice(G,j),offset:G});G=-1},V=(q,U)=>{if(G>=0&&U-G<=Y){j=U;return}B();let $=q;while(U-$>Y){let A=Z.slice($,$+Y+1).search(/\s\S*$/),O=A>0?$+A:$+Y;X.push({text:Z.slice($,O).trimEnd(),offset:$}),$=O;while($<U&&/\s/.test(Z[$]))$++}if($<U)G=$,j=U};for(let q of v0(Z,J)){let U=q.text.search(/\S/);if(U===-1)continue;let $=q.offset+U;V($,q.offset+q.text.trimEnd().length)}return B(),X};var X2=(Z,Q)=>QZ([Z],Q),G2=(Z)=>(Z||"en").split("-")[0].toLowerCase()||"en",j2=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),B2=new Set(["heading","listitem","option","radio"]),W2=(Z)=>{if(Z.type!=="text"||!Z.sourceElement)return!1;let Q=Z.sourceElement.tagName.toUpperCase(),J=(Z.sourceElement.getAttribute("role")||"").toLowerCase();return j2.has(Q)||B2.has(J)},s9=async(Z)=>{let Q=Z.resolveMathSpeech??X2,J=W7(Z.mathSpeech),{visibleText:Y}=Z,X=[],G=0,j=(V)=>{let q=T(V),U=Y.indexOf(q,G),$=U>=0?U:G,z=$+q.length;return G=z,{start:$,end:z}},B=[];for(let V=0;V<Z.chunks.length;V++){let q=Z.chunks[V];if(q.type==="text"){let O=W2(q)?[{text:q.text,offset:0}]:v0(q.text,{locale:Z.language});for(let P of O){let D=T(P.text);if(!D)continue;let N=j(D);X.push({sourceChunkIndex:V,segment:{kind:"prose",spokenText:D,visibleText:D,visibleSpan:N}}),B.push(D)}continue}let U=j(q.fallbackText),$=await Q(q,{language:Z.language,produceSsml:Z.produceSsml,mathSpeech:Z.mathSpeech,loadSre:J}),z=!$.speechText,A=$.speechText||q.fallbackText;X.push({sourceChunkIndex:V,segment:{kind:"math",spokenText:A,mathml:q.mathml,fallbackText:q.fallbackText,visibleSpan:U,usedFallback:z,ssml:$.ssml}}),B.push(A)}return{segments:X,locale:G2(Z.language),visibleText:Y,plainSpeechText:T(B.join(" "))}};var V2=(Z,Q,J)=>{let Y=new Map;for(let X=Q;X<J;X++){let G=Z.get(X);if(G)Y.set(X-Q,G)}return Y},H7=async(Z)=>{let Q=A0(Z.contentRoot,Z.textProcessingOptions,Z.range),J=await s9({chunks:Q.chunks,visibleText:Q.visibleText,language:Z.language,mathSpeech:Z.mathSpeech,produceSsml:Z.produceSsml,resolveMathSpeech:Z.resolveMathSpeech});return{plan:{items:J.segments.map(({segment:X,sourceChunkIndex:G})=>{let j=Q.chunks[G];if(X.kind==="prose"){let V=j?.type==="text"?j.sourceElement??Z.contentRoot:Z.contentRoot;return{segment:X,anchor:{sourceElement:V,regionElement:nZ(V,Z.contentRoot),visibleMap:V2(Q.map,X.visibleSpan.start,X.visibleSpan.end)}}}let B=j?.type==="math"?j.sourceElement??null:null;return{segment:X,anchor:{sourceElement:B,regionElement:B}}}),locale:J.locale,visibleText:J.visibleText,plainSpeechText:J.plainSpeechText},containsMathMarkup:Q.containsMathMarkup,visibleText:Q.visibleText}};var K2=(Z,Q)=>{let J=iZ({speechText:Z.spokenText,visibleText:Z.spokenText});return{speechText:Z.spokenText,visibleText:Z.visibleText,sourceElement:Q.sourceElement,regionElement:Q.regionElement,regionRange:F7(Q.visibleMap,0,Z.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Q.visibleMap}},n9=(Z,Q)=>{let J=Q.sourceElement;return{speechText:Z.spokenText,visibleText:Z.fallbackText,sourceElement:J,regionElement:Q.regionElement,speechMatchesVisibleText:Z.spokenText===Z.fallbackText,mathAlignment:J?e0({mathElement:J,speechText:Z.spokenText}):void 0}},q2=(Z,Q,J)=>{let Y=Q.sourceElement;return{speechText:J,visibleText:Z.fallbackText,sourceElement:Y,regionElement:Q.regionElement,speechMatchesVisibleText:!1,mathAlignment:Y?e0({mathElement:Y,speechText:J}):void 0,plainFallback:n9(Z,Q)}},D7=(Z,Q={})=>Z.items.map(({segment:J,anchor:Y})=>{if(J.kind==="prose")return K2(J,Y);if(Q.format==="ssml"&&J.ssml)return q2(J,Y,J.ssml);return n9(J,Y)});function rZ(Z){let Q=Z instanceof Error?Z:Error(String(Z));return Q.code="tts-start-failed",Q}var t=F2("tts-service",Q1),R;(function(Z){Z.IDLE="idle",Z.LOADING="loading",Z.PLAYING="playing",Z.PAUSED="paused",Z.ERROR="error"})(R||(R={}));var z2={baseMs:280,units:{minor:0.65,section:1,major:1.35},minMs:120,maxMs:900},r9=0.25,a9=4,h0=(Z)=>typeof Z==="string"&&Z.trim()?Z.trim():void 0,o9=(Z,Q={})=>{if(!Z)return Q;return{locale:"locale"in Z?h0(Z.locale):Q.locale,textNormalization:Z.textNormalization&&"locale"in Z.textNormalization?h0(Z.textNormalization.locale):Q.textNormalization,segmenter:Z.segmenter&&"locale"in Z.segmenter?h0(Z.segmenter.locale):Q.segmenter}},t9=(Z)=>("commonAncestorContainer"in Z),J1=(Z,Q)=>Z===Q||Z.startContainer===Q.startContainer&&Z.startOffset===Q.startOffset&&Z.endContainer===Q.endContainer&&Z.endOffset===Q.endOffset,A2=(Z,Q)=>{if(Z===Q)return!0;if(!Z||!Q||Z.type!==Q.type||Z.quality!==Q.quality)return!1;if(Z.type==="range"&&Q.type==="range")return J1(Z.range,Q.range);if(Z.type==="element"&&Q.type==="element")return Z.element===Q.element;if(Z.type==="text-range"&&Q.type==="text-range")return Z.node===Q.node&&Z.startOffset===Q.startOffset&&Z.endOffset===Q.endOffset;return!1},H2=(Z,Q)=>{for(let J=0;J<Math.min(Z.length,Q.length);J++)if(Z[J]!==Q[J])return{index:J,spokenChar:Z[J],normalizedChar:Q[J],spokenContext:Z.substring(Math.max(0,J-20),J+20),normalizedContext:Q.substring(Math.max(0,J-20),J+20)};return null},e9=(Z)=>{let Q=Number(Z.getAttribute("data-tts-break-ms"));return Number.isFinite(Q)&&Q>0?Q:null},D2=(Z)=>{if(typeof window>"u")return!1;let Q=window.getComputedStyle(Z).display;return Q==="block"||Q==="list-item"||Q.startsWith("table")||Q==="flex"||Q==="grid"},Z1=(Z,Q,J)=>{let Y=Z.substring(Q,J);return{start:Q+(Y.match(/^\s*/)?.[0].length||0),end:J-(Y.match(/\s*$/)?.[0].length||0)}};class _7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=R.IDLE;resumeState=R.PLAYING;ttsConfig={};hostLocales={};readLocale=mZ;disposed=!1;readinessGate=null;mathSpeechSource=null;currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Set;lastError=null;speakRunId=0;restartRunId=null;runOwner=null;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;pauseHold=null;structuralPause=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";wordlessPartHighlight=null;lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=K7();clearPlaybackStartBarrier(Z=this.playbackStartBarrierCleanup){if(Z?.(),this.playbackStartBarrierCleanup===Z)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Z,Q){if(this.playbackStartDeferredRunId!==Z||Z!==this.speakRunId)return;if(this.state===R.PAUSED)this.activeRecordedAudio?.element.pause(),this.provider?.pause();this.markPlaying();let J=this.pendingPlaybackStartHighlights.splice(0);for(let Y of J)Y();if(Q?.wordBoundaries===!1)this.highlightWordlessPlayback()}highlightWordlessPlayback(){let Z=this.wordlessPartHighlight;if(!Z||this.activeHighlightMode!=="word")return;this.highlightCoordinator?.clearTTSWord(),Z()}installPlaybackStartBarrier(Z,Q=!1){this.clearPlaybackStartBarrier();let J=this.provider,Y=J&&"onPlaybackStart"in J?J:null;if(!Y&&!Q)return null;let X=Y?.onPlaybackStart,G=(B)=>{try{this.notifyPlaybackStarted(Z,B)}finally{X?.(B)}};if(Y)Y.onPlaybackStart=G;this.playbackStartDeferredRunId=Z;let j=()=>{if(Y?.onPlaybackStart===G)Y.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Z)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=j,j}runWhenPlaybackStarts(Z,Q){if(this.playbackStartDeferredRunId===Z){this.pendingPlaybackStartHighlights.push(Q);return}Q()}async waitWhilePaused(Z){while(this.state===R.PAUSED&&Z===this.speakRunId){if(!this.pauseHold){let Q=()=>{},J=new Promise((Y)=>{Q=Y});this.pauseHold={promise:J,release:Q}}await this.pauseHold.promise}}releasePauseHold(){let Z=this.pauseHold;this.pauseHold=null,Z?.release()}waitStructuralPause(Z){return this.cancelStructuralPause(),new Promise((Q)=>{let J=()=>{if(this.structuralPause?.finish===J)clearTimeout(this.structuralPause.timer),this.structuralPause=null;Q()};this.structuralPause={timer:setTimeout(J,Z),finish:J}})}cancelStructuralPause(){this.structuralPause?.finish()}abandonRun(){this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.cancelStructuralPause(),this.releasePauseHold()}beginRun(Z){let Q=this.state===R.LOADING||this.state===R.PLAYING||this.state===R.PAUSED,J=++this.speakRunId;if(this.runOwner=Z,this.abandonRun(),Q)this.provider?.stop();return this.setState(R.LOADING,!0),J}markPlaying(){if(this.state===R.PAUSED){this.resumeState=R.PLAYING;return}this.setState(R.PLAYING)}assertNotDisposed(){if(this.disposed)throw rZ(Error("TTS service disposed"))}async emitTelemetry(Z,Q){try{await this.telemetryReporter?.(Z,Q)}catch(J){console.warn("[TTSService] telemetry callback failed:",J)}}async initialize(Z,Q={}){if(this.disposed)throw Error("TTS service disposed");this.currentProvider=Z,this.ttsConfig={...Q},this.hostLocales=o9(Q.providerOptions);let J=this.providerOptions().__pieTelemetry;this.telemetryReporter=typeof J==="function"?J:null,this.provider=await Z.initialize(Q)}async updateSettings(Z){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Q={...Z,...Z.providerOptions?{providerOptions:{...this.providerOptions(),...Z.providerOptions}}:{}};await this.provider.updateSettings(Q),this.ttsConfig={...this.ttsConfig,...Q},this.hostLocales=o9(Z.providerOptions,this.hostLocales)}setHighlightCoordinator(Z){this.highlightCoordinator=Z}setReadinessGate(Z){this.readinessGate=Z}setMathSpeechSource(Z){this.mathSpeechSource=Z}pendingReadiness(){if(this.provider||!this.readinessGate)return null;return this.readinessGate().catch((Z)=>{throw rZ(Z)})}setHighlightTargetResolverProvider(Z){return this.highlightTargetResolverProvider=Z,()=>{if(this.highlightTargetResolverProvider===Z)this.highlightTargetResolverProvider=null}}setCatalogResolver(Z){this.catalogResolver=Z}getHighlightResolverRuntime(){let Z=null;try{Z=this.highlightTargetResolverProvider?.()??null}catch{Z=null}let Q=Z?.context??{},J=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...Q,scopeElement:Q.scopeElement??J},resolver:Z?.resolver??null}}getNodeElement(Z){if(!Z)return null;return Z.nodeType===Node.ELEMENT_NODE?Z:i(Z)}isElementWithinScope(Z,Q){if(!Q)return!0;return J0(Q,Z)}isRangeWithinScope(Z,Q){let J=this.getNodeElement(Z.startContainer),Y=this.getNodeElement(Z.endContainer);if(!J||!Y)return!1;return this.isElementWithinScope(J,Q)&&this.isElementWithinScope(Y,Q)}resolveWordHighlightRange(Z){let{context:Q,resolver:J}=this.getHighlightResolverRuntime(),Y=Q.scopeElement??this.currentContentElement;try{let X=J?.resolveWordRange?.(Z,Q);if(X&&this.isRangeWithinScope(X,Y))return{range:X,remapped:!J1(Z,X)}}catch{}return{range:Z,remapped:!1}}resolveSentenceHighlightTargets(Z){let{context:Q,resolver:J}=this.getHighlightResolverRuntime(),Y=Q.scopeElement??this.currentContentElement;try{let X=J?.resolveSentenceRanges?.(Z,Q);if(!X)return{ranges:Z,elements:[]};let G=[],j=[];for(let B of X){if(typeof Range<"u"&&B instanceof Range){if(!this.isRangeWithinScope(B,Y))return{ranges:Z,elements:[]};G.push(B);continue}if(typeof Element<"u"&&B instanceof Element){if(!this.isElementWithinScope(B,Y))return{ranges:Z,elements:[]};j.push(B);continue}return{ranges:Z,elements:[]}}return{ranges:G,elements:j}}catch{return{ranges:Z,elements:[]}}}createTextRange(Z,Q,J){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let Y=document.createRange();if(Y.setStart(Z,Q),Y.setEnd(Z,J),Y.startContainer!==Z||Y.endContainer!==Z)return null;return Y}catch{return null}}paintTTSWord(Z){if(!this.highlightCoordinator||Z.length===0)return;this.highlightCoordinator.highlightTTSWord(Z.map((Q)=>this.resolveWordHighlightRange(Q).range))}paintTTSSentenceRanges(Z){if(!this.highlightCoordinator)return;let{ranges:Q,elements:J}=this.resolveSentenceHighlightTargets(Z);if(J.length>0&&Q.length===0){this.highlightCoordinator.highlightTTSSentenceElements(J);return}let Y=[...Q];for(let X of J){let G=document.createRange();G.selectNodeContents(X),Y.push(G)}this.highlightCoordinator.highlightTTSSentence(Y)}providerOptions(){let Z=this.ttsConfig.providerOptions;return Z&&typeof Z==="object"?Z:{}}maxTextLength(){let Z=this.currentProvider?.getCapabilities?.().maxTextLength;return typeof Z==="number"&&Z>0?Z:void 0}async speakWithinLimit(Z,Q){let J=this.provider;if(!J)return;let Y=this.maxTextLength();if(!Y||Z.length<=Y){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==J)return;await J.speak(Z);return}if(cZ(Z))throw Error(`[tts] SSML of ${Z.length} characters exceeds the provider's limit of ${Y}`);let X=J.onWordBoundary;try{for(let G of A7(Z,Y,{locale:this.readLocale})){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==J)return;J.onWordBoundary=X?(j,B,V)=>X(j,B+G.offset,V):void 0,await J.speak(G.text)}}finally{if(this.provider===J&&Q===this.speakRunId)J.onWordBoundary=X}}segmentsWithinLimit(Z){let Q=this.maxTextLength();if(!Q)return Z;return Z.flatMap((J)=>{if(J.text.length<=Q)return[J];let Y=A7(J.text,Q,{locale:this.readLocale});return Y.map((X,G)=>({text:X.text,startOffset:J.startOffset+X.offset,pauseMsAfter:G===Y.length-1?J.pauseMsAfter:void 0}))})}getTextProcessingOptions(Z){let Q=this.providerOptions().textNormalization?.boundarySpacingMode;return{locale:Z,boundarySpacingMode:Q==="none"||Q==="alnum"||Q==="segmenterPreferred"?Q:void 0}}resolveReadLanguage(Z,Q){let J=r5(Z)??(Z.nodeType===1?l8(Z):void 0)??(Q?.trim()||void 0)??h0(this.providerOptions().lang_id);return{contentLanguage:J,locale:J??this.hostLocales.locale??this.hostLocales.textNormalization??mZ}}getMathSpeechOptions(){if(this.mathSpeechSource)return V0(this.mathSpeechSource());return V0(this.providerOptions().mathSpeech)}buildPositionMap(Z,Q,J){this.normalizedToDOM.clear();let{text:Y,map:X}=S0(Z,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!Q1())return;t.debug("Text comparison:",{spokenLength:Q.length,normalizedDomLength:Y.length,match:Q===Y,spokenPreview:Q.substring(0,150),normalizedPreview:Y.substring(0,150),differAtIndex:Q===Y?null:H2(Q,Y)}),t.debug("Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:Q.length,normalizedDomLength:Y.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===Q.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([G,{node:j,offset:B}])=>({pos:G,offset:B,char:j.textContent?.[B],expected:Q[G]}))})}getStructuralPauseProfile(){let Z=this.providerOptions().structuralPauses||{},Q=Z.units||{},J=(X,G)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let j=Number(X);return Number.isFinite(j)?j:G}return G},Y=z2;return{baseMs:J(Z.baseMs,Y.baseMs),units:{minor:J(Q.minor,Y.units.minor),section:J(Q.section,Y.units.section),major:J(Q.major,Y.units.major)},minMs:J(Z.minMs,Y.minMs),maxMs:J(Z.maxMs,Y.maxMs)}}resolvePauseMsFromUnits(Z){let Q=this.getStructuralPauseProfile(),J=Math.max(r9,Math.min(a9,Number(this.ttsConfig.rate||1))),Y=Q.baseMs*Math.max(0,Z)/J;return Math.max(Q.minMs,Math.min(Q.maxMs,Math.round(Y)))}resolveHighlightMode(){let Z=this.providerOptions().highlightMode;if(Z==="word"||Z==="sentence")return Z;let Q=this.currentProvider?.getCapabilities();if(Q?.defaultHighlightMode)return Q.defaultHighlightMode;return Q?.supportsWordBoundary?"word":"sentence"}hasExplicitBreakSemantics(Z){if(!Z.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Z)}getBoundaryStrength(Z){if(e9(Z)!==null)return"major";let Q=Z.tagName.toUpperCase();if(Q.match(/^H[1-6]$/))return"major";let J=(Z.getAttribute("role")||"").toLowerCase();if(J==="heading")return"major";if(J==="listitem"||J==="row"||J==="option"||J==="radio"||Q==="LI")return"section";return"minor"}getBoundaryAnchor(Z,Q){let J=d(Z),Y=null;while(J&&J!==Q){if(uZ(J))return null;let G=e9(J);if(G!==null)return{anchor:J,units:G/this.getStructuralPauseProfile().baseMs};let j=(J.getAttribute("role")||"").toLowerCase(),B=J.tagName.toUpperCase();if(B.match(/^H[1-6]$/)||j==="heading"||j==="listitem"||B==="LI"){Y=J;break}if(!Y&&D2(J))Y=J;J=d(J)}if(!Y)return null;let X=this.getBoundaryStrength(Y);return{anchor:Y,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Z,Q,J,Y){let X=this.collectSpeechPlanBoundaries(Z,Y);if(J===0)return this.createSpeechPlanSegments(Q,X);let G=new Map;for(let[j,B]of X)G.set(j-J,B);return this.createSpeechPlanSegments(Q,G)}collectSpeechPlanBoundaries(Z,Q){let J=new Map,{map:Y}=S0(Z,this.getTextProcessingOptions(Q)),X=this.createNodeStartOffsets(Y),G=null;for(let j of C0(Z)){let B=d(j);if(B&&!uZ(B)&&!pZ(j)){let V=this.getBoundaryAnchor(j,Z),q=X.get(j);if(V&&q!==void 0&&V.anchor!==G&&q>0)J.set(q,Math.max(J.get(q)||0,V.units)),G=V.anchor}}return J}createNodeStartOffsets(Z){let Q=new Map;for(let[J,Y]of Z.entries())if(!Q.has(Y.node))Q.set(Y.node,J);return Q}createSpeechPlanSegments(Z,Q){let J=Array.from(Q.keys()).filter((V)=>V>0&&V<Z.length).sort((V,q)=>V-q),Y=[],X=0;for(let V of J){let{start:q,end:U}=Z1(Z,X,V);if(U>q){let $=Z.substring(q,U);Y.push({text:$,startOffset:q,pauseMsAfter:this.resolvePauseMsFromUnits(Q.get(V)||0)})}X=V}let j=Z.substring(X).match(/^\s*/)?.[0].length||0,B=X+j;if(B<Z.length)Y.push({text:Z.substring(B).trimEnd(),startOffset:B,pauseMsAfter:0});return Y.filter((V)=>V.text.trim().length>0)}segmentSentences(Z){return v0(Z,{locale:this.readLocale})}createSeekSegmentsFromText(Z){return this.segmentSentences(Z).map((Q)=>{let J=Q.text.match(/^\s*/)?.[0].length||0;return{text:Q.text.trim(),startOffset:Q.offset+J,pauseMsAfter:0}}).filter((Q)=>Q.text.length>0)}splitSegmentsAtBoundaries(Z,Q,J){if(Z.length===0||Q.length===0)return Z;let Y=Array.from(new Set(Q)).filter((G)=>Number.isFinite(G)&&G>0).sort((G,j)=>G-j);if(Y.length===0)return Z;let X=[];for(let G of Z){let j=G.startOffset,B=G.startOffset+G.text.length,V=Y.filter((U)=>U>j&&U<B);if(V.length===0){X.push(G);continue}let q=j;for(let U of[...V,B]){let{start:$,end:z}=Z1(J,q,U);if(z>$)X.push({text:J.substring($,z),startOffset:$,pauseMsAfter:0});q=U}}return X}createSentenceHighlightSegments(Z){let Q=this.createSeekSegmentsFromText(Z.contentToSpeak);if(!Z.shouldUsePlan||Z.playbackSegments.length===0)return Q;let J=Z.playbackSegments.map((Y)=>Y.startOffset).filter((Y)=>Y>0);return this.splitSegmentsAtBoundaries(Q,J,Z.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Z){let Q=0;return Z.map((J)=>{let Y=J.plainFallback?.speechText||(this.hasExplicitBreakSemantics(J.speechText)?J.visibleText:J.speechText)||J.visibleText,X=T(Y)||J.visibleText||"",G={text:X,startOffset:Q,pauseMsAfter:0};return Q+=X.length+1,G})}getCurrentSeekSegmentIndex(){return Math.max(0,this.getSegmentIndexForOffset(this.seekSegments,this.currentBoundaryOffset))}async speakWithPlan(Z,Q,J){if(!this.provider||Z.length===0)return;let Y=J?.highlightMode==="sentence",X=this.provider;if(!Y&&typeof X.speakSegments==="function"){if(await this.waitWhilePaused(Q),Q!==this.speakRunId||this.provider!==X)return;this.currentBoundaryOffset=0;let G=this.provider.onWordBoundary;this.provider.onWordBoundary=(j,B,V)=>{if(G?.(j,B,V),Number.isFinite(B))this.currentBoundaryOffset=B};try{await X.speakSegments(this.segmentsWithinLimit(Z))}finally{if(Q===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=G}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let G of Z){if(await this.waitWhilePaused(Q),Q!==this.speakRunId)return;this.currentBoundaryOffset=G.startOffset;let j=()=>{this.highlightSentenceSegment(G.startOffset,G.text)};if(Y)this.runWhenPlaybackStarts(Q,j);this.wordlessPartHighlight=j;try{await this.speakWithinLimit(G.text,Q)}finally{if(this.wordlessPartHighlight===j)this.wordlessPartHighlight=null}let B=G.pauseMsAfter??0;if(B>0&&Q===this.speakRunId)await this.waitStructuralPause(B)}}highlightSentenceSegment(Z,Q){if(!this.highlightCoordinator||typeof document>"u")return;let J=Q.trimEnd().length;if(J<=0)return;let Y=Z+this.activeWordBoundaryOffset,X=this.normalizedToDOM.get(Y),G=this.normalizedToDOM.get(Y+J-1);if(!X||!G)return;let j=D0(this.normalizedToDOM,Y,Y+J);if(j.length===0)return;this.paintTTSSentenceRanges(j),this.activeSentenceStartOffset=Z}getSegmentIndexForOffset(Z,Q){if(Z.length===0)return-1;let J=-1;for(let Y=0;Y<Z.length;Y++)if(Z[Y].startOffset<=Q)J=Y;else break;return J}highlightSentenceForOffset(Z){let Q=this.sentenceHighlightSegments;if(!this.highlightCoordinator||Q.length===0)return;let J=this.getSegmentIndexForOffset(Q,Z);if(J<0)return;let Y=Q[J];if(!Y)return;if(this.activeSentenceStartOffset===Y.startOffset)return;this.highlightSentenceSegment(Y.startOffset,Y.text)}async speak(Z,Q={}){this.assertNotDisposed();let J=this.pendingReadiness(),Y=Q.ownerId??null,X=J?this.beginRun(Y):null;if(J){try{await J}catch(V){if(X===this.speakRunId)this.setState(R.IDLE);throw V}if(this.assertNotDisposed(),X!==this.speakRunId)return}if(!this.provider){if(X!==null)this.setState(R.IDLE);throw rZ(Error("TTS service not initialized"))}let G=this.resolveReadLanguage(t9(Z)?Z.startContainer:Z,Q.language),j=t9(Z)?this.resolveRangeTarget(Z,Q,G):this.resolveElementTarget(Z,Q,G);if(!j){if(X!==null)this.setState(R.IDLE);return}let B=X??this.beginRun(Y);if(Q.rate!==void 0||Q.pitch!==void 0||Q.volume!==void 0){if(await this.applyRunSettings(Q),B!==this.speakRunId)return}await this.speakContent(j.text,j.options,B)}async applyRunSettings(Z){await this.playbackRateWriteQueue;let Q={};if(Z.rate!==void 0){let J=this.normalizePlaybackRate(Z.rate),Y=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(J!==Y)Q.rate=J}if(Z.pitch!==void 0&&Z.pitch!==this.ttsConfig.pitch)Q.pitch=Z.pitch;if(Z.volume!==void 0&&Z.volume!==this.ttsConfig.volume)Q.volume=Z.volume;if(Object.keys(Q).length>0)await this.updateSettings(Q)}isSuppressedTarget(Z){if(!pZ(Z))return!1;return console.warn("[tts] the content to read lies inside content marked not-to-be-spoken; nothing was spoken."),!0}resolveElementTarget(Z,Q,J){if(this.isSuppressedTarget(Z))return null;let Y={catalogId:Q.catalogId,catalogContext:Q.catalogContext,language:J.locale,contentLanguage:J.contentLanguage,contentElement:Z},X=A0(Z,this.getTextProcessingOptions(J.locale)).visibleText.trim();if(!X&&!this.holdsSpokenCard(Z,Y))return console.warn("[tts] the content to read holds no speakable text; nothing was spoken."),null;return{text:X,options:Y}}holdsSpokenCard(Z,Q){if(!this.catalogResolver)return!1;if(Q.catalogId){if(this.catalogResolver.getAlternative(Q.catalogId,{type:"spoken",language:Q.language,useFallback:!0,context:Q.catalogContext,form:"content"})?.content!==void 0)return!0}return this.collectCatalogSpeechChunks(Z,Q).some((J)=>J.sourceElement)}resolveRangeTarget(Z,Q,J){if(this.isSuppressedTarget(Z.commonAncestorContainer))return null;let Y=Z.commonAncestorContainer,X=Q.contentRoot||(Y.nodeType===Node.ELEMENT_NODE?Y:i(Y));if(!X)return null;let G=a5(Z,X),j=G.text.trim();if(!j){if(G.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return null}let B=this.selectMappedRangeText(Z,X,J.locale),V=j,q=B?.offset??0;if(B)V=B.text;else{let U=document.createRange();U.selectNodeContents(X),U.setEnd(Z.startContainer,Z.startOffset);let $=a5(U,X).text,z=T($);q=z.length+(/\s$/.test($)&&z?1:0)}return t.debug("selection offset calculation:",{selectedText:V,mapped:!!B,offset:q,rootTag:X.tagName}),{text:V,options:{catalogId:Q.catalogId&&DZ(Z,X,X)?Q.catalogId:void 0,catalogContext:Q.catalogContext,language:J.locale,contentLanguage:J.contentLanguage,contentElement:X,contentRange:Z,wordBoundaryOffset:q}}}async speakContent(Z,Q,J){let Y=null;try{if(await this.applyLanguageSettings(Q),J!==this.speakRunId)return;let X=await this.resolveSpeechContent(Z,Q);if(J!==this.speakRunId)return;let{contentToSpeak:G,speechText:j,highlightText:B,normalizedText:V,usedCatalogSpoken:q,speechSource:U,speechMatchesVisibleText:$,speechChunks:z}=X;this.logResolvedSpeechContent({contentToSpeak:G,speechSource:U,catalogId:Q.catalogId}),this.initializeSpeakTracking(B,Q);let A=$?this.resolveHighlightMode():"sentence";this.activeHighlightMode=A;let O=Q.wordBoundaryOffset||0;this.activeWordBoundaryOffset=O;let P=this.hasExplicitBreakSemantics(G),D=!!this.currentContentElement&&!q&&!P&&$;if(this.playbackChunks=z?.length?z:[],this.playbackChunks.length)this.seekSegments=this.createSeekSegmentsFromSpeechChunks(this.playbackChunks);else if(P||!$)this.seekSegments=[];else if(D&&this.currentContentElement)this.seekSegments=this.createSpeechPlan(this.currentContentElement,V,O,Q.language);else this.seekSegments=this.createSeekSegmentsFromText(B);if(this.sentenceHighlightSegments=P?[]:this.createSentenceHighlightSegments({contentToSpeak:B,shouldUsePlan:D,playbackSegments:this.seekSegments}),Y=this.installPlaybackStartBarrier(J,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:B,options:Q,highlightMode:A,shouldUsePlan:D,runId:J}),$)this.configureWordBoundaryHighlighting({highlightMode:A,wordBoundaryOffset:O});else this.clearWordBoundaryHighlighting();if(!Y)this.markPlaying();if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:D,runId:J,highlightMode:A,contentToSpeak:j,speechChunks:z}),J!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(X){if(J!==this.speakRunId)return;throw console.error("TTS error:",X),this.lastError=X instanceof Error?X.message:String(X),this.setState(R.ERROR),this.clearHighlightsAndTracking(),X}finally{this.clearPlaybackStartBarrier(Y)}}async applyLanguageSettings(Z){if(!this.provider)return;this.readLocale=Z.language;let Q=Z.contentLanguage,J=this.providerOptions(),Y={locale:Q??this.hostLocales.locale,textNormalization:Q??this.hostLocales.textNormalization,segmenter:Q??this.hostLocales.segmenter};if(J.contentLanguage===Q&&h0(J.locale)===Y.locale&&h0(J.textNormalization?.locale)===Y.textNormalization&&h0(J.segmenter?.locale)===Y.segmenter)return;let X={...J,locale:Y.locale,textNormalization:{...J.textNormalization,locale:Y.textNormalization},segmenter:{...J.segmenter,locale:Y.segmenter},contentLanguage:Q};this.ttsConfig={...this.ttsConfig,providerOptions:X},await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Z,Q){let J=T(Z);if(Q.catalogId&&this.catalogResolver){let G=this.catalogResolver.getAlternative(Q.catalogId,{type:"spoken",language:Q.language,useFallback:!0,context:Q.catalogContext,form:"content"}),j=G?.content;if(G&&j!==void 0){let B=A0(Q.contentElement,this.getTextProcessingOptions(Q.language)).visibleText||J,V=T(j);return t.debug(`Using catalog content for "${Q.catalogId}" (${G.language})`),{contentToSpeak:j,speechText:j,visibleText:B,highlightText:B,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:B,containsMathMarkup:!1,speechMatchesVisibleText:V===B}}t.debug(`No catalog found for "${Q.catalogId}", falling back to generated TTS`)}let Y=this.resolveCatalogComposedSpeechContent(Q.contentElement,J,Q);if(Y)return Y;return{...await this.resolveGeneratedSpeechContent(Q.contentElement,J,Q.language,Q.contentRange),usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Z,Q,J){if(!this.catalogResolver)return null;let Y=this.collectCatalogSpeechChunks(Z,J);if(!Y.some((j)=>j.sourceElement))return null;let X=T(Y.map((j)=>j.speechText).join(" ")),G=J.contentRange?Q:A0(Z,this.getTextProcessingOptions(J.language)).visibleText||Q;return{contentToSpeak:X,speechText:X,visibleText:G,highlightText:G,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:G,containsMathMarkup:!1,speechMatchesVisibleText:Y.every((j)=>j.speechMatchesVisibleText),speechChunks:Y}}collectCatalogSpeechChunks(Z,Q){let J=this.catalogResolver;if(!J)return[];let Y=[],X="",G=()=>{let $=T(X);if(X="",!$)return;Y.push({speechText:$,visibleText:$,sourceElement:null,speechMatchesVisibleText:!0})},j=Q.contentRange,B=($)=>{let z=$.getAttribute("data-catalog-idref");if(!z)return null;if(j&&!DZ(j,$,Z))return null;let A={type:"spoken",language:n5($,Z)||Q.language,useFallback:!0,context:Q.catalogContext},O=J.getAlternative(z,{...A,form:"payload"}),P=O?.payload?d8({payload:O.payload})??void 0:void 0,N=J.getAlternative(z,{...A,form:"content"})?.content;if(P===void 0&&N===void 0)return null;return{script:N,audio:P}},V=($,z)=>{let A=q($);if(A.length!==1)return null;let O=A[0],P=A0(O,this.getTextProcessingOptions(Q.language)).visibleText||T(O.textContent||""),D=(N)=>T(N).replace(/\s+/g,"");return D(P)===D(z)?O:null},q=($)=>{let z=I8($,"math");if($.localName?.toLowerCase()==="math")return[$,...z];return z},U=($)=>{if(z0($,Z))return;if($.nodeType===Node.TEXT_NODE){if(!j)X+=` ${$.textContent||""}`;else if(G0(j,$))X+=` ${o5($,j)}`;return}if($.nodeType!==Node.ELEMENT_NODE)return;let z=$,A=B(z);if(A){G();let O=A0(z,this.getTextProcessingOptions(Q.language)),P=O.visibleText||T(f8(z)),D=nZ(z,Z),N=null;if(A.script!==void 0){let M=A.script,C=iZ({speechText:M,visibleText:P}),E=V(z,P),v=E?e0({mathElement:E,speechText:M}):void 0,S=v?void 0:q(z).map((g)=>({element:g,alignment:e0({mathElement:g,speechText:M})}));N={speechText:M,visibleText:P,sourceElement:z,regionElement:D,speechMatchesVisibleText:T(M)===P,playbackMode:C.playbackMode,alignment:C,mathAlignment:v,mathAlignments:S,visibleMap:O.map}}if(A.audio){Y.push(N?{...N,audio:A.audio,plainFallback:N}:{speechText:P,visibleText:P,sourceElement:z,regionElement:D,speechMatchesVisibleText:!1,visibleMap:O.map,audio:A.audio});return}if(N)Y.push(N);return}for(let O of F0(z))U(O)};return U(Z),G(),Y}resolveGeneratedPlaybackFormat(){let Z=this.currentProvider;if(!Z)return"plain";return Z.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Z,Q,J,Y){let X=this.resolveGeneratedPlaybackFormat(),{plan:G,containsMathMarkup:j,visibleText:B}=await H7({contentRoot:Z,range:Y,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:X==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver});if(!j){let $=Y?Q:B||Q;return{contentToSpeak:$,speechText:$,visibleText:$,highlightText:$,normalizedText:$,containsMathMarkup:!1,speechMatchesVisibleText:!0}}let V=B||Q,q=D7(G,{format:X}),U=G.plainSpeechText;return{contentToSpeak:U,speechText:U,visibleText:V,highlightText:V,normalizedText:V,containsMathMarkup:!0,speechMatchesVisibleText:U===V,speechChunks:q}}logResolvedSpeechContent(Z){let Q=Z.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);t.debug("Speak resolved content",{source:Z.speechSource,catalogId:Z.catalogId||null,length:Z.contentToSpeak.length,preview:Q})}initializeSpeakTracking(Z,Q){this.currentText=Z,this.currentContentElement=Q.contentElement,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Z){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Z.contentToSpeak,Z.options.language),Z.highlightMode==="sentence"&&Z.shouldUsePlan)return;let Q=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Z.runId,()=>{if(Q)this.highlightSentenceSegment(Q.startOffset,Q.text),t.debug("Applied initial sentence highlighting");else try{let J=document.createRange();J.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([J])}catch{}})}configureWordBoundaryHighlighting(Z){if(!this.provider)return;if(Z.highlightMode==="sentence"){this.provider.onWordBoundary=void 0;return}if(!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(Q,J,Y)=>{let X=Y||Q.length,G=J+this.currentBoundaryOffset,j=G+Z.wordBoundaryOffset;this.highlightSentenceForOffset(G);let B=D0(this.normalizedToDOM,j,j+X);if(B.length===0){t.debug(`no text at position ${j}, length ${X}, to highlight`);return}t.debug(`Highlighting "${B.join("")}" (word: "${Q}") at position ${j}`),this.paintTTSWord(B)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Z){let Q=Z.regionElement||Z.sourceElement;if(!Q&&!Z.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Z.regionRange){let Y=D0(Z.visibleMap,0,Z.visibleText.length);this.highlightCoordinator.clearTTSWord(),this.paintTTSSentenceRanges(Y.length>1?Y:[Z.regionRange]);return}if(!Q)return;let J=document.createRange();J.selectNodeContents(Q),this.highlightCoordinator.clearTTSWord(),this.paintTTSSentenceRanges([J])}catch{}}highlightRenderableRegionTarget(Z){if(!this.highlightCoordinator||!Z||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&A2(this.lastRenderedRegionTarget,Z))return;try{let Q=document.createRange();if(Z.type==="element")Q.selectNodeContents(Z.element);else if(Z.type==="range"){this.paintTTSSentenceRanges(Z.ranges??[Z.range]),this.lastRenderedRegionTarget=Z;return}else Q.setStart(Z.node,Z.startOffset),Q.setEnd(Z.node,Z.endOffset);this.paintTTSSentenceRanges([Q]),this.lastRenderedRegionTarget=Z}catch{}}highlightRenderableActiveTarget(Z){if(!this.highlightCoordinator||typeof document>"u")return;if(!Z){this.highlightCoordinator.clearTTSWord();return}if(Z.type==="text-range"){let X=this.createTextRange(Z.node,Z.startOffset,Z.endOffset);if(X)this.paintTTSWord([X]);return}if(Z.type==="range"){this.paintTTSWord(Z.ranges??[Z.range]);return}let Q=document.createRange();Q.selectNodeContents(Z.element);let J=this.resolveWordHighlightRange(Q);if(J.remapped){this.highlightCoordinator.highlightTTSWord([J.range]);return}let Y=Z.element.childNodes.length===1?Z.element.firstChild:null;if(Z.quality==="semantic-token"&&Y?.nodeType===Node.TEXT_NODE){let X=document.createRange();X.selectNodeContents(Y),this.highlightCoordinator.highlightTTSWord([X]);return}this.highlightCoordinator.highlightTTSWordElement(Z.element)}renderHighlightDecision(Z){this.highlightRenderableRegionTarget(Z.regionTarget),this.highlightRenderableActiveTarget(Z.activeTarget)}async speakCatalogChunk(Z,Q){try{await this.speakCatalogChunkOnce(Z,Q)}catch(J){if(Z.plainFallback&&Q===this.speakRunId){if(t.debug("SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),this.playbackStartDeferredRunId===Q&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.markPlaying();await this.speakCatalogChunkOnce(Z.plainFallback,Q);return}throw J}}async playRecordedAudio(Z,Q){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let J=Z.sources[0],Y=document.createElement("audio");Y.preload="auto",Y.src=U2(J.src,Z.fragment),Y.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,G)=>{let j,B=!1,V=!1,q=()=>{if(V||B)return;B=!0,Q?.()},U=()=>{if(Y.removeEventListener("ended",$),Y.removeEventListener("error",z),Y.removeEventListener("playing",q),j?.(),this.activeRecordedAudio?.element===Y)this.activeRecordedAudio=null},$=()=>{if(V)return;V=!0,U(),X()},z=()=>{if(V)return;V=!0,U(),G(Error(`[tts] recorded audio failed to play: ${J.src}`))},A=()=>{Promise.resolve(Y.play()).then(q).catch((O)=>{if(O?.name==="AbortError"&&this.state===R.PAUSED)return;z()})};this.activeRecordedAudio={element:Y,cancel:()=>{if(V)return;V=!0,U(),Y.pause(),X()},play:A},Y.addEventListener("ended",$),Y.addEventListener("error",z),Y.addEventListener("playing",q),j=$2(Y,Z.fragment,$),A()}).finally(()=>{if(this.activeRecordedAudio?.element===Y)this.activeRecordedAudio=null;Y.pause(),Y.removeAttribute("src")})}cancelRecordedAudio(){let Z=this.activeRecordedAudio;if(!Z)return;this.activeRecordedAudio=null,Z.cancel()}async speakCatalogChunkOnce(Z,Q){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Z.audio){this.runWhenPlaybackStarts(Q,()=>{this.highlightCatalogRegion(Z)}),await this.playRecordedAudio(Z.audio,()=>{this.notifyPlaybackStarted(Q)});return}let J=Z.regionElement||Z.sourceElement||this.currentContentElement,Y=J?l9({contentRoot:J,chunks:[Z]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,G=Y?i9({chunks:[Y],mathTokenHighlighting:X}):null,j=!Y||Y.offsetSpace==="unsupported"?"unknown":Y.offsetSpace;if(this.runWhenPlaybackStarts(Q,()=>{if(G&&Y&&Z.mathAlignment)this.renderHighlightDecision(G.resolveInitial(Y.id));else this.highlightCatalogRegion(Z)}),!(this.resolveHighlightMode()==="word"&&Z.sourceElement&&(Z.mathAlignment&&Z.mathAlignment.speech.tokens.length>0||Z.mathAlignments&&Z.mathAlignments.length>0||Z.alignment&&Z.visibleMap&&(Z.playbackMode==="exact-word"||Z.playbackMode==="anchor-span")))){let $=this.provider,z=$.onWordBoundary;$.onWordBoundary=void 0;try{await this.speakWithinLimit(Z.speechText,Q)}finally{if(this.provider===$&&Q===this.speakRunId&&$.onWordBoundary===void 0)$.onWordBoundary=z}return}let V=this.provider,q=V.onWordBoundary,U=($,z,A)=>{if(Q!==this.speakRunId||!G||!Y)return;this.renderHighlightDecision(G.resolveBoundary({chunkId:Y.id,word:$,position:z,length:A,providerOffsetSpace:j}))};V.onWordBoundary=U;try{await this.speakWithinLimit(Z.speechText,Q)}finally{if(this.provider===V&&Q===this.speakRunId&&V.onWordBoundary===U)V.onWordBoundary=q}}async executeSpeakPlayback(Z){if(Z.speechChunks?.length&&this.provider){for(let Q=0;Q<Z.speechChunks.length;Q++){if(await this.waitWhilePaused(Z.runId),Z.runId!==this.speakRunId)return;let J=this.seekSegments[Q];if(J)this.currentBoundaryOffset=J.startOffset;let Y=Z.speechChunks[Q];await this.speakCatalogChunk(Y,Z.runId)}return}if(Z.shouldUsePlan&&this.currentContentElement&&this.seekSegments.length>0){await this.speakWithPlan(this.seekSegments,Z.runId,{highlightMode:Z.highlightMode});return}await this.speakWithinLimit(Z.contentToSpeak,Z.runId)}clearHighlightsAndTracking(){if(this.clearWordBoundaryHighlighting(),this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.activeSentenceStartOffset=null,this.wordlessPartHighlight=null}selectMappedRangeText(Z,Q,J){if(typeof Z.comparePoint!=="function")return null;let{text:Y,map:X}=S0(Q,this.getTextProcessingOptions(J)),G=-1,j=-1;for(let[U,{node:$,offset:z}]of X){if(U>=Y.length)continue;if(!FZ(Z,$,z))continue;if(G===-1||U<G)G=U;if(U>j)j=U}if(G===-1)return null;let B=Y.slice(G,j+1),V=B.length-B.trimStart().length,q=B.trim();return q?{text:q,offset:G+V}:null}pause(){if(this.state!==R.PLAYING&&this.state!==R.LOADING)return;this.resumeState=this.state,this.activeRecordedAudio?.element.pause(),this.provider?.pause(),this.setState(R.PAUSED)}resume(){if(this.state!==R.PAUSED)return;this.setState(this.resumeState),this.activeRecordedAudio?.play(),this.provider?.resume(),this.releasePauseHold()}normalizePlaybackRate(Z){if(!Number.isFinite(Z))return 1;return Math.max(r9,Math.min(a9,Z))}async restartFromSeekIndex(Z){if(!this.provider||this.seekSegments.length===0)return;let Q=Math.max(0,Math.min(this.seekSegments.length-1,Z)),J=this.playbackChunks.length?this.playbackChunks.slice(Q):null,Y=this.state===R.PAUSED;this.speakRunId+=1,this.abandonRun(),this.provider.onWordBoundary=void 0,this.provider.stop();let X=++this.speakRunId;this.restartRunId=X;let G=this.seekSegments.slice(Q);if(this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.currentBoundaryOffset=this.seekSegments[Q].startOffset,!Y)this.setState(R.LOADING);let j=this.installPlaybackStartBarrier(X,!!J?.[0]?.audio);if(Y)this.resumeState=j?R.LOADING:R.PLAYING;else if(!j)this.setState(R.PLAYING);this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),J)for(let B=0;B<J.length;B++){if(await this.waitWhilePaused(X),X!==this.speakRunId)return;let V=Q+B,q=this.seekSegments[V];if(q)this.currentBoundaryOffset=q.startOffset;await this.speakCatalogChunk(J[B],X)}else await this.speakWithPlan(G,X,{highlightMode:this.activeHighlightMode});if(X!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(B){if(X!==this.speakRunId){t.debug("Superseded seek restart failed:",B);return}throw this.lastError=B instanceof Error?B.message:String(B),this.setState(R.ERROR),this.clearHighlightsAndTracking(),B}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Z){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Q=this.normalizePlaybackRate(Z),J=this.pendingPlaybackRateRequest;if(J?.rate===Q){await J.promise;return}let Y=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let B=this.speakRunId;if(Y!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:B};let V=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Q===V)return{didUpdate:!1,playbackRunId:B};return await this.updateSettings({rate:Q}),{didUpdate:!0,playbackRunId:B}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let G=X.then(async(B)=>{if(Y!==this.playbackRateRequestId||B.playbackRunId!==this.speakRunId)return;let V=this.activePlaybackRate!==null&&this.activePlaybackRate!==Q;if(!B.didUpdate&&!V)return;if(this.state!==R.PLAYING&&this.state!==R.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),j;j=G.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===j)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:Q,promise:j},await j}async seekBy(Z){if(!this.provider||!this.currentText)return;let Q=this.state===R.LOADING&&this.restartRunId===this.speakRunId;if(this.state!==R.PLAYING&&this.state!==R.PAUSED&&!Q)return;if(this.hasExplicitBreakSemantics(this.currentText))return;if(this.seekSegments.length===0)return;let J=Number.isFinite(Z)?Math.trunc(Z):0;if(J===0)return;let Y=this.getCurrentSeekSegmentIndex(),X=Math.max(0,Math.min(this.seekSegments.length-1,Y+J));if(X===Y)return;await this.restartFromSeekIndex(X)}async seekForward(Z=1){let Q=Number.isFinite(Z)?Math.max(1,Math.trunc(Z)):1;await this.seekBy(Q)}async seekBackward(Z=1){let Q=Number.isFinite(Z)?Math.max(1,Math.trunc(Z)):1;await this.seekBy(-Q)}stop(){this.speakRunId+=1,this.abandonRun(),this.provider?.stop(),this.clearHighlightsAndTracking(),this.currentText=null;let Z=this.runOwner!==null;this.runOwner=null,this.setState(R.IDLE,Z)}releaseProvider(){this.stop(),this.provider=null,this.currentProvider=null}dispose(){if(this.disposed)return;this.releaseProvider(),this.disposed=!0,this.speakRunId+=1,this.abandonRun(),this.playbackRateRequestId+=1,this.pendingPlaybackRateRequest=null,this.listeners.clear(),this.readinessGate=null,this.mathSpeechSource=null,this.highlightTargetResolverProvider=null,this.highlightCoordinator=null,this.catalogResolver=null,this.telemetryReporter=null}getState(){return this.state}getRunOwner(){return this.runOwner}onStateChange(Z){let Q=(J)=>Z(J);return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}setState(Z,Q=!1){let J=this.state;if(J===Z&&!Q)return;this.state=Z;for(let Y of[...this.listeners])Y(Z);if(J===Z)return;if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",previousState:J,state:Z}),Z===R.PLAYING){let Y=J===R.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(Y,{toolId:"textToSpeech",previousState:J,state:Z});return}if(Z===R.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",previousState:J,state:Z});return}if(Z===R.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",previousState:J,state:Z,message:this.lastError||void 0});return}if(Z===R.IDLE&&(J===R.PLAYING||J===R.PAUSED||J===R.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",previousState:J,state:Z})}}import{createPieLogger as _2,isGlobalDebugEnabled as M2}from"@pie-players/pie-players-shared/pie";var JZ=_2("ToolProviderRegistry",M2);function YZ(Z){let Q=Z&&typeof Z==="object"?Z.backend:void 0;return typeof Q==="string"&&Q?Q:"unknown"}class aZ{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Z,Q,J){try{await Z.onTelemetry?.(Q,J)}catch(Y){console.warn("[ToolProviderRegistry] Telemetry callback failed:",Y)}}register(Z,Q){let J=this.providers.get(Z),Y=this.initializationPromises.get(Z);if(this.providers.set(Z,Q.provider),this.configs.set(Z,Q),this.initialized.set(Z,!1),this.initializationPromises.delete(Z),J)if(Y)Y.catch(()=>{}).then(()=>this.destroyProvider(Z,J));else this.destroyProvider(Z,J);if(JZ.debug(`${J?"Replaced":"Registered"} provider "${Z}" (${Q.provider.providerName})`),Q.lazy===!1)this.initialize(Z).catch((X)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Z}":`,X)})}async initialize(Z){if(this.initialized.get(Z))return;let Q=this.initializationPromises.get(Z);if(Q)return Q;let J=this.providers.get(Z),Y=this._doInitialize(Z);this.initializationPromises.set(Z,Y);try{await Y}catch(X){if(!this.isReplaced(Z,J))throw X}finally{if(this.initializationPromises.get(Z)===Y)this.initializationPromises.delete(Z)}if(this.isReplaced(Z,J))return this.initialize(Z)}isReplaced(Z,Q){let J=this.providers.get(Z);return J!==void 0&&J!==Q}destroyProvider(Z,Q){try{Q.destroy()}catch(J){console.warn(`[ToolProviderRegistry] Failed to destroy provider "${Z}":`,J)}}async _doInitialize(Z){let Q=this.providers.get(Z),J=this.configs.get(Z);if(!Q||!J)throw Error(`[ToolProviderRegistry] Provider "${Z}" not registered`);let Y={...J.config},X=Date.now();if(await this.emitTelemetry(J,"pie-tool-init-start",{toolId:Z,backend:YZ(Y),operation:"provider-initialize"}),Q.requiresAuth&&J.authFetcher){let G=Date.now();await this.emitTelemetry(J,"pie-tool-backend-call-start",{toolId:Z,backend:YZ(Y),operation:"auth-fetch"}),JZ.debug(`Fetching auth for "${Z}"...`);try{let j=await J.authFetcher();Y={...Y,...j},await this.emitTelemetry(J,"pie-tool-backend-call-success",{toolId:Z,backend:YZ(Y),operation:"auth-fetch",duration:Date.now()-G})}catch(j){throw await this.emitTelemetry(J,"pie-tool-backend-call-error",{toolId:Z,backend:YZ(Y),operation:"auth-fetch",duration:Date.now()-G,errorType:"ProviderAuthFetchError",message:j instanceof Error?j.message:String(j)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Z}":`,j),Error(`Failed to fetch auth credentials for provider "${Z}"`)}}try{if(await Q.initialize(Y),this.providers.get(Z)===Q)this.initialized.set(Z,!0);await this.emitTelemetry(J,"pie-tool-init-success",{toolId:Z,backend:YZ(Y),operation:"provider-initialize",duration:Date.now()-X}),JZ.debug(`Provider "${Z}" initialized`)}catch(G){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Z,backend:YZ(Y),operation:"provider-initialize",duration:Date.now()-X,errorType:"ProviderInitializationError",message:G instanceof Error?G.message:String(G)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Z}":`,G),G}}async getProvider(Z,Q=!0){let J=this.providers.get(Z);if(!J)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Z,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Z}" not registered`);if(Q&&!this.initialized.get(Z))JZ.debug("Auto-initializing provider:",Z),await this.initialize(Z);return J}getProvidersByCategory(Z){return Array.from(this.providers.entries()).filter(([Q,J])=>J.category===Z).map(([Q])=>Q)}getProviderIds(){return Array.from(this.providers.keys())}has(Z){return this.providers.has(Z)}isInitialized(Z){return this.initialized.get(Z)===!0}isInitializing(Z){return this.initializationPromises.has(Z)}async unregister(Z){let Q=this.providers.get(Z);if(Q){let J=this.initializationPromises.get(Z);if(J){try{await J}catch{}if(this.providers.get(Z)!==Q)return}this.destroyProvider(Z,Q),this.providers.delete(Z),this.configs.delete(Z),this.initialized.delete(Z),this.initializationPromises.delete(Z),JZ.debug(`Unregistered provider "${Z}"`)}}async destroy(){let Z=Array.from(this.providers.keys());await Promise.all(Z.map((Q)=>this.unregister(Q))),JZ.debug("Registry destroyed")}}import{languageTagWithoutVariants as O2}from"@pie-players/pie-players-shared/i18n/language-tags";import{createPieLogger as L2,isTtsDebugEnabled as P2}from"@pie-players/pie-players-shared/pie";var Y1=L2("browser-tts-provider",P2),X1=5000,B1=2000,G1=260,N2=80,w2=["__pieTelemetry","contentLanguage","highlightMode","locale","mathSpeech","segmenter","structuralPauses","textNormalization"],W1=(Z)=>{let Q={};if(Z.rate!==void 0)Q.rate=Z.rate;if(Z.pitch!==void 0)Q.pitch=Z.pitch;if(Z.volume!==void 0)Q.volume=Z.volume;if(Z.mathTokenHighlighting!==void 0)Q.mathTokenHighlighting=Z.mathTokenHighlighting;let J=Z.providerOptions;if(J&&typeof J==="object"){let Y={};for(let X of w2)if(J[X]!==void 0)Y[X]=J[X];if(Object.keys(Y).length>0)Q.providerOptions=Y}return Q},j1=(Z)=>{if(!cZ(Z))return{text:Z,sourceOffset:(X)=>X};let{spokenText:Q,rawToSpokenOffsetMap:J}=dZ(Z),Y=[];for(let[X,G]of J){let j=Y[G];if(j===void 0||X<j)Y[G]=X}return{text:Q,sourceOffset:(X)=>{for(let G=X;G>=0;G--){let j=Y[G];if(j!==void 0)return j}return 0}}},M7=(Z)=>String(Z||"").trim().toLowerCase(),R2=()=>{let Z=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return M7(Z||"en-US")},C2=(Z,Q)=>{let J=M7(Q)||R2(),Y=J.split("-")[0]||"en",X=M7(Z.lang);return X===J||X.startsWith(`${Y}-`)},b2=(Z,Q,J)=>{if(Q)return Z.find((G)=>G.voiceURI===Q)||Z.find((G)=>G.name===Q)||null;let Y=(G)=>C2(G,J),X=[(G)=>G.localService&&Y(G),(G)=>G.default&&Y(G),(G)=>Y(G),(G)=>G.localService,(G)=>G.default];for(let G of X){let j=Z.find(G);if(j)return j}return Z[0]||null},E2=(Z,Q,J=()=>!0)=>{if(Z.getVoices().length>0)return Promise.resolve(!0);let Y=typeof Z.addEventListener==="function"&&typeof Z.removeEventListener==="function";if(!Y&&!("onvoiceschanged"in Z))return Promise.resolve(!1);return new Promise((X)=>{let G=Y?null:Z.onvoiceschanged,j=!1,B=(z)=>{if(j)return;if(j=!0,clearTimeout($),Y)Z.removeEventListener("voiceschanged",q);else if(Z.onvoiceschanged===U)Z.onvoiceschanged=G;X(z)},V=()=>{if(!J())B(!1);else if(Z.getVoices().length>0)B(!0)},q=()=>V(),U=(z)=>{try{G?.call(Z,z)}finally{V()}},$=setTimeout(()=>B(!1),Q);if(Y)Z.addEventListener("voiceschanged",q);else Z.onvoiceschanged=U;V()})},S2=(Z)=>!Z.default;class O7{providerId="browser";async initialize(Z){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");if(typeof Z.voice==="string"&&Z.voice.trim())await E2(window.speechSynthesis,B1);return new V1(Z)}getCapabilities(){return{supportsWordBoundary:!0,defaultHighlightMode:"sentence",supportsSSML:!1}}destroy(){}}class V1{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;activeRunId=null;releasePauseHold=null;settlePendingChunk=null;settlePendingGap=null;onPlaybackStart=void 0;constructor(Z){this.config=Z}async waitWhilePaused(Z){while(this._isPaused&&Z===this.speakRunId)await new Promise((Q)=>{this.releasePauseHold=Q});return Z===this.speakRunId}releaseHold(){let Z=this.releasePauseHold;this.releasePauseHold=null,Z?.()}resolveBrowserVoice(){let Z=typeof this.config?.voice==="string"?this.config.voice.trim():"",Q=speechSynthesis.getVoices();if(Z&&Q.length===0)throw Error(`Configured browser voice "${Z}" could not be resolved because the browser did not publish its voice inventory within ${B1/1000} seconds.`);let J=b2(Q,Z||void 0,this.getContentLocale());if(Z&&!J)throw Error(`Configured browser voice "${Z}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return J}async speak(Z){if(!this.config)throw Error("TTS not initialized");this.stop();let Q=this.speakRunId;this.activeRunId=Q;try{let J=this.resolveBrowserVoice(),Y=j1(Z),X=this.splitIntoChunks(Y.text);for(let G of X){if(this._isPaused&&!await this.waitWhilePaused(Q))break;if(!await this.speakChunk(G.text,G.offset,Q,J,Y.sourceOffset))break}}finally{if(this.activeRunId===Q)this.activeRunId=null}}async speakSegments(Z){if(!this.config)throw Error("TTS not initialized");this.stop();let Q=this.speakRunId;this.activeRunId=Q;try{let J=this.resolveBrowserVoice();for(let Y of Z){if(Q!==this.speakRunId)break;let X=j1(Y.text),G=this.splitIntoChunks(X.text);for(let B of G){if(this._isPaused&&!await this.waitWhilePaused(Q))break;if(!await this.speakChunk(B.text,B.offset,Q,J,(q)=>Y.startOffset+X.sourceOffset(q)))break}let j=Math.max(0,Number(Y.pauseMsAfter||0));if(j>0&&Q===this.speakRunId){if(!await this.waitForPause(j,Q))break}}}finally{if(this.activeRunId===Q)this.activeRunId=null}}async waitForPause(Z,Q){return await new Promise((J)=>{let Y=()=>{if(clearTimeout(X),this.settlePendingGap===Y)this.settlePendingGap=null;J()},X=setTimeout(Y,Z);this.settlePendingGap=Y}),Q===this.speakRunId}splitIntoChunks(Z){if(Z.length<=G1)return[{text:Z,offset:0}];let Q=this.segmentSentences(Z),J=[],Y="",X=0;for(let G of Q){let j=G.text.trim();if(!j)continue;let B=G.text.search(/\S/),V=G.offset+(B===-1?0:B);if(!Y){Y=j,X=V;continue}let q=`${Y} ${j}`;if(q.length<=G1)Y=q;else J.push({text:Y,offset:X}),Y=j,X=V}if(Y)J.push({text:Y,offset:X});return J.length?J:[{text:Z,offset:0}]}getContentLocale(){let Z=this.config?.providerOptions?.contentLanguage;return typeof Z==="string"&&Z.trim()?O2(Z):void 0}getSegmentationPolicy(){let Z=this.config?.providerOptions||{},Q=Z.segmenter||{},Y=Q.mode!=="regexOnly",X=typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:typeof Z.locale==="string"&&Z.locale.trim().length>0?Z.locale:void 0;return{useSentenceSegmenter:Y,locale:X}}segmentSentences(Z){let Q=this.getSegmentationPolicy();return v0(Z,{locale:Q.locale,useSentenceSegmenter:Q.useSentenceSegmenter})}inferWordLength(Z,Q){let J=Math.max(0,Math.min(Q,Math.max(0,Z.length-1)));return Z.slice(J).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Z,Q,J,Y,X){return new Promise((G,j)=>{if(J!==this.speakRunId){G(!1);return}let B=new SpeechSynthesisUtterance(Z);this.utterance=B;let V=this.getContentLocale();if(V)B.lang=V;if(Y&&S2(Y))B.voice=Y;if(this.config?.rate)B.rate=this.config.rate;if(this.config?.pitch!==void 0)B.pitch=this.config.pitch;if(this.config?.volume!==void 0)B.volume=this.config.volume;let q=!1,U=!1,$=null,z=null,A=()=>{if(this.utterance===B)this.utterance=null},O=()=>{if($!==null)clearTimeout($),$=null},P=()=>{B.onstart=null,B.onend=null,B.onerror=null,B.onpause=null,B.onresume=null,B.onboundary=null},D=(M,C)=>{if(U)return;if(U=!0,O(),P(),A(),z&&this.settlePendingChunk===z)this.settlePendingChunk=null;if(J===this.speakRunId)this._isPlaying=!1;if(C)j(C);else G(M)},N=(M)=>Error(M==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${X1/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);z=()=>D(!1),this.settlePendingChunk=z,B.onstart=()=>{if(J!==this.speakRunId){D(!1);return}if(q=!0,O(),this._isPlaying=!0,this._isPaused)speechSynthesis.pause();try{this.onPlaybackStart?.()}catch(M){console.error("Browser TTS playback-start callback failed",M)}},B.onend=()=>{if(J!==this.speakRunId){D(!1);return}if(!q){D(!1,N("ended"));return}D(!0)},B.onerror=(M)=>{if(J!==this.speakRunId){D(!1);return}if(M.error==="interrupted"||M.error==="canceled"){D(!1);return}D(!1,Error(`Speech synthesis error: ${M.error}`))},B.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},B.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},B.onboundary=(M)=>{if(J!==this.speakRunId)return;if(Y1.debug(`boundary event: ${M.name}, charIndex ${M.charIndex}, charLength ${M.charLength}`),M.name!=="word"||!this.onWordBoundary)return;let C=Math.max(0,Math.min(M.charIndex,Math.max(0,Z.length-1))),E=Number(M.charLength||0),v=this.inferWordLength(Z,C),S=Number.isFinite(E)&&E>0&&E<=N2&&C+E<=Z.length?E:v,g=Z.substring(C,Math.min(Z.length,C+S)).trim(),e=Q+C,r=X(e),q0=X(e+S-1)+1-r;Y1.debug(`word boundary "${g}" at ${r}`),this.onWordBoundary(g,r,q0)},$=setTimeout(()=>{if(U||q||J!==this.speakRunId)return;D(!1,N("timedOut")),speechSynthesis.cancel()},X1);try{speechSynthesis.speak(B)}catch(M){D(!1,M instanceof Error?M:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPaused)return;if(this._isPlaying)speechSynthesis.pause(),this._isPaused=!0;else if(this.activeRunId===this.speakRunId)this._isPaused=!0}resume(){if(!this._isPaused)return;if(this._isPaused=!1,this._isPlaying)speechSynthesis.resume();this.releaseHold()}stop(){let Z=this.utterance,Q=this._isPlaying||Z!==null;if(this.speakRunId+=1,this.activeRunId=null,this.settlePendingChunk?.(),this.settlePendingGap?.(),Q)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1,this.releaseHold()}updateSettings(Z){if(!this.config)this.config={};if(Z.rate!==void 0)this.config.rate=Z.rate;if(Z.pitch!==void 0)this.config.pitch=Z.pitch;if(Z.volume!==void 0)this.config.volume=Z.volume;if(Z.voice!==void 0)this.config.voice=Z.voice;if(Z.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Z.providerOptions||{}}}onWordBoundary}var y2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),K1=(Z)=>Z&&typeof Z==="object"?Z:{},K0=(Z,Q)=>Z===void 0?Q:Z,q1=(Z)=>oZ(Z)==="server"&&Z.serverProvider==="custom"?"custom":"pie",T2=(Z)=>typeof Z==="string"&&y2.has(Z)?Z:"left-aligned",nY=Object.freeze([{rate:0.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);var rY=Object.freeze([0.8,1,1.25]);var x2=(Z)=>{let Q={...Z,layoutMode:T2(Z.layoutMode)};if(Z.backend!=="server")return Q;let J={...Q,apiEndpoint:K0(Q.apiEndpoint,"/api/tts"),transportMode:K0(Q.transportMode,q1(Z)),endpointValidationMode:K0(Q.endpointValidationMode,"voices"),includeAuthOnAssetFetch:K0(Q.includeAuthOnAssetFetch,!1),rate:K0(Q.rate,1),language:K0(Q.language,"en-US")};if(Z.serverProvider==="polly")return{...J,engine:K0(J.engine,"neural"),format:K0(J.format,"mp3"),speechMarksMode:K0(J.speechMarksMode,"word+sentence")};return J},L7=(Z)=>{let{enabled:Q,provider:J,...Y}=K1(Z);return x2(Y)},oZ=(Z)=>Z.backend||"browser",P7=(Z)=>{let Q=oZ(Z)==="server"?Z.serverProvider:void 0,J=Q==="polly",Y=Z.transportMode||q1(Z),X=V0(Z.mathSpeech);return{voice:Z.defaultVoice,rate:Z.rate,pitch:Z.pitch,providerOptions:{...K1(Z.providerOptions),...Z.language?{locale:Z.language}:{},...J&&Z.engine?{engine:Z.engine}:{},...J&&typeof Z.sampleRate==="number"?{sampleRate:Z.sampleRate}:{},...J&&Z.format?{format:Z.format}:{},...J?{speechMarkTypes:Z.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...Y==="custom"&&typeof Z.cache==="boolean"?{cache:Z.cache}:{},...Y==="custom"&&Z.speedRate?{speedRate:Z.speedRate}:{},...Y==="custom"&&Z.lang_id?{lang_id:Z.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Z.apiEndpoint,provider:Q,language:Z.language,transportMode:Y,endpointMode:Z.endpointMode,endpointValidationMode:Z.endpointValidationMode,includeAuthOnAssetFetch:Z.includeAuthOnAssetFetch,assetOrigins:Z.assetOrigins,credentials:Z.credentials,headers:Z.headers,...typeof Z.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Z.mathTokenHighlighting}:{}}};var m="textToSpeech";function $1(Z,Q,J){if(Z!==m||!U1(Q.mathSpeech)||!U1(J.mathSpeech))return;return{...Q.mathSpeech,...J.mathSpeech}}function U1(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}class N7{host;initialized=!1;degraded=!1;initPromise;reconfigurePromise;reportedMissingProvider=!1;heldMissingProviderBackend=null;constructor(Z){this.host=Z}get started(){return this.initialized}get failedUngranted(){return this.degraded}ownsTool(Z){return Z===m}isStarted(){return this.initialized||this.initPromise!==void 0||this.reconfigurePromise!==void 0}flushInitPromises(Z){if(this.initPromise)Z.add(this.initPromise);if(this.reconfigurePromise)Z.add(this.reconfigurePromise)}mathSpeechRuntimeOptions(){return P7(L7(this.resolveToolConfig())).providerOptions?.mathSpeech}async ensureReady(){if(this.host.assertNotDisposed(),await this.waitForPendingReconfigure(),this.host.assertNotDisposed(),this.initialized)return;if(this.initPromise)return this.initPromise;return this.initPromise=this.initializeIfNeeded().then(()=>this.host.assertNotDisposed()).finally(()=>{this.initPromise=void 0,this.host.notifyReadyChange()}),this.initPromise}waitForPendingReconfigure(){let Z=this.reconfigurePromise;return(async()=>{while(Z)await Z,Z=this.reconfigurePromise})()}async initializeIfNeeded(){if(this.initialized)return;let Z=this.resolveToolConfig(),Q=L7(Z),J=oZ(Q),Y=P7(Q);if(await this.host.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:J}}),this.host.assertNotDisposed(),await this.host.emitTelemetry("pie-toolkit-tts-init-start",{backend:J}),await this.host.emitTelemetry("pie-tool-init-start",{toolId:m,operation:"tts-init",backend:J}),this.host.toolProviderRegistry.has(m))try{let j=await(await this.host.initializeProvider(m,!0)).createInstance();await this.initializeService(j,Y),await this.host.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.host.emitTelemetry("pie-tool-init-success",{toolId:m,operation:"tts-init",backend:J,provider:"registry"});return}catch(G){if(this.host.isDisposalError(G))throw G;let j=G instanceof Error?G:Error(String(G));await this.host.emitTelemetry("pie-tool-init-fallback",{toolId:m,operation:"tts-init",backend:J,fromProvider:"registry",toProvider:"browser",reason:j.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",j)}else if(J!=="browser")this.reportMissingProvider(J);let X=new O7;try{await this.initializeService(X,J==="browser"?Y:W1(Y)),await this.host.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.host.emitTelemetry("pie-tool-init-success",{toolId:m,operation:"tts-init",backend:J,provider:"browser-fallback"})}catch(G){if(this.host.isDisposalError(G))throw G;let j=G instanceof Error?G:Error(String(G));throw this.host.reportStartFailure(j,{phase:"tts-init"},[m]),await this.host.emitTelemetry("pie-toolkit-tts-init-error",{message:j.message}),await this.host.emitTelemetry("pie-tool-init-error",{toolId:m,operation:"tts-init",backend:J,errorType:"TTSInitError",message:j.message}),j}}resolveToolConfig(){return this.host.providersConfig()?.[m]||{}}async initializeService(Z,Q){let J={...Q.providerOptions,__pieTelemetry:async(X,G)=>{await this.host.emitTelemetry(X,{toolId:m,...G||{}})}},Y={...Q,providerOptions:J};await this.host.ttsService.initialize(Z,Y),this.host.assertNotDisposed(),this.host.ttsService.setCatalogResolver(this.host.catalogResolver),this.initialized=!0,this.degraded=!1,this.host.clearDegradedTool(m),await this.host.hooks.onTTSReady?.(),this.host.assertNotDisposed()}reportMissingProvider(Z){if(this.host.isToolRegistryPending()){this.heldMissingProviderBackend=Z;return}if(this.reportedMissingProvider)return;this.reportedMissingProvider=!0,console.warn(`[ToolkitCoordinator] Text-to-speech is configured for the "${Z}" backend but falls back to browser speech: no "${m}" tool provider is registered. A coordinator registers tool providers only from its \`toolRegistry\`, or from its toolkit's when constructed without one, so supply one that carries the text-to-speech registration — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders". Reported once per coordinator.`)}reportHeldMissingProvider(){let Z=this.heldMissingProviderBackend;if(this.heldMissingProviderBackend=null,Z)this.reportMissingProvider(Z)}discardHeldMissingProvider(){this.heldMissingProviderBackend=null}requiredForReadiness(){if(this.resolveToolConfig()?.enabled===!1)return!1;return!this.host.lazyInit||this.host.isToolGranted(m)}async startForReadiness(){try{await this.ensureReady()}catch(Z){if(this.host.isDisposalError(Z))throw Z;if(this.host.isToolGranted(m))throw Z;this.degraded=!0,this.host.notifyReadyChange()}}scheduleReconfigure(){let Z=this.initPromise,Q=Z?Z.catch(()=>{}).then(()=>this.reconfigure()):this.reconfigure();this.reconfigurePromise=Q,Q.finally(()=>{if(this.reconfigurePromise===Q)this.reconfigurePromise=void 0}),Q.then(async()=>{if(this.host.isDisposalStarted())return;if(this.requiredForReadiness())await this.startForReadiness()}).catch(()=>{})}async reconfigure(){this.initialized=!1,this.degraded=!1,this.host.clearDegradedTool(m),this.initPromise=void 0,this.host.notifyReadyChange();try{this.host.ttsService.releaseProvider()}catch{}if(this.host.toolProviderRegistry.has(m))await this.host.toolProviderRegistry.unregister(m);if(this.host.isDisposalStarted())return;let Z=this.host.getProviderDescriptorTools().find((Q)=>this.ownsTool(Q.toolId));if(!Z)return;await this.host.registerProviderFromTool(Z)}}var F1={textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}};class w7{onTargetFailure;targets=new Set;changeListeners=new Set;constructor(Z=(Q,J,Y)=>console.error(`[ToolRequestRegistry] "${Q}" ${J} failed:`,Y)){this.onTargetFailure=Z}registerTarget(Z){return this.targets.add(Z),this.notifyTargetsChange(),()=>{if(!this.targets.delete(Z))return;this.notifyTargetsChange()}}canRequest(Z,Q,J){return this.findTarget(Z,Q,J)!==null}request(Z){let Q=this.findTarget(Z.toolId,Z.level,Z.scopeId);if(!Q)return!1;try{Q.open(Z.toolId,Z.params)}catch(J){return this.onTargetFailure(Z.toolId,"tool-request-open",J),!1}return!0}onTargetsChange(Z){return this.changeListeners.add(Z),()=>{this.changeListeners.delete(Z)}}findTarget(Z,Q,J){let Y=this.findTargetAtLevel(Z,Q??"section",J);if(Y||Q!==void 0)return Y;for(let X of this.targets){if(X.level==="section")continue;if(J!==void 0&&X.scopeId!==J)continue;if(this.hostsTool(X,Z))return X}return null}findTargetAtLevel(Z,Q,J){for(let Y of this.targets){if(Y.level!==Q)continue;if(J!==void 0&&Y.scopeId!==J)continue;if(this.hostsTool(Y,Z))return Y}return null}hostsTool(Z,Q){try{return Z.hostsTool(Q)===!0}catch(J){return this.onTargetFailure(Q,"tool-request-host-check",J),!1}}notifyTargetsChange(){for(let Z of this.changeListeners)try{Z()}catch(Q){console.warn("[ToolRequestRegistry] Target change listener threw:",Q)}}dispose(){this.targets.clear(),this.changeListeners.clear()}}function k2(Z){return Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:void 0}function tZ(Z,Q,J){let Y=Q?.settings,X=[Q?.personalNeedsProfile?.toolParameters?.[Z],Y?.toolParameters?.[Z],J?.settings.toolParameters?.[Z]].map(k2).filter((G)=>G!==void 0);return X.length>0?Object.assign({},...X):void 0}class R7{provenance;stepCounter=0;constructor(Z){this.provenance={contextId:Z,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Z,Q){let J={id:Q.id,name:Q.name??Q.id};switch(Z){case"organization":this.provenance.sources.organization={...J,pnpDefaults:Q.config};break;case"assessment":this.provenance.sources.assessment={...J,settings:Q.config};break;case"section":this.provenance.sources.section={...J,settings:Q.config};break;case"item":this.provenance.sources.item={...J,settings:Q.config};break;case"student":this.provenance.sources.student={id:Q.id,pnpProfile:Q.config};break;case"host":this.provenance.sources.host={id:Q.id,config:Q.config};break}return this}addDecision(Z){let Q={step:++this.stepCounter,precedence:Z.precedence,rule:Z.rule,featureId:Z.featureId,action:Z.action,source:{type:Z.sourceType,id:Z.sourceId,name:Z.sourceName},reason:Z.reason,value:Z.value,timestamp:new Date};this.provenance.decisionLog.push(Q);let J=this.provenance.features.get(Z.featureId);if(!J)J={featureId:Z.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Z.featureId,J);if(J.allDecisions.push(Q),Z.action==="advisory"){if(J.finalState==="not-configured")J.finalState="advisory-only"}else if(Z.action!=="skip"){if(!J.winningDecision||Q.precedence<J.winningDecision.precedence)J.winningDecision=Q,J.finalState=Q.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Z.sourceType]=(this.provenance.summary.bySource[Z.sourceType]||0)+1,this.provenance.summary.byRule[Z.rule]=(this.provenance.summary.byRule[Z.rule]||0)+1,this}reconcileFinalStates(Z){for(let Q of Z){let J=this.provenance.features.get(Q);if(!J){J={featureId:Q,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(Q,J);continue}J.finalState="enabled"}for(let Q of this.provenance.features.values()){if(Z.has(Q.featureId))continue;let J=Q.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),Y=Q.allDecisions.some((X)=>X.action==="advisory");if(J)Q.finalState="blocked";else if(Y)Q.finalState="advisory-only";else Q.finalState="not-configured"}return this}build(){for(let Z of this.provenance.features.values())Z.explanation=f2(Z);for(let Z of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Z.finalState==="enabled")this.provenance.summary.enabled++;else if(Z.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function f2(Z){if(!Z.winningDecision){if(Z.finalState==="advisory-only"){let G=Z.allDecisions.find((j)=>j.action==="advisory");return G?`Feature "${Z.featureId}" was kept in its host-decided state; ${G.reason}`:`Feature "${Z.featureId}" carries an advisory note.`}return`Feature "${Z.featureId}" was not configured at any level.`}let Q=Z.winningDecision,J=Q.source.name||Q.source.type,Y=`Feature "${Z.featureId}" is ${Z.finalState}.
216
216
 
217
217
  `;Y+=`**Primary Reason** (${Q.rule}):
218
218
  `,Y+=`${Q.reason}
@@ -220,6 +220,6 @@ ${J}`)}function J8(Z,Q={}){let J=O5(Z,Q.toolRegistry);return L5(J.diagnostics,Q)
220
220
  `;let X=Z.allDecisions.filter((G)=>G.step!==Q.step&&G.action!=="skip"&&G.action!=="advisory"&&G.precedence>Q.precedence);if(X.length>0){Y+=`
221
221
  **Overridden Rules**:
222
222
  `;for(let G of X)Y+=`- ${G.rule}: ${G.reason}
223
- `}return Y}function n9(Z){let{request:Q,tools:J,pnpPolicy:Y,customSources:X,contextId:G}=Z,j=new z7(G);j.addSource("host",{id:Q.scope.scopeId,name:`${Q.level}:${Q.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let B=DZ(J.placement[Q.level]),V=DZ(J.policy.allowed),K=new Set(DZ(J.policy.blocked)),U=[];for(let A of B)U.push(A),j.addDecision({precedence:0,rule:"placement-membership",featureId:A,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Q.level}`});if(U=U.filter((A)=>{if(J.providers?.[A]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:A,action:"block",sourceType:"host",reason:`tools.providers.${A}.enabled === false`,value:!1}),!1;return!0}),V.length>0){let A=new Set(V);U=U.filter((N)=>{if(!A.has(N))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:N,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:V}),!1;return!0})}U=U.filter((A)=>{if(K.has(A))return j.addDecision({precedence:0,rule:"host-blocked",featureId:A,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let $=[],z=new Set(U),D=null;if(Y.enforcement==="on"&&Y.source&&(Y.assessment||Y.item)){if(D=Y.source.apply({assessment:Y.assessment,item:Y.item}),D.sources.assessment)j.addSource("assessment",D.sources.assessment);if(D.sources.student)j.addSource("student",D.sources.student);if(D.sources.item)j.addSource("item",D.sources.item);for(let O of D.decisions)j.addDecision({precedence:O.precedence,rule:O.rule,featureId:O.featureId,action:O.action,sourceType:O.sourceType,reason:O.reason,value:O.value});for(let[O,S]of D.blockedOverrides)$.push(D7(O,S,Q.level));let{blockedToolIds:A}=D;U=U.filter((O)=>!A.has(O));let N=new Set(Object.values(J.placement).flatMap(DZ));for(let[O,S]of D.mandates){if(z.has(O))continue;if(!B.includes(O)&&N.has(O))continue;let C=q2(O,{placedAtAnyLevel:N,allTools:J.placement,allowed:V,blocked:K,providers:J.providers}),h={rule:S,hostRule:C.hostRule,hostValue:C.hostValue};$.push({code:"tool-policy.requiredToolBlocked",level:Q.level,toolId:O,message:C.hostRule==="placement-missing"?`Profile policy mandates "${O}" (${S}), but no level of tools.placement lists it.`:`Profile policy mandates "${O}" (${S}), but host policy removes it via ${C.hostRule}.`,details:h}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:O,action:"advisory",sourceType:"host",reason:`Host removed required tool "${O}" via ${C.hostRule}`,value:h})}}for(let A=0;A<X.length;A++){let N=X[A],O=U.slice(),S=N.refine({request:Q,candidates:O}),C=new Set(S.refinedCandidates);for(let b of S.refinedCandidates)if(!O.includes(b))$.push({code:"tool-policy.placementMissing",level:Q.level,toolId:b,message:`Custom source "${N.id}" tried to add tool "${b}" that was not in candidates; ignored.`,details:{customSourceId:N.id}}),C.delete(b);U=O.filter((b)=>C.has(b));let h=new Set;if(S.decisions){for(let b of S.decisions)if(j.addDecision({precedence:b.precedence??100+A,rule:b.rule,featureId:b.featureId,action:b.action,sourceType:b.sourceType,reason:b.reason,value:b.value}),b.action==="block")h.add(b.featureId)}for(let b of O){if(C.has(b))continue;if(h.has(b))continue;j.addDecision({precedence:100+A,rule:"custom-source",featureId:b,action:"block",sourceType:"custom",reason:`Custom policy source "${N.id}" removed tool "${b}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:N.id}})}}for(let A of U)for(let N of Z.unappliedItems??[]){let O=["restrictedTools","requiredTools"].filter((C)=>N.settings[C]?.includes(A)===!0);if(O.length===0)continue;let S={itemId:N.id,settings:O,toolbarLevel:Q.scope.level};$.push({code:"tool-policy.itemSettingNotApplied",level:Q.level,toolId:A,message:`Item "${N.id}" names "${A}" in ${O.join(" and ")}, but "${A}" is on the ${Q.scope.level}-level toolbar, which item settings do not reach. Place "${A}" at item level to enforce the setting per item.`,details:S})}let L=new Set(U),P=U.map((A)=>{let N=D?.perToolFlags.get(A);return{toolId:A,required:N?.required??!1,alwaysAvailable:N?.alwaysAvailable??!1,parameters:l0(A,Y.assessment,Y.item)}});return j.reconcileFinalStates(L),{visibleTools:P,diagnostics:$,provenance:j.build()}}function q2(Z,Q){if(!Q.placedAtAnyLevel.has(Z))return{hostRule:"placement-missing",hostValue:Q.allTools};if(Q.providers?.[Z]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Q.allowed.length>0&&!Q.allowed.includes(Z))return{hostRule:"host-allowlist",hostValue:Q.allowed};if(Q.blocked.has(Z))return{hostRule:"host-blocked",hostValue:Array.from(Q.blocked)};return{hostRule:"placement-missing",hostValue:Q.allTools}}var r9={"district-block":"settings.districtPolicy.blockedTools","test-admin-override":"settings.testAdministration.toolOverrides","item-restriction":"item settings.restrictedTools","pnp-prohibited":"personalNeedsProfile.prohibitedSupports","item-requirement":"item settings.requiredTools","district-requirement":"settings.districtPolicy.requiredTools","pnp-support":"personalNeedsProfile.supports"};function D7(Z,Q,J){return{code:"tool-policy.overrideBlocked",...J?{level:J}:{},toolId:Z,message:`settings.testAdministration.toolOverrides grants "${Z}", but ${r9[Q]} withdraws it and outranks a granting override.`,details:{rule:Q}}}function o9(Z,Q){let J=Q.map((Y)=>r9[Y]).join(", ");return{code:"tool-policy.unknownSupportId",toolId:Z,message:`No tool is registered under "${Z}", named in ${J}, so it matches nothing. These lists name tools by tool id.`,details:{origins:[...Q]}}}var K2=(Z)=>`No assessment is bound, so no policy source could grant "${Z}"`;function A7(Z,Q,J,Y){return{featureId:Z,granted:!1,action:"block",rule:Q,precedence:0,sourceType:"host",reason:Q==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${J.join(", ")})`,required:!1,assessmentBound:Y.assessmentBound,diagnostics:[]}}function a9(Z,Q,J,Y){let X=Q.decisions[0],G=Array.from(Q.perToolFlags.values())[0],j=X?.action==="enable",B=X?.reason??`Feature "${Z}" not configured`,V=X!==void 0&&X.action!=="skip";return{featureId:Z,granted:j,action:X?.action??"skip",rule:V?X.rule:"none",precedence:V?X.precedence:null,sourceType:X?.sourceType??"system",reason:J.assessmentBound||j?B:K2(Z),required:Boolean(G?.required),parameters:Y,assessmentBound:J.assessmentBound,diagnostics:Array.from(Q.blockedOverrides,([K,U])=>D7(K,U))}}var eZ=(Z)=>Array.isArray(Z)&&Z.length>0;function U2(Z){if(!Z)return!1;let Q=Z.personalNeedsProfile;if(Q&&(eZ(Q.supports)||eZ(Q.prohibitedSupports)))return!0;let J=Z.settings;if(J){let Y=J.districtPolicy;if(Y&&(eZ(Y.blockedTools)||eZ(Y.requiredTools)))return!0;let X=J.testAdministration?.toolOverrides;if(X&&typeof X==="object"&&Object.keys(X).length>0)return!0}return!1}function $2(Z){if(!Z)return!1;return eZ(Z.requiredTools)||eZ(Z.restrictedTools)}function t9(Z){if(U2(Z.assessment))return"on";if($2(Z.itemSettings))return"on";return"off"}class i0{id="pnp";toolRegistry;constructor(Z){this.toolRegistry=Z}apply(Z){let{ctx:Q,result:J}=this.prepare(Z),{pnp:Y,districtPolicy:X,testAdmin:G,itemSettings:j}=Q,B=new Set;Y?.supports?.forEach((V)=>B.add(V)),Y?.prohibitedSupports?.forEach((V)=>B.add(V)),X?.blockedTools?.forEach((V)=>B.add(V)),X?.requiredTools?.forEach((V)=>B.add(V));for(let V of Object.keys(G?.toolOverrides??{}))B.add(V);j?.requiredTools?.forEach((V)=>B.add(V)),j?.restrictedTools?.forEach((V)=>B.add(V));for(let V of B)this.resolveSupport(V,Q,J);return J}resolveFeature(Z,Q){let{ctx:J,result:Y}=this.prepare(Q);return this.resolveSupport(Z,J,Y),Y}prepare(Z){let{assessment:Q,item:J}=Z,Y=Q?.personalNeedsProfile,X=Q?.settings,G=J?.settings,j={blockedToolIds:new Set,mandates:new Map,perToolFlags:new Map,decisions:[],blockedOverrides:new Map,sources:{}};if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Q?.id||"unknown",name:Q?.name||Q?.id||"Assessment",config:X};if(Y)j.sources.student={id:"student",name:"Student PNP Profile",config:Y};if(J)j.sources.item={id:J.id,name:J.id,config:J.settings};return{ctx:{pnp:Y,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:G},result:j}}resolveSupport(Z,Q,J){if(Q.districtPolicy?.blockedTools?.includes(Z)){J.blockedToolIds.add(Z),J.decisions.push({precedence:1,rule:"district-block",featureId:Z,action:"block",sourceType:"assessment",reason:`District policy blocks "${Z}" for all assessments`,value:Q.districtPolicy.blockedTools});return}let Y=Q.testAdmin?.toolOverrides?.[Z];if(Y===!1){J.blockedToolIds.add(Z),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:Z,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(Q.itemSettings?.restrictedTools?.includes(Z)){if(J.blockedToolIds.add(Z),Y===!0)J.blockedOverrides.set(Z,"item-restriction");J.decisions.push({precedence:3,rule:"item-restriction",featureId:Z,action:"block",sourceType:"item",reason:`Item restricts "${Z}" (e.g., mental math question blocks calculator)`,value:Q.itemSettings.restrictedTools});return}if(Q.pnp?.prohibitedSupports?.includes(Z)){if(J.blockedToolIds.add(Z),Y===!0)J.blockedOverrides.set(Z,"pnp-prohibited");J.decisions.push({precedence:4,rule:"pnp-prohibited",featureId:Z,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Z}"`,value:Q.pnp.prohibitedSupports});return}let X=Q.itemSettings?.requiredTools?.includes(Z)?"item-requirement":Q.districtPolicy?.requiredTools?.includes(Z)?"district-requirement":void 0;if(Y===!0){if(X)J.mandates.set(Z,X);J.perToolFlags.set(Z,{required:X!==void 0,alwaysAvailable:!0,rule:"test-admin-override"}),J.decisions.push({precedence:5,rule:"test-admin-override",featureId:Z,action:"enable",sourceType:"assessment",reason:`Test administrator enabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(X==="item-requirement"){J.mandates.set(Z,X),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,rule:"item-requirement"}),J.decisions.push({precedence:6,rule:"item-requirement",featureId:Z,action:"enable",sourceType:"item",reason:`Item requires "${Z}" for this question`,value:Q.itemSettings?.requiredTools});return}if(X==="district-requirement"){J.mandates.set(Z,X),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,rule:"district-requirement"}),J.decisions.push({precedence:7,rule:"district-requirement",featureId:Z,action:"enable",sourceType:"assessment",reason:`District policy requires "${Z}" for all assessments`,value:Q.districtPolicy?.requiredTools});return}if(Q.pnp?.supports?.includes(Z)){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,rule:"pnp-support"}),J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Z}"`,value:Q.pnp.supports});return}J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"skip",sourceType:"system",reason:`Feature "${Z}" not configured at any level`,value:{supportId:Z}})}unknownSupportIds(Z,Q){let J=new Map;if(this.toolRegistry.getAllTools().length===0)return J;let Y=Z?.personalNeedsProfile,X=Z?.settings,G=[["district-block",X?.districtPolicy?.blockedTools],["test-admin-override",Object.keys(X?.testAdministration?.toolOverrides??{})],["item-restriction",Q.flatMap((j)=>j.restrictedTools??[])],["pnp-prohibited",Y?.prohibitedSupports],["item-requirement",Q.flatMap((j)=>j.requiredTools??[])],["district-requirement",X?.districtPolicy?.requiredTools],["pnp-support",Y?.supports]];for(let[j,B]of G)for(let V of B??[]){if(this.toolRegistry.has(V))continue;let K=J.get(V)??[];if(!K.includes(j))K.push(j);J.set(V,K)}return J}}var e9=cZ({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class s0{toolRegistry;unsubscribeRegistry;contextId;assessmentOptional;pnpPolicySource;customSources;listeners=new Set;tools;assessment;pnpEnforcementOverride;itemSettings=new Map;inputDiagnostics=Object.freeze([]);disposed=!1;constructor(Z){this.toolRegistry=Z.toolRegistry,this.contextId=Z.contextId??"tool-policy",this.assessmentOptional=Z.assessmentOptional===!0,this.pnpPolicySource=new i0(this.toolRegistry),this.customSources=Z.customSources?[...Z.customSources]:[];let Q=Z.inputs??{};this.tools=Q.tools??e9,this.assessment=Q.assessment??null,this.pnpEnforcementOverride=Q.pnpEnforcement??null,this.refreshInputDiagnostics(),this.unsubscribeRegistry=this.watchRegistry()}decide(Z){this.assertNotDisposed();let Q=Z.scope.scopeId?`${this.contextId}:${Z.level}:${Z.scope.scopeId}`:`${this.contextId}:${Z.level}`,J=Z.level==="item"?this.itemForScope(Z.scope):void 0,Y=Z.level!=="item"||Z.scope.level==="section"||Z.scope.level==="assessment";return n9({request:Z,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,item:J,enforcement:this.enforcementFor(J)},unappliedItems:Y?this.enforcedItems():void 0,customSources:this.customSources,contextId:Q})}grantsFeatureAnywhere(Z,Q={}){let J=(Y)=>!Q.enforced||this.enforcementFor(Y)==="on";if(J()&&this.decideFeature(Z).granted)return!0;for(let Y of this.itemSettings.keys()){let X=this.itemSettingsFor(Y);if(!J(X?{id:Y,settings:X}:void 0))continue;if(this.decideFeature(Z,{level:"item",scopeId:Y}).granted)return!0}return!1}registerItemSettings(Z,Q){this.assertNotDisposed();let J={settings:Q},Y=this.itemSettingsFor(Z),X=this.itemSettings.get(Z)??[];return X.push(J),this.itemSettings.set(Z,X),this.emitIfItemSettingsChanged(Z,Y),()=>{if(this.disposed)return;let G=this.itemSettings.get(Z),j=G?.indexOf(J)??-1;if(!G||j<0)return;let B=this.itemSettingsFor(Z);if(G.splice(j,1),G.length===0)this.itemSettings.delete(Z);this.emitIfItemSettingsChanged(Z,B)}}decideFeature(Z,Q){this.assertNotDisposed();let J=this.hostFeatureGate(Z);if(J)return J;let Y=this.itemForScope(Q);return a9(Z,this.pnpPolicySource.resolveFeature(Z,{assessment:this.assessment??void 0,item:Y}),{assessmentBound:this.assessment!==null},l0(Z,this.assessment,Y))}hostFeatureGate(Z){let Q={assessmentBound:this.assessment!==null},J=DZ(this.tools.policy.blocked);if(J.includes(Z))return A7(Z,"host-blocked",J,Q);let Y=DZ(this.tools.policy.allowed);if(Y.length>0&&!Y.includes(Z))return A7(Z,"host-allowlist",Y,Q);return null}getVisibleToolIds(Z,Q){return this.decide({level:Z,scope:{level:Z,scopeId:Q}}).visibleTools.map((J)=>J.toolId)}updateInputs(Z){this.assertNotDisposed();let Q=!1,J=!1;if("tools"in Z){let Y=Z.tools??e9;if(!Object.is(this.tools,Y))this.tools=Y,Q=!0}if("assessment"in Z){let Y=Z.assessment??null,X=!hZ(this.assessment,Y);if(this.assessment=Y,X)Q=!0,this.refreshInputDiagnostics()}if("pnpEnforcement"in Z){let Y=Z.pnpEnforcement??null;if(this.pnpEnforcementOverride!==Y)this.pnpEnforcementOverride=Y,J=!0}if(Q||J)this.emit({reason:J&&!Q?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(Z,Q){this.assertNotDisposed(),this.unsubscribeRegistry(),this.toolRegistry=Z,this.pnpPolicySource=new i0(Z),this.unsubscribeRegistry=this.watchRegistry(),this.tools=Q,this.refreshInputDiagnostics(),this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Z){return this.assertNotDisposed(),this.customSources.push(Z),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Q=this.customSources.indexOf(Z);if(Q===-1)return;if(this.customSources.splice(Q,1),this.disposed)return;this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}onPolicyChange(Z){return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeRegistry(),this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.itemSettings.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,pnpEnforcement:this.enforcementFor(),pnpEnforcementOverride:this.pnpEnforcementOverride,assessmentExpected:!this.assessmentOptional||this.pnpEnforcementOverride==="on",diagnostics:this.inputDiagnostics})}enforcementFor(Z){return this.pnpEnforcementOverride??t9({assessment:this.assessment,itemSettings:Z?.settings})}itemSettingsFor(Z){return this.itemSettings.get(Z)?.at(-1)?.settings}emitIfItemSettingsChanged(Z,Q){if(hZ(Q,this.itemSettingsFor(Z)))return;this.refreshInputDiagnostics(),this.emit({reason:"item-settings",inputs:this.snapshotInputs()})}refreshInputDiagnostics(){let Z=[];for(let J of this.itemSettings.keys()){let Y=this.itemSettingsFor(J);if(Y)Z.push(Y)}let Q=Array.from(this.pnpPolicySource.unknownSupportIds(this.assessment,Z),([J,Y])=>o9(J,Y));if(hZ(this.inputDiagnostics,Q))return!1;return this.inputDiagnostics=Object.freeze(Q),!0}watchRegistry(){return this.toolRegistry.onRegistryChange(()=>{if(this.disposed)return;if(this.refreshInputDiagnostics())this.emit({reason:"inputs",inputs:this.snapshotInputs()})})}itemForScope(Z){if(Z?.level!=="item")return;let Q=Z.canonicalItemId||Z.itemId||Z.scopeId,J=Q?this.itemSettingsFor(Q):void 0;return J?{id:Q,settings:J}:void 0}enforcedItems(){let Z=[];for(let Q of this.itemSettings.keys()){let J=this.itemSettingsFor(Q);if(!J)continue;let Y={id:Q,settings:J};if(this.enforcementFor(Y)==="on")Z.push(Y)}return Z}emit(Z){for(let Q of Array.from(this.listeners))try{Q(Z)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}import{hasResponseField as F2,hasResponseValue as Z1}from"@pie-players/pie-players-shared/pie";import{isPlainRecord as Z0}from"@pie-players/pie-players-shared/object";function n0(Z){return Z0(Z)&&Z0(Z.session)?Z.session:Z}function z2(Z,Q){let J=Z0(Z)?Z:{},Y=Z0(Q)?Q:{},X=new Set([...Object.keys(J),...Object.keys(Y)]);for(let G of X)if(!hZ(n0(J[G]),n0(Y[G])))return!1;return!0}function D2(Z,Q){for(let[J,Y]of Object.entries(Z)){if(Y===void 0)continue;if(J==="itemSessions"){if(!z2(Y,Q.itemSessions))return!1;continue}if(!hZ(Y,Q[J]))return!1}return!0}function r0(Z,Q){if(!Z)return Q;let J=Z0(Q.itemSessions)?{...Q.itemSessions}:{},Y=Z0(Z.itemSessions)?Z.itemSessions:{};for(let[G,j]of Object.entries(Y)){if(!Z1(n0(j)))continue;let B=n0(J[G]);if(Z1(B)||F2(B))continue;J[G]=j}let X={...Q,itemSessions:J};return D2(X,Z)?null:X}class c extends Error{constructor(){super("ToolkitCoordinator has been disposed.");this.name="ToolkitCoordinatorDisposedError"}}class o0 extends Error{constructor(){super("Section controller acquisition was retired during initialization.");this.name="SectionControllerRetiredError"}}var Q1=(Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z),A2=(Z,Q,J)=>{let Y={...Q,...J};if(Z==="textToSpeech"&&Q1(Q.mathSpeech)&&Q1(J.mathSpeech))Y.mathSpeech={...Q.mathSpeech,...J.mathSpeech};return Y},H2={"tool-module-load":"failed to load","tool-request-open":"failed to open on request","tool-request-host-check":"failed its toolbar's host check","tool-visibility":"failed its relevance check","tool-applicability":"failed its applicability check","tool-state-load":"failed to restore its state","tool-state-save":"failed to save its state","tool-playback":"failed during playback"},_2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],O2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error","timed-media-cue-changed","timed-media-policy-degraded","timed-media-invalid"];class _7{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;ttsInitialized=!1;ttsDegraded=!1;ttsInitPromise;ttsReconfigurePromise;stateLoadSettled=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;degradedTools=new Map;reportedToolFailures=new Set;readyChangeListeners=new Set;eagerInit;toolRegistry;toolRegistrySupplied;toolRegistrySettled;toolRegistryAbsent=!1;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;toolRequests=new F7((Z,Q,J)=>this.reportToolFailure(Z,Q,J));sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitEntries=new Map;sectionControllerDisposePromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;ownedToolCoordinator;frameworkErrorHookUnsubscribe=null;disposePromise=null;policyEngine;reportedPolicyDiagnostics=new Map;policyDiagnosticListeners=new Set;reportedUnboundFeaturePolicy=!1;reportedMissingTTSProvider=!1;heldMissingTTSProviderBackend=null;reportedRegistryUnavailable=!1;resolveConfig(Z){let Q=_5(Z.toolConfigStrictness),J=Z.toolRegistry??new H7,Y=Z.deferToolConfigValidation===!0?cZ(Z.tools):this.validateToolsConfig(Z.tools,{strictness:Q,source:"ToolkitCoordinator.init",toolRegistry:J});return{...Z,toolConfigStrictness:Q,toolRegistry:J,tools:{...Y,providers:{...{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}},...Y.providers}},accessibility:{language:"en-US",...Z.accessibility??{},catalogs:Z.accessibility?.catalogs??[]}}}validateToolsConfig(Z,Q){let{config:J,diagnostics:Y}=O5(Z,Q.toolRegistry),X=this.reportedRegistryUnavailable||this.toolRegistryPending()?Y.filter((G)=>G.code!=="tools.registryUnavailable"):Y;if(L5(X,Q),Q.strictness!=="off"&&X.some((G)=>G.code==="tools.registryUnavailable"))this.reportedRegistryUnavailable=!0;return J}constructor(Z){if(!Z.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=Z.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let Q=this.resolveConfig(Z);if(this.assessmentId=Q.assessmentId,this.config=Q,this.toolRegistry=Q.toolRegistry??new H7,this.installToolContextResolvers(Q.toolContextResolvers),this.hooks={...Q.hooks},this.lazyInit=Z.lazyInit===!0,this.eagerInit=Z.eagerInit??!this.lazyInit,this.frameworkErrorBus=Z.frameworkErrorBus??new W0,this.ownsFrameworkErrorBus=!Z.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.ownedToolCoordinator=new J1,this.toolCoordinator=this.ownedToolCoordinator,this.highlightCoordinator=new $0,this.elementToolStateStore=new S5,this.catalogResolver=new b5(Q.accessibility?.catalogs||[],Q.accessibility?.language||"en-US"),this.toolProviderRegistry=new d0,this._registerToolProviders(),this.ttsService=new V7,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.ttsService.setReadinessGate(()=>this.ensureTTSReady()),this.ttsService.setMathSpeechSource(()=>$7(U7(this.resolveTTSToolConfig())).providerOptions?.mathSpeech),this.setupStatePersistenceHooks(),this.policyEngine=new s0({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,assessmentOptional:this.config.assessmentOptional===!0,inputs:{tools:this.config.tools,assessment:null,pnpEnforcement:this.resolveConfiguredPnpEnforcement()}}),this.policyEngine.onPolicyChange((J)=>{if(J.reason==="disposed")return;if(J.reason==="inputs"||J.reason==="pnp-enforcement")this.reportedPolicyDiagnostics.clear();this.warnPolicyDiagnostics(J.inputs.diagnostics),this.reportNewlyGrantedFailures()}),this.eagerInit)this.waitUntilReady().catch((J)=>{if(J instanceof c)return;console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready",recoverable:!1})})}assertNotDisposed(){if(this.disposePromise!==null)throw new c}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors((Z)=>{let Q=this.hooks.onFrameworkError;if(!Q)return;try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Z,Q){try{await this.hooks.onTelemetry?.(Z,Q)}catch(Y){console.warn("[ToolkitCoordinator] telemetry hook failed:",Y)}let J=Q?{...Q}:void 0;for(let Y of this.telemetryListeners)try{Y({eventName:Z,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Z){for(let Q of this.sectionControllerLifecycleListeners)try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Z,Q,J){let Y=z8({error:Z,context:Q,recoverable:Q.recoverable,scope:J?"cohort":"runtime",cohort:J});this.frameworkErrorBus.reportFrameworkError(Y)}isToolGranted(Z){try{return this.policyEngine.grantsFeatureAnywhere(Z,{enforced:this.toolRegistry.getToolActivation(Z)!=="region"})}catch{return!1}}reportStartFailure(Z,Q,J,Y=!1){let X=Array.from(J),G=Y||!X.some((j)=>this.isToolGranted(j));if(G&&!Y)for(let j of X)this.degradedTools.set(j,{error:Z,context:Q});this.handleError(Z,{...Q,recoverable:G})}reportToolFailure(Z,Q,J){if(Q==="tool-module-load")this.toolRequests.notifyTargetsChange();let Y=`${Q}\x00${Z}`;if(this.reportedToolFailures.has(Y))return;this.reportedToolFailures.add(Y);let X=J instanceof Error&&J.message.trim().length>0?J.message:String(J),G=()=>this.reportStartFailure(Error(`Tool "${Z}" ${H2[Q]}: ${X}`,{cause:J}),{phase:Q,details:{toolId:Z}},[Z],Q!=="tool-module-load");if(Q==="tool-module-load")G();else queueMicrotask(G)}reportNewlyGrantedFailures(){for(let[Z,Q]of this.degradedTools){if(!this.isToolGranted(Z))continue;this.degradedTools.delete(Z),this.handleError(Q.error,{...Q.context,recoverable:!1})}}onReadyChange(Z){return this.readyChangeListeners.add(Z),()=>{this.readyChangeListeners.delete(Z)}}notifyReadyChange(){for(let Z of this.readyChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] ready-change listener failed:",Q)}}subscribeFrameworkErrors(Z){return this.frameworkErrorBus.subscribeFrameworkErrors(Z)}reportFrameworkError(Z){this.frameworkErrorBus.reportFrameworkError(Z)}sectionControllerKey(Z){return{assessmentId:this.assessmentId,sectionId:Z.sectionId,attemptId:Z.attemptId}}getSectionControllerMapKey(Z){return`${Z.assessmentId}::${Z.sectionId}::${Z.attemptId||""}`}createDefaultSectionPersistence(){let Z=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Q=(J)=>{let{assessmentId:Y,sectionId:X,attemptId:G}=J.key;if(!G)return null;return`pie:section-controller:v1:${Y}:${X}:${G}`};return{async loadSession(J){let Y=Q(J);if(!Z||!Y)return null;let X=Z.getItem(Y);if(!X)return null;try{return JSON.parse(X)}catch{return null}},async saveSession(J,Y){let X=Q(J);if(!Z||!X)return;Z.setItem(X,JSON.stringify(Y))},async clearSession(J){let Y=Q(J);if(!Z||!Y)return;Z.removeItem(Y)}}}async resolveSectionPersistence(Z){let Q=this.getSectionControllerMapKey(Z.key),J=this.sectionPersistenceStrategies.get(Q);if(J)return J;let Y={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Z,Y)??await Y.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Q,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Z)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Z)).catch((Q)=>{this.handleError(Q,{phase:"state-save",recoverable:!0})})})}async ensureStateLoaded(){if(this.stateLoadSettled)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Z=this.hooks.loadToolState;if(!Z)return;try{let Q=await Z();if(this.assertNotDisposed(),Q&&typeof Q==="object")this.elementToolStateStore.loadState(Q);this.stateLoadSettled=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Q)})}catch(Q){if(Q instanceof c)throw Q;this.stateLoadSettled=!0,this.handleError(Q,{phase:"state-load",recoverable:!0})}})().finally(()=>{this.stateLoadPromise=void 0,this.notifyReadyChange()}),this.stateLoadPromise}toolRegistryPending(){return!this.toolRegistrySettled&&!this.toolRegistryAbsent}reportMissingTTSProvider(Z){if(this.toolRegistryPending()){this.heldMissingTTSProviderBackend=Z;return}if(this.reportedMissingTTSProvider)return;this.reportedMissingTTSProvider=!0,console.warn(`[ToolkitCoordinator] Text-to-speech is configured for the "${Z}" backend but falls back to browser speech: no "textToSpeech" tool provider is registered. A coordinator registers tool providers only from its \`toolRegistry\`, or from its toolkit's when constructed without one, so supply one that carries the text-to-speech registration — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders". Reported once per coordinator.`)}adoptToolRegistry(Z){if(this.disposePromise!==null||this.toolRegistrySettled)return!1;if(!Z&&this.toolRegistryAbsent)return!1;let Q=this.heldMissingTTSProviderBackend;this.heldMissingTTSProviderBackend=null;let J=this.config.toolConfigStrictness??"error",Y="ToolkitCoordinator.adoptToolRegistry";if(!Z){if(this.toolRegistryAbsent=!0,this.validateToolsConfig(this.config.tools,{strictness:J,source:Y,toolRegistry:this.toolRegistry}),Q)this.reportMissingTTSProvider(Q);return!1}this.toolRegistrySettled=!0,this.toolRegistry=Z,this.config.toolRegistry=Z;try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:J==="off"?"off":"warn",source:Y,toolRegistry:Z})}catch(G){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",G)}this.policyEngine.replaceToolRegistry(Z,this.config.tools);let X=this.ttsInitialized||this.ttsInitPromise!==void 0||this.ttsReconfigurePromise!==void 0;for(let G of this.getProviderDescriptorTools()){if(X&&G.toolId==="textToSpeech")continue;this.registerProviderFromTool(G)}if(X)this.scheduleTTSReconfigure();return!0}_registerToolProviders(){let Z=this.getProviderDescriptorTools();for(let Q of Z)this.registerProviderFromTool(Q)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Z)=>!!Z.provider)}async registerProviderFromTool(Z,Q=!1){let J=Z.provider;if(!J)return;let{toolId:Y}=Z,X;try{let G=this.getToolConfig(Y)||void 0;if(G?.enabled===!1){if(Q)this.toolProviderRegistry.unregister(Y);return}if(!Q&&this.toolProviderRegistry.has(Y))return;let j=J.createProvider(G),B=J.getInitConfig?.(G)??G?.provider?.init??{},V=this.addToolTelemetryReporter(Y,B),K=this.createToolTelemetryForwarder(Y),U=J.getAuthFetcher?.(G)??G?.provider?.runtime?.authFetcher;X={provider:j,config:V,lazy:J.lazy??!0,authFetcher:U,onTelemetry:K}}catch(G){this.reportProviderRegisterFailure(G,Y);return}await this.registerProvider(Y,X)}createToolTelemetryForwarder(Z){return async(Q,J)=>{await this.emitTelemetry(Q,{...J||{},toolId:Z})}}addToolTelemetryReporter(Z,Q){let J=Q&&typeof Q==="object"?{...Q}:{},Y=typeof J.onTelemetry==="function"?J.onTelemetry:null,X=this.createToolTelemetryForwarder(Z);return J.onTelemetry=async(G,j)=>{if(Y)await Y(G,j);await X(G,j)},J}async registerProvider(Z,Q){try{this.toolProviderRegistry.register(Z,Q);let J={providerName:Q.provider.providerName};await this.hooks.onProviderRegistered?.(Z,J),await this.emitTelemetry("pie-toolkit-provider-registered",{toolId:Z,providerName:Q.provider.providerName})}catch(J){this.reportProviderRegisterFailure(J,Z)}}reportProviderRegisterFailure(Z,Q){console.warn(`[ToolkitCoordinator] Failed to register the provider of tool "${Q}":`,Z),this.reportStartFailure(Z,{phase:"provider-register",toolId:Q},[Q])}async ensureProviderReady(Z){return this.initializeProvider(Z,!1)}async initializeProvider(Z,Q){this.assertNotDisposed();let J=this.providerInitPromises.get(Z);if(J)return J;let Y=(async()=>{try{let X=await this.toolProviderRegistry.getProvider(Z,!1);if(this.assertNotDisposed(),this.toolProviderRegistry.isInitialized(Z))return X;let G={providerName:X.providerName};return await this.hooks.onProviderInitStart?.(Z,G),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(Z),this.assertNotDisposed(),X=await this.toolProviderRegistry.getProvider(Z,!1),await this.hooks.onProviderReady?.(Z,G),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{toolId:Z}),this.assertNotDisposed(),X}catch(X){if(X instanceof c)throw X;let G=X instanceof Error?X:Error(String(X));throw this.reportStartFailure(G,{phase:"provider-init",toolId:Z},this.toolRegistry.get(Z)?.provider?[Z]:[],Q),G}})().finally(()=>{this.providerInitPromises.delete(Z)});return this.providerInitPromises.set(Z,Y),Y}setHooks(Z){if(Object.assign(this.hooks,Z),this.setupStatePersistenceHooks(),this.disposePromise===null&&Z.onCoordinatorReady&&this.isReady())Promise.resolve(Z.onCoordinatorReady(this)).catch((Q)=>{this.handleError(Q,{phase:"coordinator-ready",recoverable:!1})})}subscribeTelemetry(Z){return this.telemetryListeners.add(Z),()=>{this.telemetryListeners.delete(Z)}}getSectionController(Z){let Q=this.sectionControllerKey(Z);return this.sectionControllers.get(this.getSectionControllerMapKey(Q))}subscribeSectionEvents(Z){if(this.activeCohortMapKey===null&&this.latestRequestedActiveCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Q=this.activeSubscriptions.get(Z.listener);if(Q)Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J={listener:Z.listener,eventTypes:Z.eventTypes,itemIds:Z.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Z.listener,J);let Y=this.activeCohortMapKey===null?void 0:this.sectionControllers.get(this.activeCohortMapKey);if(Y)this.bindSubscriptionToController(J,Y);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Z.listener)===J)this.activeSubscriptions.delete(Z.listener)}}bindSubscriptionToController(Z,Q){Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null;let J=Q.subscribe;if(typeof J!=="function")return;let Y=this.buildSectionEventPredicate(Z);Z.unsubscribeCurrent=J.call(Q,(j)=>{if(!Y(j))return;this.deliverSectionEventSafely(Z.listener,j)});let X=this.buildContentLoadedReplayEvents(Q);for(let j of X)if(Y(j))this.deliverSectionEventSafely(Z.listener,j);let G=this.buildLoadingCompleteReplayEvent(Q);if(G&&Y(G))this.deliverSectionEventSafely(Z.listener,G)}deliverSectionEventSafely(Z,Q){try{Z(Q)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Z){if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=Z;let Q=this.sectionControllers.get(Z);if(!Q)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Q)}setActiveCohortIfLatestRequest(Z){if(this.latestRequestedActiveCohortMapKey!==Z)return;this.setActiveCohort(Z)}suspendActiveCohortIfSuperseded(Z){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}clearActiveCohortIfMatches(Z){if(this.activeCohortMapKey!==Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}detachActiveSubscriptions(){for(let Z of Array.from(this.activeSubscriptions.values()))Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null}buildSectionEventPredicate(Z){let Q=Z.eventTypes?new Set(Z.eventTypes):null,J=Z.itemIds?new Set(Z.itemIds):null;return(Y)=>{if(Q){let X=Y?.type;if(!X||!Q.has(X))return!1}if(!J)return!0;return Array.from(this.collectEventItemIds(Y)).some((X)=>J.has(X))}}collectEventItemIds(Z){let Q=new Set;if("itemId"in Z&&typeof Z.itemId==="string")Q.add(Z.itemId);if("canonicalItemId"in Z&&typeof Z.canonicalItemId==="string")Q.add(Z.canonicalItemId);if("currentItemId"in Z&&typeof Z.currentItemId==="string")Q.add(Z.currentItemId);if("previousItemId"in Z&&typeof Z.previousItemId==="string")Q.add(Z.previousItemId);return Q}buildContentLoadedReplayEvents(Z){let Q=Z.getRuntimeState?.(),J=Q?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let Y=typeof Q?.currentItemIndex==="number"&&Number.isFinite(Q.currentItemIndex)?Q.currentItemIndex:0,X=Date.now(),G=[];for(let j of J){if(!j)continue;let B=j.itemId,V=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:B;if(typeof B!=="string"||!B)continue;G.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:B,canonicalItemId:V,currentItemIndex:Y,timestamp:X})}return G}buildLoadingCompleteReplayEvent(Z){let Q=Z.getRuntimeState?.();if(Q?.loadingComplete!==!0)return null;let J=typeof Q.totalRegistered==="number"&&Number.isFinite(Q.totalRegistered)?Math.max(0,Q.totalRegistered):0,Y=typeof Q.totalLoaded==="number"&&Number.isFinite(Q.totalLoaded)?Math.max(0,Q.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:Y,currentItemIndex:Q.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||_2,itemIds:Z.itemIds,listener:Z.listener})}subscribeSectionLifecycleEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||O2,listener:Z.listener})}onSectionControllerLifecycle(Z){return this.sectionControllerLifecycleListeners.add(Z),()=>{this.sectionControllerLifecycleListeners.delete(Z)}}async getOrCreateSectionController(Z){if(this.disposePromise!==null)throw new c;let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let Y;try{if(Y=await this.resolveExistingSectionController({mapKey:J,key:Q,input:Z.input,updateExisting:Z.updateExisting}),Y){if(this.disposePromise!==null)throw new c;if(Z.initialSession)await this.assignSessionToPublishedController(Y,Z.initialSession)}}catch(V){throw this.deliverSectionStartError(J,V),V}if(Y)return Y;let X=this.sectionControllerDisposePromises.get(J);if(X)await Promise.allSettled([X]);if(this.disposePromise!==null)throw new c;let G=this.sectionControllerInitEntries.get(J);if(G){if(!Z.initialSession)return G.promise;let V=await G.promise;return await this.assignSessionToPublishedController(V,Z.initialSession),V}let j={retired:!1,candidateClaimed:!1},B=this.initializeNewSectionController({args:Z,key:Q,mapKey:J,token:j}).catch((V)=>{throw this.handleSectionControllerInitError(V,Z),this.deliverSectionStartError(J,V),V}).finally(()=>{if(this.sectionControllerInitEntries.get(J)?.token===j)this.sectionControllerInitEntries.delete(J)});return this.sectionControllerInitEntries.set(J,{key:Q,token:j,promise:B}),B}async resolveExistingSectionController(Z){let Q=this.sectionControllers.get(Z.mapKey);if(!Q)return;if(this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.updateExisting!==!1)await Q.updateInput?.(Z.input);if(this.sectionControllers.get(Z.mapKey)!==Q)return;return this.setActiveCohortIfLatestRequest(Z.mapKey),Q}createSectionControllerContext(Z){return{key:Z.key,coordinator:this,input:Z.input}}async initializeNewSectionController(Z){let Q=this.createSectionControllerContext({key:Z.key,input:Z.args.input}),J=await this.resolveSectionPersistence(Q);if(this.disposePromise!==null||Z.token.retired){if(this.sectionPersistenceStrategies.get(Z.mapKey)===J)this.sectionPersistenceStrategies.delete(Z.mapKey);throw this.createSectionControllerRetirementError()}let Y={createDefaultController:Z.args.createDefaultController},X=await this.hooks.createSectionController?.(Q,Y)??await Y.createDefaultController(),G={mapKey:Z.mapKey,key:Z.key,controller:X,persistence:J,token:Z.token};try{await this.retireUnpublishedSectionControllerIfNeeded(G),await X.configureSessionPersistence?.({strategy:J,context:Q}),await this.retireUnpublishedSectionControllerIfNeeded(G),await X.initialize?.(Z.args.input),await this.retireUnpublishedSectionControllerIfNeeded(G);let j=Z.args.initialSession;if(j){if(!X.applySession)throw Error("Section controller cannot apply the session it was created with: it has no applySession.");await X.applySession(j,{mode:"replace"})}else await X.hydrate?.();return await this.finalizeSectionControllerReady({...G,context:Q}),X}catch(j){throw await this.cleanupUnpublishedSectionController(G),j}}async assignSessionToPublishedController(Z,Q){if(!Q)return;if(!Z.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");let J=r0(Z.getSession?.()??null,Q);if(!J)return;await Z.applySession(J,{mode:"replace"})}createSectionControllerRetirementError(){return this.disposePromise!==null?new c:new o0}async retireUnpublishedSectionControllerIfNeeded(Z){if(this.disposePromise===null&&!Z.token.retired)return;throw await this.cleanupUnpublishedSectionController(Z),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(Z){if(Z.token.candidateClaimed)return;Z.token.candidateClaimed=!0;try{await Z.controller.dispose?.()}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.key.sectionId,attemptId:Z.key.attemptId},recoverable:!0})}finally{if(this.sectionPersistenceStrategies.get(Z.mapKey)===Z.persistence)this.sectionPersistenceStrategies.delete(Z.mapKey)}}retirePublishedSectionControllerIfNeeded(Z){if(this.disposePromise!==null&&!Z.token.retired)this.disposeSectionController({sectionId:Z.key.sectionId,attemptId:Z.key.attemptId});if(Z.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(Z){await this.retireUnpublishedSectionControllerIfNeeded(Z),this.sectionControllers.set(Z.mapKey,Z.controller),this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(Z.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Z.key,controller:Z.controller}),await this.hooks.onSectionControllerReady?.(Z.context,Z.controller),this.retirePublishedSectionControllerIfNeeded(Z),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(Z)}handleSectionControllerInitError(Z,Q){if(Z instanceof c||Z instanceof o0)return;this.handleError(Z,{phase:"section-controller-init",details:{sectionId:Q.sectionId,attemptId:Q.attemptId},recoverable:!1},{sectionId:Q.sectionId,attemptId:Q.attemptId})}deliverSectionStartError(Z,Q){if(Q instanceof c||Q instanceof o0||this.latestRequestedActiveCohortMapKey!==Z)return;let J={type:"section-error",source:"section-runtime",error:Q,currentItemIndex:0,timestamp:Date.now()};for(let Y of Array.from(this.activeSubscriptions.values()))if(this.buildSectionEventPredicate(Y)(J))this.deliverSectionEventSafely(Y.listener,J)}disposeSectionController(Z){let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q),Y=this.sectionControllerInitEntries.get(J);if(Y)Y.token.retired=!0;let X=this.sectionControllers.get(J);if(!X){let K=this.sectionControllerDisposePromises.get(J);if(K)return K;if(!Y)return Promise.resolve();let U=Promise.allSettled([Y.promise]).then(()=>{return});return this.trackSectionControllerDisposal(J,U)}let G=this.sectionPersistenceStrategies.get(J);if(this.clearActiveCohortIfMatches(J),this.sectionControllers.get(J)===X)this.sectionControllers.delete(J),this.sectionControllerKeys.delete(J),this.sectionPersistenceStrategies.delete(J),this.emitSectionControllerLifecycle({type:"disposed",key:Q});let j=this.createSectionControllerContext({key:Q,input:void 0}),B=this.disposeSectionControllerEntry({args:Z,key:Q,context:j,controller:X,persistenceStrategy:G}),V=Y?Promise.allSettled([Y.promise]).then(()=>B):B;return this.trackSectionControllerDisposal(J,V)}trackSectionControllerDisposal(Z,Q){this.sectionControllerDisposePromises.set(Z,Q);let J=()=>{if(this.sectionControllerDisposePromises.get(Z)===Q)this.sectionControllerDisposePromises.delete(Z)};return Q.then(J,J),Q}async disposeSectionControllerEntry(Z){try{await this.runSectionControllerDisposePipeline({key:Z.key,context:Z.context,controller:Z.controller,persistBeforeDispose:Z.args.persistBeforeDispose})}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.args.sectionId,attemptId:Z.args.attemptId},recoverable:!0})}finally{await this.finalizeSectionControllerDispose({context:Z.context,persistenceStrategy:Z.persistenceStrategy,clearPersistence:Z.args.clearPersistence})}}async runSectionControllerDisposePipeline(Z){let Q=[];if(Z.persistBeforeDispose!==!1)try{await Z.controller.persist?.()}catch(J){Q.push(J)}try{await Z.controller.dispose?.()}catch(J){Q.push(J)}if(Q.length===1)throw Q[0];if(Q.length>1)throw AggregateError(Q,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(Z.context,Z.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId})}async finalizeSectionControllerDispose(Z){if(Z.clearPersistence)await Z.persistenceStrategy?.clearSession?.(Z.context)}dispose(){if(this.disposePromise)return this.disposePromise;return this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise}async disposeOwnedResources(){let Z=[],Q=async(Y)=>{try{await Y()}catch(X){Z.push(X)}};await this.waitForAdmittedInitialization();let J=new Map;for(let[Y,X]of this.sectionControllerInitEntries)J.set(Y,X.key);for(let[Y,X]of this.sectionControllerKeys)J.set(Y,X);for(let Y of J.values())this.disposeSectionController({sectionId:Y.sectionId,attemptId:Y.attemptId});await Promise.allSettled(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let Y of this.activeSubscriptions.values())await Q(()=>Y.unsubscribeCurrent?.()),Y.unsubscribeCurrent=null;if(this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await Q(()=>this.ttsService.dispose()),await Q(()=>this.toolProviderRegistry.destroy()),await Q(()=>this.highlightCoordinator.destroy()),await Q(()=>this.ownedToolCoordinator.destroy()),await Q(()=>this.catalogResolver.destroy()),await Q(()=>this.toolRequests.dispose()),await Q(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.policyDiagnosticListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus)this.frameworkErrorBus.dispose();if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let Z=new Set;if(this.coordinatorReadyPromise)Z.add(this.coordinatorReadyPromise);if(this.ttsInitPromise)Z.add(this.ttsInitPromise);if(this.ttsReconfigurePromise)Z.add(this.ttsReconfigurePromise);for(let Q of this.providerInitPromises.values())Z.add(Q);await Promise.allSettled(Z)}async ensureTTSReady(){if(this.assertNotDisposed(),await this.waitForPendingTTSReconfigure(),this.assertNotDisposed(),this.ttsInitialized)return;if(this.ttsInitPromise)return this.ttsInitPromise;return this.ttsInitPromise=this._initializeTTS().then(()=>this.assertNotDisposed()).finally(()=>{this.ttsInitPromise=void 0,this.notifyReadyChange()}),this.ttsInitPromise}async waitForPendingTTSReconfigure(){let Z=this.ttsReconfigurePromise;while(Z)await Z,Z=this.ttsReconfigurePromise}async _initializeTTS(){if(this.ttsInitialized)return;let Z=this.resolveTTSToolConfig(),Q=U7(Z),J=c0(Q),Y=$7(Q);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:J}}),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:J}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:J}),this.toolProviderRegistry.has("textToSpeech"))try{let j=await(await this.initializeProvider("textToSpeech",!0)).createInstance();await this.initializeTTSService(j,Y),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:J,provider:"registry"});return}catch(G){if(G instanceof c)throw G;let j=G instanceof Error?G:Error(String(G));await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",operation:"tts-init",backend:J,fromProvider:"registry",toProvider:"browser",reason:j.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",j)}else if(J!=="browser")this.reportMissingTTSProvider(J);let X=new K7;try{await this.initializeTTSService(X,J==="browser"?Y:d9(Y)),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:J,provider:"browser-fallback"})}catch(G){if(G instanceof c)throw G;let j=G instanceof Error?G:Error(String(G));throw this.reportStartFailure(j,{phase:"tts-init"},["textToSpeech"]),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:j.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:J,errorType:"TTSInitError",message:j.message}),j}}resolveTTSToolConfig(){return this.getTTSConfigFromProviders()||{}}async initializeTTSService(Z,Q){let J={...Q.providerOptions,__pieTelemetry:async(X,G)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...G||{}})}},Y={...Q,providerOptions:J};await this.ttsService.initialize(Z,Y),this.assertNotDisposed(),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,this.ttsDegraded=!1,this.degradedTools.delete("textToSpeech"),await this.hooks.onTTSReady?.(),this.assertNotDisposed()}async waitUntilReady(){if(this.assertNotDisposed(),this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{if(await this.ensureStateLoaded(),this.assertNotDisposed(),this.ttsRequiredForReadiness())await this.startTTSForReadiness();if(this.assertNotDisposed(),!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return(this.stateLoadSettled||!this.hooks.loadToolState)&&(this.ttsInitialized||this.ttsDegraded||!this.ttsRequiredForReadiness())}ttsRequiredForReadiness(){if(this.getTTSConfigFromProviders()?.enabled===!1)return!1;return!this.lazyInit||this.isToolGranted("textToSpeech")}async startTTSForReadiness(){try{await this.ensureTTSReady()}catch(Z){if(Z instanceof c)throw Z;if(this.isToolGranted("textToSpeech"))throw Z;this.ttsDegraded=!0,this.notifyReadyChange()}}getTTSConfigFromProviders(){return this.config.tools?.providers?.textToSpeech}assertCanonicalToolId(Z){if(typeof Z!=="string"||Z.trim().length===0)throw Error("Tool id must be a non-empty string.");if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Z))throw Error(`Unknown tool id "${Z}".`)}installToolContextResolvers(Z){if(!Z)return;for(let[Q,J]of Object.entries(Z)){if(J==null)continue;if(this.assertCanonicalToolId(Q),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);this.toolContextResolvers.set(Q,J)}}setToolContextResolvers(Z){this.toolContextResolvers.clear(),this.installToolContextResolvers(Z??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Z of this.toolContextResolverChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Q)}}getToolConfig(Z){return this.assertCanonicalToolId(Z),this.config.tools?.providers?.[Z]||null}updateToolConfig(Z,Q){this.assertCanonicalToolId(Z);let J=this.getToolConfig(Z)||{};if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});if(!this.config.tools.providers)this.config.tools.providers={};let Y={...this.config.tools.providers,[Z]:A2(Z,J,Q)},X=this.validateToolsConfig({...this.config.tools,providers:Y},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X,this.policyEngine.updateInputs({tools:X}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Z}),this._applyToolConfigChange(Z)}updateToolsPlacement(Z){if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});let Q=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Z.section??Q.section??[]],item:[...Z.item??Q.item??[]],passage:[...Z.passage??Q.passage??[]]},Y=this.validateToolsConfig({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});Y.placement=J,this.config.tools=Y,this.policyEngine.updateInputs({tools:Y})}decideToolPolicy(Z){let Q=this.policyEngine.decide(Z);return this.warnPolicyDiagnostics(Q.diagnostics),Q}warnPolicyDiagnostics(Z){for(let Q of Z){let J=Q.code==="tool-policy.itemSettingNotApplied"?Q.details.itemId:"",Y=`${Q.code}\x00${Q.toolId}\x00${J}`;if(this.reportedPolicyDiagnostics.has(Y))continue;this.reportedPolicyDiagnostics.set(Y,Q),console.warn(`[ToolkitCoordinator] ${Q.message}`);for(let X of Array.from(this.policyDiagnosticListeners))this.notifyPolicyDiagnosticListener(X,Q)}}notifyPolicyDiagnosticListener(Z,Q){try{Z(Q)}catch(J){console.error("[ToolkitCoordinator] Policy diagnostic listener failed:",J)}}registerItemSettings(Z,Q){return this.policyEngine.registerItemSettings(Z,Q)}decideFeaturePolicy(Z,Q){let J=this.policyEngine.decideFeature(Z,Q);if(this.warnPolicyDiagnostics(J.diagnostics),!J.assessmentBound&&this.policyEngine.getInputs().assessmentExpected&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Z}" with no assessment bound, so profile, district and test-administration policy have nothing to read and only an item's requiredTools can grant. Pass the assessment to the toolkit's assessment property, or call updateAssessment(...), before relying on any accommodation. Reported once per coordinator.`);return J}onPolicyChange(Z){return this.policyEngine.onPolicyChange(Z)}onPolicyDiagnostic(Z){this.policyDiagnosticListeners.add(Z);for(let Q of Array.from(this.reportedPolicyDiagnostics.values()))this.notifyPolicyDiagnosticListener(Z,Q);return()=>{this.policyDiagnosticListeners.delete(Z)}}onCatalogsChange(Z){return this.catalogResolver.onCatalogsChange(Z)}updateAssessment(Z){this.policyEngine.updateInputs({assessment:Z})}setPnpEnforcement(Z){this.policyEngine.updateInputs({pnpEnforcement:Z})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Z){return this.policyEngine.registerPolicySource(Z)}hasToolContextResolver(Z){return this.assertCanonicalToolId(Z),this.toolContextResolvers.has(Z)}resolveToolContext(Z){this.assertCanonicalToolId(Z.toolId);let Q=this.toolContextResolvers.get(Z.toolId);if(!Q)return null;let J;try{J=Q(Z)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Z.toolId}" threw:`,X),{toolId:Z.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Z.toolId,visible:!0,params:{}};let Y=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Z.toolId,visible:J.visible!==!1,params:Y,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Z){return this.toolContextResolverChangeListeners.add(Z),()=>{this.toolContextResolverChangeListeners.delete(Z)}}getToolRegistry(){return this.toolRegistry}registerToolRequestTarget(Z){return this.toolRequests.registerTarget(Z)}requestTool(Z){return this.assertCanonicalToolId(Z.toolId),this.toolRequests.request(Z)}canRequestTool(Z,Q,J){try{this.assertCanonicalToolId(Z)}catch{return!1}return this.toolRequests.canRequest(Z,Q,J)}onToolRequestTargetsChange(Z){return this.toolRequests.onTargetsChange(Z)}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Z){if(this.disposePromise!==null)return;if(Z==="textToSpeech"){this.scheduleTTSReconfigure();return}this._registerChangedToolProvider(Z)}_registerChangedToolProvider(Z){let Q=this.getProviderDescriptorTools().find((J)=>J.toolId===Z);if(!Q)return;this.degradedTools.delete(Z),this.registerProviderFromTool(Q,!0)}scheduleTTSReconfigure(){let Z=this.ttsInitPromise,Q=Z?Z.catch(()=>{}).then(()=>this._reconfigureTTSProvider()):this._reconfigureTTSProvider();this.ttsReconfigurePromise=Q,Q.finally(()=>{if(this.ttsReconfigurePromise===Q)this.ttsReconfigurePromise=void 0}),Q.then(async()=>{if(this.disposePromise!==null)return;if(this.ttsRequiredForReadiness())await this.startTTSForReadiness()}).catch(()=>{})}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsDegraded=!1,this.degradedTools.delete("textToSpeech"),this.ttsInitPromise=void 0,this.notifyReadyChange();try{this.ttsService.releaseProvider()}catch{}if(this.toolProviderRegistry.has("textToSpeech"))await this.toolProviderRegistry.unregister("textToSpeech");if(this.disposePromise!==null)return;let Z=this.getProviderDescriptorTools().find((Q)=>Q.toolId==="textToSpeech");if(!Z)return;await this.registerProviderFromTool(Z)}}var L2=()=>{};function Y1(Z){return Z===R.PLAYING||Z===R.LOADING}function X1(Z){let{ttsService:Q,silence:J}=Z;if(typeof Q?.onStateChange!=="function")return L2;let Y=Q.onStateChange((X)=>{if(Y1(X))J()});return()=>{try{Y()}catch{}}}function G1(Z){try{if(Y1(Z?.getState?.()))Z?.pause?.()}catch{}}import{timedMediaProjectionSignature as c2}from"@pie-players/pie-players-shared/timed-media";function j1(Z,Q,J){let Y=Z.detail?.runtimeId;if(typeof Y==="string"&&Y!=="")return Y===Q;return J(Z.target)}function B1(Z,Q,J){let Y=[Z.catalogResolver.registerOwner({owner:{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:J.assessmentId,sectionId:J.sectionId},entity:Q.item})];if(Q.kind==="item"&&Q.settings)Y.push(Z.registerItemSettings(Q.canonicalItemId||Q.itemId,Q.settings));return Y}var M2=["a[href]","button","label","summary",...["button","checkbox","combobox","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","switch","tab","treeitem"].map((Z)=>`[role="${Z}"]`)].join(", "),W1=new Set(["mi","mn","mtext"]),P2=(Z)=>W1.has(Z.localName)||Z.localName==="mrow"&&Z.children.length===1&&W1.has(Z.children[0].localName),N2=(Z)=>Array.from(Z.getElementsByTagName("mfrac")).every((Q)=>Array.from(Q.children).every(P2))?"Fraction_Over":"Fraction_General",w2=(Z)=>!Z||Z.toLowerCase().split("-")[0]==="en";function V1(Z,Q={}){if(typeof MutationObserver>"u")return()=>{};let J=new Map,Y=!1,X=async(U,$,z)=>{let D=await oZ([{type:"math",mathml:U,fallbackText:""}],{language:z,loadSre:Q.loadSre,mathSpeech:{...w2(z)?{style:N2($)}:{},engineOptions:Q.getMathSpeech?.()?.engineOptions}});return D.usedMathSpeech?D.speechText:null},G=(U)=>{if(!T5(U,M2))return;let $=CZ(U,"math"),z=$&&rZ($.outerHTML);if(!$||!z)return;let D=E8(U,{contentLanguage:Q.getContentLanguage?.()}),L=`${D??""}\x00${z}`,P=J.get(L);if(!P)P=X(z,$,D),J.set(L,P);P.then((A)=>{if(Y||!A||!U.isConnected)return;if(U.getAttribute("aria-label")!==A)U.setAttribute("aria-label",A)})},j=new WeakSet,B=(U)=>{if(j.has(U))return;j.add(U),K.observe(U,{childList:!0,subtree:!0})},V=(U)=>{if(U.nodeType!==1)return;let $=U,z=T5($,"mjx-container");if(z){G(z);return}if($.shadowRoot)B($.shadowRoot);V0($,(D)=>{if(D.nodeType!==1)return"skip";let L=D;if(L.localName==="mjx-container")return G(L),"skip";if(L.shadowRoot)B(L.shadowRoot);return})},K=new MutationObserver((U)=>{for(let $ of U)for(let z of $.addedNodes)V(z)});return B(Z),V(Z),()=>{Y=!0,K.disconnect()}}import{createPieLogger as C2,isGlobalDebugEnabled as b2}from"@pie-players/pie-players-shared";function R2(Z,Q){if(Z===Q)return 0;let J=Z.compareDocumentPosition(Q);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class O7{shellsByElement=new Map;register(Z){let Q=this.shellsByElement.get(Z.element),J={...Z,sortKey:Date.now()};if(Q&&Q.kind===J.kind&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Z.element,J),!0}unregister(Z){return this.shellsByElement.delete(Z)}getOrderedShells(Z){let Q=Array.from(this.shellsByElement.values()).filter((J)=>!Z||J.kind===Z);return Q.sort((J,Y)=>R2(J.element,Y.element)),Q}getCanonicalIdMap(){let Z={};for(let Q of this.getOrderedShells("item")){if(!Q.itemId)continue;Z[Q.itemId]=Q.canonicalItemId||Q.itemId}return Z}clear(){this.shellsByElement.clear()}}var q1=C2("section-controller-binding",()=>b2());function E2(Z){let Q=Z?.renderables;if(!Array.isArray(Q))return null;let J=new Set;for(let Y of Q){let X=Y?.entity?.id;if(typeof X==="string"&&X)J.add(X)}return J}function K1(Z,Q){return Z.has(Q.itemId)||!!Q.canonicalItemId&&Z.has(Q.canonicalItemId)}class L7{registry=new O7;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;sectionRenderableIds=null;boundSections=new Map;loadedRenderableKeys=new Set;async initialize(Z){this.activeInitToken+=1;let Q=this.activeInitToken;this.coordinator=Z.coordinator,this.sectionId=Z.sectionId,this.attemptId=Z.attemptId,this.forgetUnregisteredLoads(Z.coordinator.getSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId}));let J;try{J=await Z.coordinator.getOrCreateSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId,input:{section:Z.section,sectionId:Z.sectionId,assessmentId:Z.assessmentId,view:Z.view},updateExisting:!0,initialSession:Z.initialSession,createDefaultController:Z.createDefaultController})}catch(X){if(Q===this.activeInitToken)this.unsubscribeController?.(),this.unsubscribeController=null,this.controller=null;throw X}if(Q!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.sectionRenderableIds=E2(J.getCompositionModel?.());let Y=this.getSectionKey(Z.sectionId,Z.attemptId);this.boundSections.delete(Y),this.boundSections.set(Y,{sectionId:Z.sectionId,attemptId:Z.attemptId,renderableIds:this.sectionRenderableIds}),this.replayRegisteredShellsIntoController(J),Z.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.((X)=>{try{Z.onControllerEvent?.(X)}catch(G){q1.warn("onControllerEvent handler threw",G)}Z.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Z){if(!Z.handleContentRegistered)return;let Q=this.registry.getOrderedShells().filter((Y)=>this.isSectionRenderable(Y));if(Q.length===0)return;for(let Y of Q){let X=Y.canonicalItemId||Y.itemId;Z.handleContentRegistered({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind})}let J=Date.now();for(let Y of Q){let X=Y.canonicalItemId||Y.itemId,G=this.getLoadedKey(X,Y.contentKind);if(this.loadedRenderableKeys.has(G))Z.handleContentLoaded?.({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind,timestamp:J})}}getLoadedKey(Z,Q){return`${Q??""}:${Z}`}isSectionRenderable(Z){let Q=this.sectionRenderableIds;return!Q||K1(Q,Z)}getSectionKey(Z,Q){return`${Z}\x00${Q??""}`}controllerFor(Z){if(this.isSectionRenderable(Z))return this.controller;let Q=this.getSectionKey(this.sectionId,this.attemptId),J=[...this.boundSections.entries()].reverse();for(let[Y,X]of J){if(Y===Q||!X.renderableIds)continue;if(!K1(X.renderableIds,Z))continue;let G=this.coordinator?.getSectionController({sectionId:X.sectionId,attemptId:X.attemptId});if(G)return G}return null}requireControllerFor(Z,Q){let J=this.controllerFor(Z);if(!J)q1.warn(`Dropped ${Q} for "${Z.itemId}": no section this toolkit bound renders it.`);return J}forgetUnregisteredLoads(Z){if(!Z||Z===this.controller)return;let Q=Z.getRuntimeState?.()?.loadedRenderables??[];if(Q.length===0)return;let J=new Set;for(let Y of this.registry.getOrderedShells())if(J.add(Y.itemId),Y.canonicalItemId)J.add(Y.canonicalItemId);for(let Y of Q){if(J.has(Y.canonicalItemId)||J.has(Y.itemId))continue;Z.handleContentUnregistered?.({itemId:Y.itemId,canonicalItemId:Y.canonicalItemId,contentKind:Y.contentKind})}}register(Z){return this.registry.register(Z)}unregister(Z){return this.registry.unregister(Z)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Z){return this.registry.getCanonicalIdMap()[Z]||this.controller?.getCanonicalItemId?.(Z)||Z}handleContentRegistered(Z){if(!this.isSectionRenderable(Z))return;this.controller?.handleContentRegistered?.({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId||Z.itemId,contentKind:Z.contentKind||Z.kind})}handleContentUnregistered(Z){let Q=Z.canonicalItemId||Z.itemId,J=this.getLoadedKey(Q,Z.contentKind);if(this.registry.getOrderedShells().some((X)=>this.getLoadedKey(X.canonicalItemId||X.itemId,X.contentKind)===J))return;this.loadedRenderableKeys.delete(J),this.controllerFor(Z)?.handleContentUnregistered?.({itemId:Z.itemId,canonicalItemId:Q,contentKind:Z.contentKind||Z.kind})}handleContentLoaded(Z){let Q=Z.canonicalItemId||Z.itemId;if(this.loadedRenderableKeys.add(this.getLoadedKey(Q,Z.contentKind)),!this.isSectionRenderable(Z))return;this.controller?.handleContentLoaded?.(Z)}handleItemPlayerError(Z){this.requireControllerFor(Z,"an item player error")?.handleItemPlayerError?.(Z)}reportSectionError(Z){(Z.itemId?this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId},"a section error"):this.controller)?.reportSectionError?.(Z)}updateItemSession(Z,Q){let J=this.getCanonicalItemId(Z);return this.requireControllerFor({itemId:Z,canonicalItemId:J},"a session update")?.updateItemSession?.(J,Q)??null}navigateToItem(Z){return this.controller?.navigateToItem?.(Z)??null}handleFormativeAction(Z){if(!Z?.itemId)return;let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId),J=this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a formative action");if(Z.action==="retry"){J?.retryFormativeItem?.({itemId:Q});return}J?.recordFormativeTry?.({itemId:Q,outcomes:Z.outcomes})}handleMediaTimeSource(Z){if(!Z?.renderableId)return;let Q=this.requireControllerFor({itemId:Z.renderableId,canonicalItemId:this.getCanonicalItemId(Z.renderableId)},"a media time source");if(Z.action==="detach"){Q?.detachMediaTimeSource?.({origin:Z.origin??"host"});return}if(!Z.source)return;Q?.attachMediaTimeSource?.(Z.source,{origin:Z.origin??"host",renderableId:Z.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}async dispose(){this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null;let Z=this.coordinator;if(Z)for(let Q of this.boundSections.values())await Z.disposeSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId});this.registry.clear(),this.loadedRenderableKeys.clear(),this.boundSections.clear(),this.controller=null,this.sectionRenderableIds=null,this.coordinator=null}}function U1(Z){let Q=Z.section?.identifier;return Z.sectionId||(typeof Q==="string"?Q:"")||`section-${Z.assessmentId||"default"}`}function $1(Z,Q){return["pnpEnforcement","assessment"].filter((Y)=>Z?!Object.is(Z[Y],Q[Y]):Q[Y]!==null)}function z1(Z){if(!Z)return;let Q=Symbol.for("pie.assessmentToolkit.unclaimedRegistrationWatch"),J=Z;if(J[Q])return;J[Q]=!0,Z.addEventListener(a0,(Y)=>{let X=Y.detail,G=typeof X?.itemId==="string"?X.itemId:"";F1(Z,"unclaimedRegistration",`[pie-assessment-toolkit] Item "${G}" registered, but no toolkit claimed the registration, so its accessibility catalogs are not filed and it does not count toward its section's loading. Render its shell or scope inside the <pie-assessment-toolkit> that answered it. Reported once per page.`)})}function z0(Z,Q){if(typeof Z==="function")return Z;if(Z===null)return null;return typeof Q==="function"?Q:null}function D1(Z={}){let Q=Z.frameDeadlineMs??100,J=!1,Y=null,X=null,G=null,j=null,B=null;function V(){if(J=!1,X!==null)j?.(X),X=null;if(G!==null)B?.(G),G=null;j=null,B=null}function K(z){if(!J)return;if(z==="frame")X=null;if(z==="timer")G=null;let D=Y;Y=null,V(),D?.()}function U(z){if(Y=z,J)return;J=!0;let D=globalThis,L=z0(Z.requestFrame,D.requestAnimationFrame);j=z0(Z.cancelFrame,D.cancelAnimationFrame);let P=z0(Z.setTimer,D.setTimeout);if(B=z0(Z.clearTimer,D.clearTimeout),L){let N=L(()=>K("frame"));if(!J)return;if(X=N,P){let O=P(()=>K("timer"),Q);if(J)G=O}return}let A=z0(Z.queueMicrotaskFn,D.queueMicrotask);if(A){A(()=>K("microtask"));return}if(P){let N=P(()=>K("timer"),0);if(J)G=N;return}K("microtask")}function $(){if(!J)return;Y=null,V()}return{schedule:U,cancel:$,isPending:()=>J}}function A1(Z="runtime"){return`${Z}-${Math.random().toString(16).slice(2)}-${Date.now()}`}function H1(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function _1(Z){Z.lastSessionEventSignatureByItemId.clear(),Z.lastMetadataSignatureByItemId.clear()}function O1(Z){let{state:Q,itemId:J,payload:Y}=Z;if(y2(Y)){let j=T2(Y);if(Q.lastMetadataSignatureByItemId.get(J)===j)return!1;Q.lastMetadataSignatureByItemId.set(J,j)}let X=S2(Y);if(Q.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Q.lastSessionEventSignatureByItemId.set(J,X),!0}function S2(Z){let Q={...Z};delete Q.timestamp,delete Q.sourceRuntimeId;try{return JSON.stringify(Q)}catch{return String(Q.itemId||"")}}function y2(Z){return Z.intent==="metadata-only"}function T2(Z){try{return JSON.stringify({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId,intent:Z.intent,complete:Z.complete??null,component:Z.component??null})}catch{return String(Z.itemId||"")}}var x2=(Z,Q)=>{if(customElements.get(Z))return;try{customElements.define(Z,Q)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Z))throw J}},d2=N7('<div class="pie-assessment-toolkit-error svelte-15pthty" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-15pthty"> </div> <div class="pie-assessment-toolkit-error-message svelte-15pthty"> </div> <pre class="pie-assessment-toolkit-error-details svelte-15pthty"> </pre></div>'),l2=N7('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),i2={hash:"svelte-15pthty",code:`.pie-assessment-toolkit-anchor.svelte-15pthty {display:none;}.pie-assessment-toolkit-error.svelte-15pthty {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
224
- color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-15pthty {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-15pthty {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-15pthty {margin:0;white-space:pre-wrap;word-break:break-word;}`};function l1(Z,Q){w1(Q,!0),x1(Z,i2);let J=h2("pie-assessment-toolkit",()=>m2()),Y=A1("toolkit"),X=new L7,G=new W0,j={mode:"gather",role:"student"},B={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},V="Unable to initialize assessment toolkit.",K=k(Q,"assessmentId",7,""),U=k(Q,"section",7,null),$=k(Q,"sectionId",7,""),z=k(Q,"attemptId",7,""),D=k(Q,"env",23,()=>({})),L=k(Q,"ndsIcons",7,!1),P=k(Q,"locale",7,""),A=k(Q,"contentLanguage",7,""),N=k(Q,"lazyInit",7,!1),O=k(Q,"toolConfigStrictness",7,"error"),S=k(Q,"tools",23,()=>({})),C=k(Q,"toolContextResolvers",7,null),h=k(Q,"enabledTools",7,""),b=k(Q,"toolRegistry",7,null),d=k(Q,"accessibility",23,()=>({})),VZ=k(Q,"player",7,null),r=k(Q,"playerType",7,""),s=k(Q,"coordinator",7,null),AZ=k(Q,"createSectionController",7,null),HZ=k(Q,"onFrameworkError",7,null),_Z=k(Q,"errorRenderer",7,null),D0=k(Q,"assessment",7,null),qZ=k(Q,"isolation",7,"inherit"),OZ=k(Q,"session",7,null),Q0=n(null),u=n(null),QZ=n(null),w7=null,R7=null,J0=!1,mZ=null,uZ=null,pZ=null,A0=n(0),Y5=n(null),JZ=n(null),X5=n(V),G5=n(C1([])),C7="",j5="",Y0=null,X0=null,H0=null,b7=null,B5=null,E7=null,_0=null,S7=!1,y7=null,T7=!1,x7=n(""),W5=null,O0=D1(),LZ=[],L0=new Map,V5=new WeakMap,M0=new Map,k7=H1(),G0=n(!1);function i1(){if(!F(Q0))return null;let W=F(Q0).getRootNode();if(W&&"host"in W)return W.host;return F(Q0).parentElement}let f=i(()=>i1());function MZ(W,q){if(!F(f)){LZ=[...LZ,{name:W,detail:q}];return}P7(F(f),W,q)}y(()=>{if(!F(f))return;if(LZ.length===0)return;let W=LZ;LZ=[],queueMicrotask(()=>{let q=F(f);if(!q){LZ=[...W,...LZ];return}for(let H of W)P7(q,H.name,H.detail)})});function f7(W){return W.details.length>0?W.details:[W.message]}function s1(W){if(!_Z())return{title:V,details:f7(W)};try{let q=_Z()(W)||{};return{title:typeof q.title==="string"&&q.title.trim().length>0?q.title:V,details:Array.isArray(q.details)&&q.details.length>0?q.details.map((H)=>String(H)):f7(W)}}catch(q){let H=q instanceof Error&&q.message.trim().length>0?q.message:String(q||"Unknown renderer error");return{title:V,details:[...W.details,`Error renderer failed: ${H}`]}}}function PZ(W){let q=y5({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable,scope:W.cohort?"cohort":"runtime",cohort:W.cohort});return G.reportFrameworkError(q),q}function I7(W){return(W||[]).map((q)=>q?.message).filter((q)=>typeof q==="string")}function n1(W,q){if(W?.type==="timed-media-policy-degraded"){G.reportFrameworkError(E0({kind:"timed-media",severity:"warning",source:"pie-assessment-toolkit",message:"A timed-media playback policy degraded to advisory: the media time source does not report the capability it needs.",details:I7(W.degradations),recoverable:!0,scope:"cohort",cohort:q}));return}if(W?.type!=="timed-media-invalid")return;G.reportFrameworkError(E0({kind:"timed-media",severity:"error",source:"pie-assessment-toolkit",message:'This section declares sectionType: "timed-media" but its timedMedia data is not deliverable; the section renders without cue behavior.',details:I7(W.errors),recoverable:!1,scope:"cohort",cohort:q}))}function r1(W){if(W?.type!=="timed-media-audio-started")return;if(!F(E))return;G1(F(E).ttsService)}function o1(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function j0(W){return`${W.kind}|${W.source}|${W.message}`}function v7(W){if(!HZ())return;try{HZ()(W),C7=j0(W)}catch(q){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,q)}}let h7=new WeakSet,m7=new WeakMap;function a1(W){if(typeof W!=="object"||W===null)return null;return m7.get(W)??null}function u7(W){let q=s1(W);v(JZ,W,!0),v(X5,q.title,!0),v(G5,q.details,!0)}function p7(){v(JZ,null),v(X5,V),v(G5,[],!0)}y(()=>{let W=G.subscribeFrameworkErrors((q)=>{if(console.error(D8(q),q.cause),typeof q.cause==="object"&&q.cause!==null)m7.set(q.cause,q);if(o1(q.kind)&&!h7.has(q))u7(q);MZ("framework-error",q),v7(q)});return()=>{W()}}),y(()=>{let W=s();if(!W||F(E)!==W)return;if(typeof W.subscribeFrameworkErrors!=="function")return;return I(()=>W.subscribeFrameworkErrors((q)=>{h7.add(q),G.reportFrameworkError(q)}))}),y(()=>{let W=F(E),q=b();if(!W||F(w0))return;if(typeof W.adoptToolRegistry!=="function")return;I(()=>{let H=W===F(u);if(H&&!q)return;if(W.adoptToolRegistry(q)&&H&&Y0)Y0={...Y0,toolRegistry:q}})}),y(()=>{if(!F(JZ))return;if(C7===j0(F(JZ)))return;v7(F(JZ))});function t1(W){let q=5381;for(let H=0;H<W.length;H+=1)q=(q<<5)+q^W.charCodeAt(H);return(q>>>0).toString(36)}function o(W){return W&&typeof W==="object"?W:{}}function e1(W){let q=o(W.section),H=typeof q.identifier==="string"?q.identifier:"",w=typeof W.sectionId==="string"?W.sectionId:"";return H||w}function Z6(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function Q6(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((H,w)=>{let M=o(H),_=o(M.entity),l=typeof _.id==="string"&&_.id||`renderable-${w}`,C0=o(_.config),H5=typeof _.version==="string"&&_.version||(typeof _.version==="number"?String(_.version):"")||(typeof C0.version==="string"?C0.version:"");return{id:l,version:H5}})}function J6(W){let q=o(W.itemSessionsByItemId);return Object.keys(q).sort((H,w)=>H.localeCompare(w)).map((H)=>{let w=o(q[H]),M=typeof w.id==="string"?w.id:"",_=Array.isArray(w.data)?w.data:[],l="";try{l=t1(JSON.stringify(_))}catch{l=String(_.length)}return{itemId:H,sessionId:M,payloadSignature:l}})}function Y6(W){let q=o(o(W.formative).states);return Object.entries(q).map(([H,w])=>{let M=o(w),_=o(M.lastOutcome).correctness??"";return`${H}:${M.tryCount??0}:${M.revealed===!0?1:0}:${String(_)}:${String(M.revealOverride??"")}`}).sort().join("|")}function X6(W){let q=W.timedMedia;return c2(q)}function G6(W){let q=o(W),H=Q6(q).map((M)=>`${M.id}:${M.version}`).join("|"),w=J6(q).map((M)=>`${M.itemId}:${M.sessionId}:${M.payloadSignature}`).join("|");return{sectionId:e1(q),currentItemIndex:Z6(q),renderableSignature:H,itemSessionSignature:w,formativeSignature:Y6(q),timedMediaSignature:X6(q)}}function j6(W){let q=G6(W);return`${q.sectionId}|${q.currentItemIndex}|${q.renderableSignature}|${q.itemSessionSignature}|${q.formativeSignature}|${q.timedMediaSignature}`}function g7(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function B6(W,q){let H=W?.type,w=g7(H)?H:g7(q)?q:W?.tagName?"custom":"iife",M=W?.tagName?.trim();if(w==="custom"&&!M)return{type:"iife",tagName:B.iife,version:void 0,source:void 0,isDefault:!0};return{type:w,tagName:M||B[w],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!q}}function c7(W){let q=W||{},H=typeof q.mode==="string"&&q.mode.trim()?q.mode.trim():j.mode,w=typeof q.role==="string"&&q.role.trim()?q.role.trim():j.role;return{mode:H,role:w}}function W6(W){let q=c7(W);if(q.mode==="author")return"author";if(q.role==="instructor")return"scorer";return"candidate"}function d7(W,q){return W.sectionId===q.sectionId&&W.attemptId===q.attemptId}function l7(){if(!OZ()||OZ()===b7)return;b7=OZ(),H0={value:OZ(),cohort:{sectionId:F(e),attemptId:z()||void 0}}}function i7(W,q){l7();let H=H0;if(!H)return null;if(!d7(H.cohort,W)){if(q)H0=null;return null}return H0=null,H.value}function s7(){let W=B5,q=F(E);if(!W||!q)return;let H=i7(W,!1);if(!H)return;let w=q.getSectionController(W);if(!w)return;let M=r0(w.getSession?.()??null,H);if(!M)return;Promise.resolve().then(()=>{if(!w.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");return w.applySession(M,{mode:"replace"})}).catch((_)=>{PZ({kind:"unknown",source:"pie-assessment-toolkit",error:_,recoverable:!0})})}async function V6(){if(AZ())return AZ()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function q5(){let W=S()||{},q=h1(h());if(q.length===0)return W;let H=W.placement||{},w=Array.isArray(H.section)?H.section:null;if(w&&w.length>0)return W;return{...W,placement:{...H,section:q}}}function q6(){return J8(q5(),{strictness:O(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:b()}).config}function K6(){let W="",q="";try{W=JSON.stringify(q5())}catch{W="[unserializable-tools]"}try{q=JSON.stringify(Object.entries(C()??{}).map(([H,w])=>[H,typeof w]))}catch{q="[unserializable-resolvers]"}return[K()||"",String(O()||"error"),W,q].join("|")}function U6(W){let q=W?.pnpEnforcement;return q==="on"||q==="off"?q:null}function $6(W){let q=K()||U()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new _7({assessmentId:q,lazyInit:N(),eagerInit:!1,toolConfigStrictness:O(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:W,toolRegistry:b(),toolContextResolvers:C(),accessibility:d(),frameworkErrorBus:G})}function n7(W){try{return JSON.stringify(W??null)}catch{return"[unserializable]"}}function r7(){return{signatures:{assessmentId:K()||"",toolConfigStrictness:String(O()||"error"),lazyInit:String(N()),tools:n7({...q5(),pnpEnforcement:void 0}),accessibility:n7(d())},toolRegistry:b()}}function F6(){let W=Y0;if(!W)return[];let q=r7(),H=Object.keys(q.signatures).filter((w)=>q.signatures[w]!==W.signatures[w]);if(W.toolRegistry&&q.toolRegistry!==W.toolRegistry)H.push("toolRegistry");return H}function z6(W,q){if(S7)return;S7=!0,console.warn(`[pie-assessment-toolkit] ${W.join(", ")} changed after ${q} with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section or the first item scope, pass a coordinator of your own, or update this one from runtime-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`)}function D6(W){if(T7)return;T7=!0,console.warn(`[pie-assessment-toolkit] The toolkit above this one (runtime "${W}") had no coordinator when this one connected, so this one built its own and keeps it: the two share no tool state, policy or read-aloud. Give the outer toolkit its coordinator before the inner one connects, or set isolation="force" on the inner one to keep them apart on purpose. Reported once per toolkit.`)}function P0(){let W=F(u);if(!W)return Promise.resolve();return v(u,null),W.dispose()}function N0(W){PZ({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}let w0=i(()=>!s()&&qZ()!=="force"&&F(QZ)?.coordinator!=null),E=i(()=>{if(F(w0))return F(QZ)?.coordinator;return s()||F(u)}),K5=i(()=>U()!=null);y(()=>{F(f),s(),qZ(),F(QZ),C(),F(K5),F(G0),S(),h(),K(),O(),N(),d(),b(),I(()=>{if(!F(f))return;if(s()){if(F(u))P0().catch(N0);mZ=null;return}if(qZ()!=="force"&&F(QZ)?.coordinator){if(F(u))P0().catch(N0);mZ=null;return}if(F(u)){let W=F6();if(W.length>0&&X0)z6(W,X0);else if(W.length>0&&(U()||F(G0)))P0().catch(N0)}if(F(u)&&mZ!==C()){try{F(u).setToolContextResolvers(C()),mZ=C()}catch(W){PZ({kind:"coordinator-init",source:"pie-assessment-toolkit",error:W})}return}if(!F(u)){if(qZ()!=="force"&&!J0){let q=M1(F(f),J5);if(q?.coordinator&&q.runtimeId!==Y){v(QZ,q,!0),mZ=null;return}}let W=K6();if(j5===W)return;try{let q=q6();v(u,$6(q),!0),J0=qZ()!=="force",Y0=r7(),X0=null,mZ=C(),j5="",p7()}catch(q){v(u,null),j5=W,PZ({kind:"coordinator-init",source:"pie-assessment-toolkit",error:q})}}})}),y(()=>{if(!F(G0)||!F(E))return;let W=F(E);I(()=>{if(W===F(u))X0??="an item registered"})});let R0=p2(),U5=n(0);y(()=>R0.subscribe(()=>{v(U5,F(U5)+1)})),y(()=>{let W=typeof P()==="string"?P().trim():"";I(()=>{Promise.resolve(R0.setLocale(W||g2)).catch((q)=>{PZ({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:q instanceof Error?q:Error(String(q)),recoverable:!0})})})});let NZ=i(()=>K()||F(E)?.assessmentId||""),e=i(()=>U1({sectionId:$(),section:U(),assessmentId:K()})),$5=i(()=>c7(D())),A6=i(()=>W6(F($5))),gZ=i(()=>B6(VZ(),r())),B0=i(()=>I2({player:F(gZ),component:"pie-assessment-toolkit"})),H6=i(()=>{if(!F(E))return null;return{toolkitCoordinator:F(E),toolCoordinator:F(E).toolCoordinator,ttsService:F(E).ttsService,highlightCoordinator:F(E).highlightCoordinator,catalogResolver:F(E).catalogResolver,elementToolStateStore:F(E).elementToolStateStore,assessmentId:F(NZ),sectionId:F(e),attemptId:z()||void 0,itemPlayer:F(gZ),ndsIcons:L()===!0,locale:(F(U5),R0.getLocale()),i18n:R0,contentLanguage:A()?.trim()||void 0,reportSectionError:(W)=>{X.reportSectionError({source:"section-runtime",error:W,timestamp:Date.now()})}}}),_6=i(()=>{if(!F(E)||!F(f))return null;return{runtimeId:Y,coordinator:F(E),sectionBound:F(K5),eventTarget:F(f)}});function o7(W){if(W==null)return;let q=j6(W);if(q===F(x7))return;v(x7,q,!0),v(A0,F(A0)+1),v(Y5,W,!0),MZ("composition-changed",{composition:F(Y5),version:F(A0)})}function F5(W){W5=W??X.getCompositionModel(),O0.schedule(()=>{o7(W5)})}function O6(){if(!O0.isPending())return;O0.cancel(),o7(W5)}function z5(W){if(!W)return;let q=V5.get(W);if(!q)return;for(let H of q)H();V5.delete(W)}function a7(){for(let W of L0.values())z5(W.element)}function t7(W){if(z5(W.element),!F(E))return;V5.set(W.element,B1(F(E),W,{assessmentId:F(NZ),sectionId:F(e)}))}function L6(){a7();for(let W of L0.values())t7(W)}function D5(W){if(!W)return;M0.get(W)?.(),M0.delete(W)}function M6(W){D5(W),M0.set(W,V1(W,{getMathSpeech:()=>F(E)?.ttsService.getMathSpeechOptions(),getContentLanguage:()=>A()}))}function P6(W){let H={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:Y};if(!O1({state:k7,itemId:W.itemId,payload:H}))return;MZ("session-changed",H)}function N6(W){if(!(W instanceof HTMLElement))return!1;return M1(W,J5)?.runtimeId===Y}function wZ(W){return W.detail??null}function w6(W,q){for(let H of q)W.addEventListener(H.name,H.handler);return()=>{for(let H of q)W.removeEventListener(H.name,H.handler)}}y(()=>{let W=F(f),q=qZ();return I(()=>{if(!W)return;if(q==="force")return v(QZ,null),()=>{J0=!1};let H=v1(W,(w)=>{if(w.runtimeId===Y)return;if(J0){D6(w.runtimeId);return}v(QZ,w,!0)});return()=>{H(),v(QZ,null),J0=!1}})}),y(()=>{let W=F(E);if(!W)return;return I(()=>X1({ttsService:W.ttsService,silence:()=>X.requestMediaPauseForCompetingAudio()}))}),y(()=>{let W=F(w0)?F(QZ)?.runtimeId??null:null,q=W?"inherited":"owned";if(q!==w7)w7=q,MZ(q==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:Y,parentRuntimeId:W})}),y(()=>{let W=F(f);if(!W)return;I(()=>z1(W.ownerDocument))}),y(()=>{let W=F(E);if(!W)return;let q=F(w0)?"inherited":"owned";I(()=>{if(W===R7)return;R7=W,MZ("runtime-ready",{runtimeId:Y,coordinator:W,ownership:q})})}),y(()=>{let W=F(e),q=z()||"";_1(k7)}),y(()=>{if(!F(f))return;F(f).setAttribute("data-item-player-type",F(gZ).type),F(f).setAttribute("data-item-player-tag",F(gZ).tagName),F(f).setAttribute("data-env-mode",F($5).mode),F(f).setAttribute("data-env-role",F($5).role)}),y(()=>{return F(E),F(NZ),F(e),L6(),()=>{a7()}}),y(()=>{if(!F(f))return;return f2({host:F(f),instrumentationProvider:F(B0),component:"pie-assessment-toolkit",eventMap:v2,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:F(NZ),sectionId:F(e),attemptId:z()||void 0}})});let A5=null;y(()=>{D0(),S();let W=F(E);if(!W)return;if(W!==F(u))return;I(()=>{let q={pnpEnforcement:U6(S()),assessment:D0()??null},H=A5?.coordinator===W?A5.inputs:null;A5={coordinator:W,inputs:q};for(let w of $1(H,q))if(w==="pnpEnforcement")W.setPnpEnforcement(q.pnpEnforcement);else W.updateAssessment(q.assessment)})}),y(()=>{if(!F(E))return;return F(E).subscribeTelemetry(({eventName:W,payload:q})=>{if(!u2(F(B0)))return;if(!F(B0).isReady())return;let H=new Date().toISOString(),w={...q||{},instrumentationLayer:"toolkit",assessmentId:F(NZ),sectionId:F(e),attemptId:z()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:H};F(B0).trackEvent(W,w);let M=q&&typeof q.errorType==="string"?q.errorType:void 0;if(!W.endsWith("-error")&&!M)return;let _=q&&typeof q.message==="string"?q.message:`Toolkit telemetry error: ${W}`;F(B0).trackError(Error(_),{component:"pie-assessment-toolkit",errorType:M||"ToolkitTelemetryError",...w})})}),y(()=>{if(!U()||!F(E))return;let W=!1;if(F(E)===I(()=>F(u)))X0??="a section initialized";let q={sectionId:F(e),attemptId:z()||void 0},H=E7;if(E7=q,H&&!d7(H,q))I(()=>P1(F(f),{reason:"teardown",logger:J}));B5=null;let w=I(()=>i7(q,!0));return X.initialize({coordinator:F(E),section:U(),sectionId:F(e),assessmentId:F(NZ),attemptId:z()||void 0,view:F(A6),initialSession:w,createDefaultController:V6,onCompositionChanged:(M)=>{if(W)return;F5(M)},onControllerEvent:(M)=>{if(W)return;r1(M),n1(M,q)}}).then(()=>{if(W)return;B5=q;let M=I(()=>F(JZ));if(M&&j0(M)===_0)p7();_0=null,I(()=>s7()),I(()=>O6()),queueMicrotask(()=>{if(W)return;MZ("toolkit-ready",{runtimeId:Y,assessmentId:F(NZ),sectionId:F(e),itemPlayer:F(gZ),coordinator:F(E)}),MZ("section-ready",{sectionId:q.sectionId,attemptId:q.attemptId,controller:F(E).getSectionController(q)??null})})}).catch((M)=>{if(W)return;let _=I(()=>a1(M));if(_)I(()=>u7(_)),_0=j0(_);else _0=j0(PZ({kind:"runtime-init",source:"pie-assessment-toolkit",error:M,cohort:q}))}),()=>{W=!0}}),y(()=>{OZ(),I(()=>{l7(),s7()})}),y(()=>{if(!F(f))return;let W=F(f),q=(M)=>{if(!j1(M,Y,N6))return!1;return M.stopPropagation(),!0},w=w6(W,[{name:a0,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.element||!_?.itemId)return;let l=X.register(_);if(L0.set(_.element,_),v(G0,!0),t7(_),M6(_.element),X.handleContentRegistered(_),l)F5()}},{name:m1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.itemId)return;let l=_?.element?X.unregister(_.element):!1;if(z5(_.element),D5(_.element),_.element)L0.delete(_.element);if(X.handleContentUnregistered(_),l)F5()}},{name:u1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.itemId)return;let l=X.updateItemSession(_.itemId,_.session);P6({itemId:_.itemId,canonicalItemId:X.getCanonicalItemId(_.itemId),result:l,fallbackSession:_.session})}},{name:p1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.itemId)return;X.handleContentLoaded({itemId:_.itemId,canonicalItemId:_.canonicalItemId,contentKind:_.contentKind,detail:_.detail,timestamp:Date.now()})}},{name:g1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.itemId)return;X.handleItemPlayerError({itemId:_.itemId,canonicalItemId:_.canonicalItemId,contentKind:_.contentKind,error:_.error,timestamp:Date.now()})}},{name:c1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.itemId)return;if(_.action!=="check"&&_.action!=="retry")return;X.handleFormativeAction({itemId:_.itemId,canonicalItemId:_.canonicalItemId,action:_.action,outcomes:_.outcomes})}},{name:d1,handler:(M)=>{if(!q(M))return;let _=wZ(M);if(!_?.renderableId)return;if(_.action!=="attach"&&_.action!=="detach")return;X.handleMediaTimeSource({renderableId:_.renderableId,action:_.action,source:_.source,origin:_.origin})}}]);return()=>{I(()=>P1(W,{reason:"teardown",logger:J})),w();for(let M of[...M0.keys()])D5(M)}}),y(()=>{if(!F(f))return;return()=>{pZ?.disconnect(),pZ=null,uZ?.disconnect(),uZ=null}}),y(()=>{let W=F(f),q=F(_6);if(!W||!q)return;I(()=>{if(pZ){pZ.setValue(q);return}pZ=new L1(W,{context:J5,initialValue:q}),pZ.connect()})}),y(()=>{let W=F(f),q=F(H6);if(!W||!q)return;I(()=>{if(uZ){uZ.setValue(q);return}uZ=new L1(W,{context:I1,initialValue:q}),uZ.connect()})});async function R6(){if(!F(E))throw Error("Coordinator not initialized");await F(E).waitUntilReady()}function C6(W){if(!F(E))throw Error("Coordinator not initialized");F(E).setHooks(W)}function b6(W){return X.navigateToItem(W)}function E6(){return X.getCompositionModel()}function S6(){return F(gZ)}async function y6(){await X.persist()}async function T6(){await X.hydrate()}y(()=>{let W=F(E);if(!W)return;let q=F(A0)>0||F(Y5)!==null,H=!F(K5)&&F(G0);if(!q&&!H)return;I(()=>{if(W===y7)return;y7=W,W.waitUntilReady().catch(()=>{})})}),y(()=>{return()=>{O0.cancel(),X.dispose().catch((W)=>{PZ({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).then(()=>P0()).catch(N0).finally(()=>{G.dispose()})}});var x6={waitUntilReady:R6,setHooks:C6,navigateToItem:b6,getCompositionModel:E6,getItemPlayerConfig:S6,persist:y6,hydrate:T6,get assessmentId(){return K()},set assessmentId(W){K(W),x()},get section(){return U()},set section(W){U(W),x()},get sectionId(){return $()},set sectionId(W){$(W),x()},get attemptId(){return z()},set attemptId(W){z(W),x()},get env(){return D()},set env(W){D(W),x()},get ndsIcons(){return L()},set ndsIcons(W){L(W),x()},get locale(){return P()},set locale(W){P(W),x()},get contentLanguage(){return A()},set contentLanguage(W){A(W),x()},get lazyInit(){return N()},set lazyInit(W){N(W),x()},get toolConfigStrictness(){return O()},set toolConfigStrictness(W){O(W),x()},get tools(){return S()},set tools(W){S(W),x()},get toolContextResolvers(){return C()},set toolContextResolvers(W){C(W),x()},get enabledTools(){return h()},set enabledTools(W){h(W),x()},get toolRegistry(){return b()},set toolRegistry(W){b(W),x()},get accessibility(){return d()},set accessibility(W){d(W),x()},get player(){return VZ()},set player(W){VZ(W),x()},get playerType(){return r()},set playerType(W){r(W),x()},get coordinator(){return s()},set coordinator(W){s(W),x()},get createSectionController(){return AZ()},set createSectionController(W){AZ(W),x()},get onFrameworkError(){return HZ()},set onFrameworkError(W){HZ(W),x()},get errorRenderer(){return _Z()},set errorRenderer(W){_Z(W),x()},get assessment(){return D0()},set assessment(W){D0(W),x()},get isolation(){return qZ()},set isolation(W){qZ(W),x()},get session(){return OZ()},set session(W){OZ(W),x()}},e7=l2(),Z8=M7(e7);k1(Z8,(W)=>v(Q0,W),()=>F(Q0));var k6=e0(Z8,2);{var f6=(W)=>{var q=d2(),H=b1(q),w=t0(H,!0),M=e0(H,2),_=t0(M,!0),l=e0(M,2),C0=t0(l,!0);N1(q),E1((H5)=>{Q5(w,F(X5)),Q5(_,F(JZ).message),Q5(C0,H5)},[()=>F(G5).join(`
225
- `)]),Z5(W,q)},I6=(W)=>{var q=S1(),H=M7(q);T1(H,Q,"default",{},null),Z5(W,q)};y1(k6,(W)=>{if(F(JZ)&&!F(JZ).recoverable)W(f6);else W(I6,-1)})}return Z5(Z,e7),R1(x6)}x2("pie-assessment-toolkit",f1(l1,{assessmentId:{attribute:"assessment-id",type:"String"},section:{attribute:"section",type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},env:{attribute:"env",type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},contentLanguage:{attribute:"content-language",type:"String"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},assessment:{type:"Object"},isolation:{attribute:"isolation",type:"String"},session:{type:"Object"}},["default"],["waitUntilReady","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"},k2));export{l1 as default};
223
+ `}return Y}function z1(Z){let{request:Q,tools:J,pnpPolicy:Y,customSources:X,contextId:G}=Z,j=new R7(G);j.addSource("host",{id:Q.scope.scopeId,name:`${Q.level}:${Q.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let B=_0(J.placement[Q.level]),V=_0(J.policy.allowed),q=new Set(_0(J.policy.blocked)),U=[];for(let D of B)U.push(D),j.addDecision({precedence:0,rule:"placement-membership",featureId:D,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Q.level}`});if(U=U.filter((D)=>{if(J.providers?.[D]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:D,action:"block",sourceType:"host",reason:`tools.providers.${D}.enabled === false`,value:!1}),!1;return!0}),V.length>0){let D=new Set(V);U=U.filter((N)=>{if(!D.has(N))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:N,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:V}),!1;return!0})}U=U.filter((D)=>{if(q.has(D))return j.addDecision({precedence:0,rule:"host-blocked",featureId:D,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let $=[],z=new Set(U),A=null;if(Y.enforcement==="on"&&Y.source&&(Y.assessment||Y.item)){if(A=Y.source.apply({assessment:Y.assessment,item:Y.item}),A.sources.assessment)j.addSource("assessment",A.sources.assessment);if(A.sources.student)j.addSource("student",A.sources.student);if(A.sources.item)j.addSource("item",A.sources.item);for(let M of A.decisions)j.addDecision({precedence:M.precedence,rule:M.rule,featureId:M.featureId,action:M.action,sourceType:M.sourceType,reason:M.reason,value:M.value});for(let[M,C]of A.blockedOverrides)$.push(b7(M,C,Q.level));for(let[M,C]of A.supportConflicts){if(!z.has(M))continue;$.push(_Z(M,C.support,C.grant??"placement",Q.level))}let{blockedToolIds:D}=A;U=U.filter((M)=>!D.has(M));let N=new Set(Object.values(J.placement).flatMap(_0));for(let[M,C]of A.mandates){if(z.has(M))continue;if(!B.includes(M)&&N.has(M))continue;let E=I2(M,{placedAtAnyLevel:N,allTools:J.placement,allowed:V,blocked:q,providers:J.providers}),v={rule:C,hostRule:E.hostRule,hostValue:E.hostValue};$.push({code:"tool-policy.requiredToolBlocked",level:Q.level,toolId:M,message:E.hostRule==="placement-missing"?`Profile policy mandates "${M}" (${C}), but no level of tools.placement lists it.`:`Profile policy mandates "${M}" (${C}), but host policy removes it via ${E.hostRule}.`,details:v}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:M,action:"advisory",sourceType:"host",reason:`Host removed required tool "${M}" via ${E.hostRule}`,value:v})}}for(let D=0;D<X.length;D++){let N=X[D],M=U.slice(),C=N.refine({request:Q,candidates:M}),E=new Set(C.refinedCandidates);for(let S of C.refinedCandidates)if(!M.includes(S))$.push({code:"tool-policy.placementMissing",level:Q.level,toolId:S,message:`Custom source "${N.id}" tried to add tool "${S}" that was not in candidates; ignored.`,details:{customSourceId:N.id}}),E.delete(S);U=M.filter((S)=>E.has(S));let v=new Set;if(C.decisions){for(let S of C.decisions)if(j.addDecision({precedence:S.precedence??100+D,rule:S.rule,featureId:S.featureId,action:S.action,sourceType:S.sourceType,reason:S.reason,value:S.value}),S.action==="block")v.add(S.featureId)}for(let S of M){if(E.has(S))continue;if(v.has(S))continue;j.addDecision({precedence:100+D,rule:"custom-source",featureId:S,action:"block",sourceType:"custom",reason:`Custom policy source "${N.id}" removed tool "${S}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:N.id}})}}for(let D of U)for(let N of Z.unappliedItems??[]){let M=["restrictedTools","requiredTools"].filter((E)=>N.settings[E]?.includes(D)===!0);if(M.length===0)continue;let C={itemId:N.id,settings:M,toolbarLevel:Q.scope.level};$.push({code:"tool-policy.itemSettingNotApplied",level:Q.level,toolId:D,message:`Item "${N.id}" names "${D}" in ${M.join(" and ")}, but "${D}" is on the ${Q.scope.level}-level toolbar, which item settings do not reach. Place "${D}" at item level to enforce the setting per item.`,details:C})}let O=new Set(U),P=U.map((D)=>{let N=A?.perToolFlags.get(D);return{toolId:D,required:N?.required??!1,alwaysAvailable:N?.alwaysAvailable??!1,activateAtInit:N?.activateAtInit??!1,parameters:tZ(D,Y.assessment,Y.item)}});return j.reconcileFinalStates(O),{visibleTools:P,diagnostics:$,provenance:j.build()}}function I2(Z,Q){if(!Q.placedAtAnyLevel.has(Z))return{hostRule:"placement-missing",hostValue:Q.allTools};if(Q.providers?.[Z]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Q.allowed.length>0&&!Q.allowed.includes(Z))return{hostRule:"host-allowlist",hostValue:Q.allowed};if(Q.blocked.has(Z))return{hostRule:"host-blocked",hostValue:Array.from(Q.blocked)};return{hostRule:"placement-missing",hostValue:Q.allTools}}var C7={"district-block":"settings.districtPolicy.blockedTools","test-admin-override":"settings.testAdministration.toolOverrides","item-restriction":"item settings.restrictedTools","pnp-prohibited":"personalNeedsProfile.prohibitedSupports","support-conflict":"a withholding support in personalNeedsProfile.supports","item-requirement":"item settings.requiredTools","district-requirement":"settings.districtPolicy.requiredTools","pnp-support":"personalNeedsProfile.supports","pnp-activate-at-init":"personalNeedsProfile.activateAtInit"};function b7(Z,Q,J){return{code:"tool-policy.overrideBlocked",...J?{level:J}:{},toolId:Z,message:`settings.testAdministration.toolOverrides grants "${Z}", but ${C7[Q]} withdraws it and outranks a granting override.`,details:{rule:Q}}}function _Z(Z,Q,J,Y){let X=J==="placement"?"tools.placement":J==="attribute"?"The item player's attribute":J==="authored"?"The item's authored content":C7[J];return{code:"tool-policy.supportConflict",...Y?{level:Y}:{},toolId:Z,message:`${X} serves "${Z}", but the student's "${Q}" support withholds it.`,details:{support:Q,servedBy:J}}}function A1(Z,Q){let J=Q.map((Y)=>C7[Y]).join(", ");return{code:"tool-policy.unknownSupportId",toolId:Z,message:`No tool is registered under "${Z}", named in ${J}, so it matches nothing. These lists name tools by tool id.`,details:{origins:[...Q]}}}var v2=(Z)=>`No assessment is bound, so no policy source could grant "${Z}"`;function E7(Z,Q,J,Y){return{featureId:Z,granted:!1,action:"block",rule:Q,precedence:0,sourceType:"host",reason:Q==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${J.join(", ")})`,required:!1,assessmentBound:Y.assessmentBound,diagnostics:[]}}function H1(Z,Q,J,Y){let X=Q.decisions[0],G=Array.from(Q.perToolFlags.values())[0],j=X?.action==="enable",B=X?.reason??`Feature "${Z}" not configured`,V=X!==void 0&&X.action!=="skip",q=Q.supportConflicts.get(Z);return{featureId:Z,granted:j,action:X?.action??"skip",rule:V?X.rule:"none",precedence:V?X.precedence:null,sourceType:X?.sourceType??"system",reason:J.assessmentBound||j?B:v2(Z),required:Boolean(G?.required),parameters:Y,...V&&X.rule==="support-conflict"&&q?{withheldBy:q.support}:{},assessmentBound:J.assessmentBound,diagnostics:[...Array.from(Q.blockedOverrides,([U,$])=>b7(U,$)),...Array.from(Q.supportConflicts).flatMap(([U,{support:$,grant:z}])=>z?[_Z(U,$,z)]:[])]}}var m0=(Z)=>Array.isArray(Z)&&Z.length>0;function h2(Z){if(!Z)return!1;let Q=Z.personalNeedsProfile;if(Q&&(m0(Q.supports)||m0(Q.prohibitedSupports)||m0(Q.activateAtInit)))return!0;let J=Z.settings;if(J){let Y=J.districtPolicy;if(Y&&(m0(Y.blockedTools)||m0(Y.requiredTools)))return!0;let X=J.testAdministration?.toolOverrides;if(X&&typeof X==="object"&&Object.keys(X).length>0)return!0}return!1}function m2(Z){if(!Z)return!1;return m0(Z.requiredTools)||m0(Z.restrictedTools)}function D1(Z){if(h2(Z.assessment))return"on";if(m2(Z.itemSettings))return"on";return"off"}class eZ{id="pnp";toolRegistry;supportConflicts;withheldBy=new Map;registrylessIds=new Set;constructor(Z,Q=[]){this.toolRegistry=Z,this.supportConflicts=Q;for(let{support:J,withholds:Y}of Q){this.registrylessIds.add(J);for(let X of Y){this.registrylessIds.add(X);let G=this.withheldBy.get(X)??[];G.push(J),this.withheldBy.set(X,G)}}}apply(Z){let{ctx:Q,result:J}=this.prepare(Z),{pnp:Y,districtPolicy:X,testAdmin:G,itemSettings:j}=Q,B=new Set;Y?.supports?.forEach((V)=>B.add(V)),Y?.prohibitedSupports?.forEach((V)=>B.add(V)),Y?.activateAtInit?.forEach((V)=>B.add(V)),X?.blockedTools?.forEach((V)=>B.add(V)),X?.requiredTools?.forEach((V)=>B.add(V));for(let V of Object.keys(G?.toolOverrides??{}))B.add(V);j?.requiredTools?.forEach((V)=>B.add(V)),j?.restrictedTools?.forEach((V)=>B.add(V));for(let{support:V,withholds:q}of this.supportConflicts)if(this.supportInEffect(V,Q))q.forEach((U)=>B.add(U));for(let V of B)this.resolveSupport(V,Q,J);return J}resolveFeature(Z,Q){let{ctx:J,result:Y}=this.prepare(Q);return this.resolveSupport(Z,J,Y),Y}prepare(Z){let{assessment:Q,item:J}=Z,Y=Q?.personalNeedsProfile,X=Q?.settings,G=J?.settings,j=S7();if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Q?.id||"unknown",name:Q?.name||Q?.id||"Assessment",config:X};if(Y)j.sources.student={id:"student",name:"Student PNP Profile",config:Y};if(J)j.sources.item={id:J.id,name:J.id,config:J.settings};return{ctx:{pnp:Y,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:G},result:j}}supportInEffect(Z,Q){let J=S7();return this.resolveSupport(Z,Q,J,!1),J.decisions[0]?.action==="enable"}resolveSupport(Z,Q,J,Y=!0){if(Q.districtPolicy?.blockedTools?.includes(Z)){J.blockedToolIds.add(Z),J.decisions.push({precedence:1,rule:"district-block",featureId:Z,action:"block",sourceType:"assessment",reason:`District policy blocks "${Z}" for all assessments`,value:Q.districtPolicy.blockedTools});return}let X=Q.testAdmin?.toolOverrides?.[Z];if(X===!1){J.blockedToolIds.add(Z),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:Z,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(Q.itemSettings?.restrictedTools?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"item-restriction");J.decisions.push({precedence:3,rule:"item-restriction",featureId:Z,action:"block",sourceType:"item",reason:`Item restricts "${Z}" (e.g., mental math question blocks calculator)`,value:Q.itemSettings.restrictedTools});return}if(Q.pnp?.prohibitedSupports?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"pnp-prohibited");J.decisions.push({precedence:4,rule:"pnp-prohibited",featureId:Z,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Z}"`,value:Q.pnp.prohibitedSupports});return}let G=Y?this.withheldBy.get(Z)?.find((V)=>this.supportInEffect(V,Q)):void 0;if(G){let V=S7();this.resolveSupport(Z,Q,V,!1);let q=V.decisions[0];J.blockedToolIds.add(Z),J.supportConflicts.set(Z,{support:G,...q?.action==="enable"?{grant:q.rule}:{}}),J.decisions.push({precedence:4,rule:"support-conflict",featureId:Z,action:"block",sourceType:"student",reason:`"${Z}" is withheld while the student's "${G}" support is in effect`,value:{support:G}});return}let j=Q.pnp?.activateAtInit?.includes(Z)===!0,B=Q.itemSettings?.requiredTools?.includes(Z)?"item-requirement":Q.districtPolicy?.requiredTools?.includes(Z)?"district-requirement":void 0;if(X===!0){if(B)J.mandates.set(Z,B);J.perToolFlags.set(Z,{required:B!==void 0,alwaysAvailable:!0,activateAtInit:j,rule:"test-admin-override"}),J.decisions.push({precedence:5,rule:"test-admin-override",featureId:Z,action:"enable",sourceType:"assessment",reason:`Test administrator enabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(B==="item-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"item-requirement"}),J.decisions.push({precedence:6,rule:"item-requirement",featureId:Z,action:"enable",sourceType:"item",reason:`Item requires "${Z}" for this question`,value:Q.itemSettings?.requiredTools});return}if(B==="district-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"district-requirement"}),J.decisions.push({precedence:7,rule:"district-requirement",featureId:Z,action:"enable",sourceType:"assessment",reason:`District policy requires "${Z}" for all assessments`,value:Q.districtPolicy?.requiredTools});return}if(j){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:j,rule:"pnp-activate-at-init"}),J.decisions.push({precedence:8,rule:"pnp-activate-at-init",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile turns on "${Z}" at start`,value:Q.pnp?.activateAtInit});return}if(Q.pnp?.supports?.includes(Z)){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:!1,rule:"pnp-support"}),J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Z}"`,value:Q.pnp.supports});return}J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"skip",sourceType:"system",reason:`Feature "${Z}" not configured at any level`,value:{supportId:Z}})}unknownSupportIds(Z,Q){let J=new Map;if(this.toolRegistry.getAllTools().length===0)return J;let Y=Z?.personalNeedsProfile,X=Z?.settings,G=[["district-block",X?.districtPolicy?.blockedTools],["test-admin-override",Object.keys(X?.testAdministration?.toolOverrides??{})],["item-restriction",Q.flatMap((j)=>j.restrictedTools??[])],["pnp-prohibited",Y?.prohibitedSupports],["item-requirement",Q.flatMap((j)=>j.requiredTools??[])],["district-requirement",X?.districtPolicy?.requiredTools],["pnp-activate-at-init",Y?.activateAtInit],["pnp-support",Y?.supports]];for(let[j,B]of G)for(let V of B??[]){if(this.toolRegistry.has(V)||this.registrylessIds.has(V))continue;let q=J.get(V)??[];if(!q.includes(j))q.push(j);J.set(V,q)}return J}}function S7(){return{blockedToolIds:new Set,mandates:new Map,perToolFlags:new Map,decisions:[],blockedOverrides:new Map,supportConflicts:new Map,sources:{}}}var _1=n0({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class Z5{toolRegistry;unsubscribeRegistry;contextId;assessmentOptional;pnpPolicySource;supportConflicts;customSources;listeners=new Set;tools;assessment;pnpEnforcementOverride;itemSettings=new Map;inputDiagnostics=Object.freeze([]);disposed=!1;constructor(Z){this.toolRegistry=Z.toolRegistry,this.contextId=Z.contextId??"tool-policy",this.assessmentOptional=Z.assessmentOptional===!0,this.supportConflicts=Z.supportConflicts??[],this.pnpPolicySource=new eZ(this.toolRegistry,this.supportConflicts),this.customSources=Z.customSources?[...Z.customSources]:[];let Q=Z.inputs??{};this.tools=Q.tools??_1,this.assessment=Q.assessment??null,this.pnpEnforcementOverride=Q.pnpEnforcement??null,this.refreshInputDiagnostics(),this.unsubscribeRegistry=this.watchRegistry()}decide(Z){this.assertNotDisposed();let Q=Z.scope.scopeId?`${this.contextId}:${Z.level}:${Z.scope.scopeId}`:`${this.contextId}:${Z.level}`,J=Z.level==="item"?this.itemForScope(Z.scope):void 0,Y=Z.level!=="item"||Z.scope.level==="section"||Z.scope.level==="assessment";return z1({request:Z,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,item:J,enforcement:this.enforcementFor(J)},unappliedItems:Y?this.enforcedItems():void 0,customSources:this.customSources,contextId:Q})}grantsFeatureAnywhere(Z,Q={}){let J=(Y)=>!Q.enforced||this.enforcementFor(Y)==="on";if(J()&&this.decideFeature(Z).granted)return!0;for(let Y of this.itemSettings.keys()){let X=this.itemSettingsFor(Y);if(!J(X?{id:Y,settings:X}:void 0))continue;if(this.decideFeature(Z,{level:"item",scopeId:Y}).granted)return!0}return!1}registerItemSettings(Z,Q){this.assertNotDisposed();let J={settings:Q},Y=this.itemSettingsFor(Z),X=this.itemSettings.get(Z)??[];return X.push(J),this.itemSettings.set(Z,X),this.emitIfItemSettingsChanged(Z,Y),()=>{if(this.disposed)return;let G=this.itemSettings.get(Z),j=G?.indexOf(J)??-1;if(!G||j<0)return;let B=this.itemSettingsFor(Z);if(G.splice(j,1),G.length===0)this.itemSettings.delete(Z);this.emitIfItemSettingsChanged(Z,B)}}decideFeature(Z,Q){this.assertNotDisposed();let J=this.hostFeatureGate(Z);if(J)return J;let Y=this.itemForScope(Q);return H1(Z,this.pnpPolicySource.resolveFeature(Z,{assessment:this.assessment??void 0,item:Y}),{assessmentBound:this.assessment!==null},tZ(Z,this.assessment,Y))}hostFeatureGate(Z){let Q={assessmentBound:this.assessment!==null},J=_0(this.tools.policy.blocked);if(J.includes(Z))return E7(Z,"host-blocked",J,Q);let Y=_0(this.tools.policy.allowed);if(Y.length>0&&!Y.includes(Z))return E7(Z,"host-allowlist",Y,Q);return null}getVisibleToolIds(Z,Q){return this.decide({level:Z,scope:{level:Z,scopeId:Q}}).visibleTools.map((J)=>J.toolId)}updateInputs(Z){this.assertNotDisposed();let Q=!1,J=!1;if("tools"in Z){let Y=Z.tools??_1;if(!Object.is(this.tools,Y))this.tools=Y,Q=!0}if("assessment"in Z){let Y=Z.assessment??null,X=!u0(this.assessment,Y);if(this.assessment=Y,X)Q=!0,this.refreshInputDiagnostics()}if("pnpEnforcement"in Z){let Y=Z.pnpEnforcement??null;if(this.pnpEnforcementOverride!==Y)this.pnpEnforcementOverride=Y,J=!0}if(Q||J)this.emit({reason:J&&!Q?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(Z,Q){this.assertNotDisposed(),this.unsubscribeRegistry(),this.toolRegistry=Z,this.pnpPolicySource=new eZ(Z,this.supportConflicts),this.unsubscribeRegistry=this.watchRegistry(),this.tools=Q,this.refreshInputDiagnostics(),this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Z){return this.assertNotDisposed(),this.customSources.push(Z),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Q=this.customSources.indexOf(Z);if(Q===-1)return;if(this.customSources.splice(Q,1),this.disposed)return;this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}onPolicyChange(Z){return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeRegistry(),this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.itemSettings.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,pnpEnforcement:this.enforcementFor(),pnpEnforcementOverride:this.pnpEnforcementOverride,assessmentExpected:!this.assessmentOptional||this.pnpEnforcementOverride==="on",diagnostics:this.inputDiagnostics})}enforcementFor(Z){return this.pnpEnforcementOverride??D1({assessment:this.assessment,itemSettings:Z?.settings})}itemSettingsFor(Z){return this.itemSettings.get(Z)?.at(-1)?.settings}emitIfItemSettingsChanged(Z,Q){if(u0(Q,this.itemSettingsFor(Z)))return;this.refreshInputDiagnostics(),this.emit({reason:"item-settings",inputs:this.snapshotInputs()})}refreshInputDiagnostics(){let Z=[];for(let J of this.itemSettings.keys()){let Y=this.itemSettingsFor(J);if(Y)Z.push(Y)}let Q=Array.from(this.pnpPolicySource.unknownSupportIds(this.assessment,Z),([J,Y])=>A1(J,Y));if(u0(this.inputDiagnostics,Q))return!1;return this.inputDiagnostics=Object.freeze(Q),!0}watchRegistry(){return this.toolRegistry.onRegistryChange(()=>{if(this.disposed)return;if(this.refreshInputDiagnostics())this.emit({reason:"inputs",inputs:this.snapshotInputs()})})}itemForScope(Z){if(Z?.level!=="item")return;let Q=Z.canonicalItemId||Z.itemId||Z.scopeId,J=Q?this.itemSettingsFor(Q):void 0;return J?{id:Q,settings:J}:void 0}enforcedItems(){let Z=[];for(let Q of this.itemSettings.keys()){let J=this.itemSettingsFor(Q);if(!J)continue;let Y={id:Q,settings:J};if(this.enforcementFor(Y)==="on")Z.push(Y)}return Z}emit(Z){for(let Q of Array.from(this.listeners))try{Q(Z)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}import{hasResponseField as u2,hasResponseValue as M1}from"@pie-players/pie-players-shared/pie";import{isPlainRecord as XZ}from"@pie-players/pie-players-shared/object";function Q5(Z){return XZ(Z)&&XZ(Z.session)?Z.session:Z}function p2(Z,Q){let J=XZ(Z)?Z:{},Y=XZ(Q)?Q:{},X=new Set([...Object.keys(J),...Object.keys(Y)]);for(let G of X)if(!u0(Q5(J[G]),Q5(Y[G])))return!1;return!0}function g2(Z,Q){for(let[J,Y]of Object.entries(Z)){if(Y===void 0)continue;if(J==="itemSessions"){if(!p2(Y,Q.itemSessions))return!1;continue}if(!u0(Y,Q[J]))return!1}return!0}function J5(Z,Q){if(!Z)return Q;let J=XZ(Q.itemSessions)?{...Q.itemSessions}:{},Y=XZ(Z.itemSessions)?Z.itemSessions:{};for(let[G,j]of Object.entries(Y)){if(!M1(Q5(j)))continue;let B=Q5(J[G]);if(M1(B)||u2(B))continue;J[G]=j}let X={...Q,itemSessions:J};return g2(X,Z)?null:X}var O1=[{support:"screenReader",withholds:["textToSpeech","autoplayAudio"]}];class n extends Error{constructor(){super("ToolkitCoordinator has been disposed.");this.name="ToolkitCoordinatorDisposedError"}}class Y5 extends Error{constructor(){super("Section controller acquisition was retired during initialization.");this.name="SectionControllerRetiredError"}}var c2=(Z,Q,J)=>{let Y={...Q,...J},X=$1(Z,Q,J);if(X)Y.mathSpeech=X;return Y},d2={"tool-module-load":"failed to load","tool-request-open":"failed to open on request","tool-request-host-check":"failed its toolbar's host check","tool-visibility":"failed its relevance check","tool-applicability":"failed its applicability check","tool-state-load":"failed to restore its state","tool-state-save":"failed to save its state","tool-playback":"failed during playback"},i2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],l2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error","timed-media-cue-changed","timed-media-policy-degraded","timed-media-invalid"];class T7{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;tts;stateLoadSettled=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;degradedTools=new Map;reportedToolFailures=new Set;readyChangeListeners=new Set;eagerInit;toolRegistry;toolRegistrySupplied;toolRegistrySettled;toolRegistryAbsent=!1;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;toolRequests=new w7((Z,Q,J)=>this.reportToolFailure(Z,Q,J));sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitEntries=new Map;sectionControllerDisposePromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;ownedToolCoordinator;frameworkErrorHookUnsubscribe=null;disposePromise=null;policyEngine;reportedPolicyDiagnostics=new Map;policyDiagnosticListeners=new Set;reportedUnboundFeaturePolicy=!1;reportedRegistryUnavailable=!1;resolveConfig(Z){let Q=C5(Z.toolConfigStrictness),J=Z.toolRegistry??new y7,Y=Z.deferToolConfigValidation===!0?n0(Z.tools):this.validateToolsConfig(Z.tools,{strictness:Q,source:"ToolkitCoordinator.init",toolRegistry:J}),X={...F1};return{...Z,toolConfigStrictness:Q,toolRegistry:J,tools:{...Y,providers:{...X,...Y.providers}},accessibility:{language:"en-US",...Z.accessibility??{},catalogs:Z.accessibility?.catalogs??[]}}}validateToolsConfig(Z,Q){let{config:J,diagnostics:Y}=b5(Z,Q.toolRegistry),X=this.reportedRegistryUnavailable||this.toolRegistryPending()?Y.filter((G)=>G.code!=="tools.registryUnavailable"):Y;if(E5(X,Q),Q.strictness!=="off"&&X.some((G)=>G.code==="tools.registryUnavailable"))this.reportedRegistryUnavailable=!0;return J}constructor(Z){if(!Z.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=Z.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let Q=this.resolveConfig(Z);if(this.assessmentId=Q.assessmentId,this.config=Q,this.toolRegistry=Q.toolRegistry??new y7,this.installToolContextResolvers(Q.toolContextResolvers),this.hooks={...Q.hooks},this.lazyInit=Z.lazyInit===!0,this.eagerInit=Z.eagerInit??!this.lazyInit,this.frameworkErrorBus=Z.frameworkErrorBus??new UZ,this.ownsFrameworkErrorBus=!Z.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.ownedToolCoordinator=new L1,this.toolCoordinator=this.ownedToolCoordinator,this.highlightCoordinator=new HZ,this.elementToolStateStore=new m5,this.catalogResolver=new v5(Q.accessibility?.catalogs||[],Q.accessibility?.language||"en-US"),this.toolProviderRegistry=new aZ,this._registerToolProviders(),this.ttsService=new _7,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.ttsService.setReadinessGate(()=>this.ensureTTSReady()),this.tts=new N7({assertNotDisposed:()=>this.assertNotDisposed(),isDisposalStarted:()=>this.disposePromise!==null,isDisposalError:(J)=>J instanceof n,emitTelemetry:(J,Y)=>this.emitTelemetry(J,Y),hooks:this.hooks,toolProviderRegistry:this.toolProviderRegistry,initializeProvider:(J,Y)=>this.initializeProvider(J,Y),ttsService:this.ttsService,catalogResolver:this.catalogResolver,clearDegradedTool:(J)=>void this.degradedTools.delete(J),reportStartFailure:(J,Y,X)=>this.reportStartFailure(J,Y,X),isToolGranted:(J)=>this.isToolGranted(J),lazyInit:this.lazyInit,isToolRegistryPending:()=>this.toolRegistryPending(),providersConfig:()=>this.config.tools?.providers,getProviderDescriptorTools:()=>this.getProviderDescriptorTools(),registerProviderFromTool:(J,Y)=>this.registerProviderFromTool(J,Y),notifyReadyChange:()=>this.notifyReadyChange()}),this.ttsService.setMathSpeechSource(()=>this.tts.mathSpeechRuntimeOptions()),this.setupStatePersistenceHooks(),this.policyEngine=new Z5({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,assessmentOptional:this.config.assessmentOptional===!0,supportConflicts:O1,inputs:{tools:this.config.tools,assessment:null,pnpEnforcement:this.resolveConfiguredPnpEnforcement()}}),this.policyEngine.onPolicyChange((J)=>{if(J.reason==="disposed")return;if(J.reason==="inputs"||J.reason==="pnp-enforcement")this.reportedPolicyDiagnostics.clear();this.warnPolicyDiagnostics(J.inputs.diagnostics),this.reportNewlyGrantedFailures()}),this.eagerInit)this.waitUntilReady().catch((J)=>{if(J instanceof n)return;console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready",recoverable:!1})})}assertNotDisposed(){if(this.disposePromise!==null)throw new n}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors((Z)=>{let Q=this.hooks.onFrameworkError;if(!Q)return;try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Z,Q){try{await this.hooks.onTelemetry?.(Z,Q)}catch(Y){console.warn("[ToolkitCoordinator] telemetry hook failed:",Y)}let J=Q?{...Q}:void 0;for(let Y of this.telemetryListeners)try{Y({eventName:Z,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Z){for(let Q of this.sectionControllerLifecycleListeners)try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Z,Q,J){let Y=T8({error:Z,context:Q,recoverable:Q.recoverable,scope:J?"cohort":"runtime",cohort:J});this.frameworkErrorBus.reportFrameworkError(Y)}isToolGranted(Z){try{return this.policyEngine.grantsFeatureAnywhere(Z,{enforced:this.toolRegistry.getToolActivation(Z)!=="region"})}catch{return!1}}reportStartFailure(Z,Q,J,Y=!1){let X=Array.from(J),G=Y||!X.some((j)=>this.isToolGranted(j));if(G&&!Y)for(let j of X)this.degradedTools.set(j,{error:Z,context:Q});this.handleError(Z,{...Q,recoverable:G})}reportToolFailure(Z,Q,J){if(Q==="tool-module-load")this.toolRequests.notifyTargetsChange();let Y=`${Q}\x00${Z}`;if(this.reportedToolFailures.has(Y))return;this.reportedToolFailures.add(Y);let X=J instanceof Error&&J.message.trim().length>0?J.message:String(J),G=()=>this.reportStartFailure(Error(`Tool "${Z}" ${d2[Q]}: ${X}`,{cause:J}),{phase:Q,details:{toolId:Z}},[Z],Q!=="tool-module-load");if(Q==="tool-module-load")G();else queueMicrotask(G)}reportNewlyGrantedFailures(){for(let[Z,Q]of this.degradedTools){if(!this.isToolGranted(Z))continue;this.degradedTools.delete(Z),this.handleError(Q.error,{...Q.context,recoverable:!1})}}onReadyChange(Z){return this.readyChangeListeners.add(Z),()=>{this.readyChangeListeners.delete(Z)}}notifyReadyChange(){for(let Z of this.readyChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] ready-change listener failed:",Q)}}subscribeFrameworkErrors(Z){return this.frameworkErrorBus.subscribeFrameworkErrors(Z)}reportFrameworkError(Z){this.frameworkErrorBus.reportFrameworkError(Z)}sectionControllerKey(Z){return{assessmentId:this.assessmentId,sectionId:Z.sectionId,attemptId:Z.attemptId}}getSectionControllerMapKey(Z){return`${Z.assessmentId}::${Z.sectionId}::${Z.attemptId||""}`}createDefaultSectionPersistence(){let Z=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Q=(J)=>{let{assessmentId:Y,sectionId:X,attemptId:G}=J.key;if(!G)return null;return`pie:section-controller:v1:${Y}:${X}:${G}`};return{async loadSession(J){let Y=Q(J);if(!Z||!Y)return null;let X=Z.getItem(Y);if(!X)return null;try{return JSON.parse(X)}catch{return null}},async saveSession(J,Y){let X=Q(J);if(!Z||!X)return;Z.setItem(X,JSON.stringify(Y))},async clearSession(J){let Y=Q(J);if(!Z||!Y)return;Z.removeItem(Y)}}}async resolveSectionPersistence(Z){let Q=this.getSectionControllerMapKey(Z.key),J=this.sectionPersistenceStrategies.get(Q);if(J)return J;let Y={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Z,Y)??await Y.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Q,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Z)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Z)).catch((Q)=>{this.handleError(Q,{phase:"state-save",recoverable:!0})})})}async ensureStateLoaded(){if(this.stateLoadSettled)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Z=this.hooks.loadToolState;if(!Z)return;try{let Q=await Z();if(this.assertNotDisposed(),Q&&typeof Q==="object")this.elementToolStateStore.loadState(Q);this.stateLoadSettled=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Q)})}catch(Q){if(Q instanceof n)throw Q;this.stateLoadSettled=!0,this.handleError(Q,{phase:"state-load",recoverable:!0})}})().finally(()=>{this.stateLoadPromise=void 0,this.notifyReadyChange()}),this.stateLoadPromise}toolRegistryPending(){return!this.toolRegistrySettled&&!this.toolRegistryAbsent}adoptToolRegistry(Z){if(this.disposePromise!==null||this.toolRegistrySettled)return!1;if(!Z&&this.toolRegistryAbsent)return!1;let Q=this.config.toolConfigStrictness??"error",J="ToolkitCoordinator.adoptToolRegistry";if(!Z)return this.toolRegistryAbsent=!0,this.validateToolsConfig(this.config.tools,{strictness:Q,source:J,toolRegistry:this.toolRegistry}),this.tts.reportHeldMissingProvider(),!1;this.toolRegistrySettled=!0,this.toolRegistry=Z,this.config.toolRegistry=Z,this.tts.discardHeldMissingProvider();try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:Q==="off"?"off":"warn",source:J,toolRegistry:Z})}catch(X){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",X)}this.policyEngine.replaceToolRegistry(Z,this.config.tools);let Y=this.tts.isStarted();for(let X of this.getProviderDescriptorTools()){if(Y&&this.tts.ownsTool(X.toolId))continue;this.registerProviderFromTool(X)}if(Y)this.tts.scheduleReconfigure();return!0}_registerToolProviders(){let Z=this.getProviderDescriptorTools();for(let Q of Z)this.registerProviderFromTool(Q)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Z)=>!!Z.provider)}async registerProviderFromTool(Z,Q=!1){let J=Z.provider;if(!J)return;let{toolId:Y}=Z,X;try{let G=this.getToolConfig(Y)||void 0;if(G?.enabled===!1){if(Q)this.toolProviderRegistry.unregister(Y);return}if(!Q&&this.toolProviderRegistry.has(Y))return;let j=J.createProvider(G),B=J.getInitConfig?.(G)??G?.provider?.init??{},V=this.addToolTelemetryReporter(Y,B),q=this.createToolTelemetryForwarder(Y),U=J.getAuthFetcher?.(G)??G?.provider?.runtime?.authFetcher;X={provider:j,config:V,lazy:J.lazy??!0,authFetcher:U,onTelemetry:q}}catch(G){this.reportProviderRegisterFailure(G,Y);return}await this.registerProvider(Y,X)}createToolTelemetryForwarder(Z){return async(Q,J)=>{await this.emitTelemetry(Q,{...J||{},toolId:Z})}}addToolTelemetryReporter(Z,Q){let J=Q&&typeof Q==="object"?{...Q}:{},Y=typeof J.onTelemetry==="function"?J.onTelemetry:null,X=this.createToolTelemetryForwarder(Z);return J.onTelemetry=async(G,j)=>{if(Y)await Y(G,j);await X(G,j)},J}async registerProvider(Z,Q){try{this.toolProviderRegistry.register(Z,Q);let J={providerName:Q.provider.providerName};await this.hooks.onProviderRegistered?.(Z,J),await this.emitTelemetry("pie-toolkit-provider-registered",{toolId:Z,providerName:Q.provider.providerName})}catch(J){this.reportProviderRegisterFailure(J,Z)}}reportProviderRegisterFailure(Z,Q){console.warn(`[ToolkitCoordinator] Failed to register the provider of tool "${Q}":`,Z),this.reportStartFailure(Z,{phase:"provider-register",toolId:Q},[Q])}async ensureProviderReady(Z){return this.initializeProvider(Z,!1)}async initializeProvider(Z,Q){this.assertNotDisposed();let J=this.providerInitPromises.get(Z);if(J)return J;let Y=(async()=>{try{let X=await this.toolProviderRegistry.getProvider(Z,!1);if(this.assertNotDisposed(),this.toolProviderRegistry.isInitialized(Z))return X;let G={providerName:X.providerName};return await this.hooks.onProviderInitStart?.(Z,G),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(Z),this.assertNotDisposed(),X=await this.toolProviderRegistry.getProvider(Z,!1),await this.hooks.onProviderReady?.(Z,G),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{toolId:Z}),this.assertNotDisposed(),X}catch(X){if(X instanceof n)throw X;let G=X instanceof Error?X:Error(String(X));throw this.reportStartFailure(G,{phase:"provider-init",toolId:Z},this.toolRegistry.get(Z)?.provider?[Z]:[],Q),G}})().finally(()=>{this.providerInitPromises.delete(Z)});return this.providerInitPromises.set(Z,Y),Y}setHooks(Z){if(Object.assign(this.hooks,Z),this.setupStatePersistenceHooks(),this.disposePromise===null&&Z.onCoordinatorReady&&this.isReady())Promise.resolve(Z.onCoordinatorReady(this)).catch((Q)=>{this.handleError(Q,{phase:"coordinator-ready",recoverable:!1})})}subscribeTelemetry(Z){return this.telemetryListeners.add(Z),()=>{this.telemetryListeners.delete(Z)}}getSectionController(Z){let Q=this.sectionControllerKey(Z);return this.sectionControllers.get(this.getSectionControllerMapKey(Q))}subscribeSectionEvents(Z){if(this.activeCohortMapKey===null&&this.latestRequestedActiveCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Q=this.activeSubscriptions.get(Z.listener);if(Q)Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J={listener:Z.listener,eventTypes:Z.eventTypes,itemIds:Z.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Z.listener,J);let Y=this.activeCohortMapKey===null?void 0:this.sectionControllers.get(this.activeCohortMapKey);if(Y)this.bindSubscriptionToController(J,Y);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Z.listener)===J)this.activeSubscriptions.delete(Z.listener)}}bindSubscriptionToController(Z,Q){Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null;let J=Q.subscribe;if(typeof J!=="function")return;let Y=this.buildSectionEventPredicate(Z);Z.unsubscribeCurrent=J.call(Q,(j)=>{if(!Y(j))return;this.deliverSectionEventSafely(Z.listener,j)});let X=this.buildContentLoadedReplayEvents(Q);for(let j of X)if(Y(j))this.deliverSectionEventSafely(Z.listener,j);let G=this.buildLoadingCompleteReplayEvent(Q);if(G&&Y(G))this.deliverSectionEventSafely(Z.listener,G)}deliverSectionEventSafely(Z,Q){try{Z(Q)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Z){if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=Z;let Q=this.sectionControllers.get(Z);if(!Q)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Q)}setActiveCohortIfLatestRequest(Z){if(this.latestRequestedActiveCohortMapKey!==Z)return;this.setActiveCohort(Z)}suspendActiveCohortIfSuperseded(Z){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}clearActiveCohortIfMatches(Z){if(this.activeCohortMapKey!==Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}detachActiveSubscriptions(){for(let Z of Array.from(this.activeSubscriptions.values()))Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null}buildSectionEventPredicate(Z){let Q=Z.eventTypes?new Set(Z.eventTypes):null,J=Z.itemIds?new Set(Z.itemIds):null;return(Y)=>{if(Q){let X=Y?.type;if(!X||!Q.has(X))return!1}if(!J)return!0;return Array.from(this.collectEventItemIds(Y)).some((X)=>J.has(X))}}collectEventItemIds(Z){let Q=new Set;if("itemId"in Z&&typeof Z.itemId==="string")Q.add(Z.itemId);if("canonicalItemId"in Z&&typeof Z.canonicalItemId==="string")Q.add(Z.canonicalItemId);if("currentItemId"in Z&&typeof Z.currentItemId==="string")Q.add(Z.currentItemId);if("previousItemId"in Z&&typeof Z.previousItemId==="string")Q.add(Z.previousItemId);return Q}buildContentLoadedReplayEvents(Z){let Q=Z.getRuntimeState?.(),J=Q?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let Y=typeof Q?.currentItemIndex==="number"&&Number.isFinite(Q.currentItemIndex)?Q.currentItemIndex:0,X=Date.now(),G=[];for(let j of J){if(!j)continue;let B=j.itemId,V=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:B;if(typeof B!=="string"||!B)continue;G.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:B,canonicalItemId:V,currentItemIndex:Y,timestamp:X})}return G}buildLoadingCompleteReplayEvent(Z){let Q=Z.getRuntimeState?.();if(Q?.loadingComplete!==!0)return null;let J=typeof Q.totalRegistered==="number"&&Number.isFinite(Q.totalRegistered)?Math.max(0,Q.totalRegistered):0,Y=typeof Q.totalLoaded==="number"&&Number.isFinite(Q.totalLoaded)?Math.max(0,Q.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:Y,currentItemIndex:Q.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||i2,itemIds:Z.itemIds,listener:Z.listener})}subscribeSectionLifecycleEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||l2,listener:Z.listener})}onSectionControllerLifecycle(Z){return this.sectionControllerLifecycleListeners.add(Z),()=>{this.sectionControllerLifecycleListeners.delete(Z)}}async getOrCreateSectionController(Z){if(this.disposePromise!==null)throw new n;let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let Y;try{if(Y=await this.resolveExistingSectionController({mapKey:J,key:Q,input:Z.input,updateExisting:Z.updateExisting}),Y){if(this.disposePromise!==null)throw new n;if(Z.initialSession)await this.assignSessionToPublishedController(Y,Z.initialSession)}}catch(V){throw this.deliverSectionStartError(J,V),V}if(Y)return Y;let X=this.sectionControllerDisposePromises.get(J);if(X)await MZ([X]);if(this.disposePromise!==null)throw new n;let G=this.sectionControllerInitEntries.get(J);if(G){if(!Z.initialSession)return G.promise;let V=await G.promise;return await this.assignSessionToPublishedController(V,Z.initialSession),V}let j={retired:!1,candidateClaimed:!1},B=this.initializeNewSectionController({args:Z,key:Q,mapKey:J,token:j}).catch((V)=>{throw this.handleSectionControllerInitError(V,Z),this.deliverSectionStartError(J,V),V}).finally(()=>{if(this.sectionControllerInitEntries.get(J)?.token===j)this.sectionControllerInitEntries.delete(J)});return this.sectionControllerInitEntries.set(J,{key:Q,token:j,promise:B}),B}async resolveExistingSectionController(Z){let Q=this.sectionControllers.get(Z.mapKey);if(!Q)return;if(this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.updateExisting!==!1)await Q.updateInput?.(Z.input);if(this.sectionControllers.get(Z.mapKey)!==Q)return;return this.setActiveCohortIfLatestRequest(Z.mapKey),Q}createSectionControllerContext(Z){return{key:Z.key,coordinator:this,input:Z.input}}async initializeNewSectionController(Z){let Q=this.createSectionControllerContext({key:Z.key,input:Z.args.input}),J=await this.resolveSectionPersistence(Q);if(this.disposePromise!==null||Z.token.retired){if(this.sectionPersistenceStrategies.get(Z.mapKey)===J)this.sectionPersistenceStrategies.delete(Z.mapKey);throw this.createSectionControllerRetirementError()}let Y={createDefaultController:Z.args.createDefaultController},X=await this.hooks.createSectionController?.(Q,Y)??await Y.createDefaultController(),G={mapKey:Z.mapKey,key:Z.key,controller:X,persistence:J,token:Z.token};try{await this.retireUnpublishedSectionControllerIfNeeded(G),await X.configureSessionPersistence?.({strategy:J,context:Q}),await this.retireUnpublishedSectionControllerIfNeeded(G),await X.initialize?.(Z.args.input),await this.retireUnpublishedSectionControllerIfNeeded(G);let j=Z.args.initialSession;if(j){if(!X.applySession)throw Error("Section controller cannot apply the session it was created with: it has no applySession.");await X.applySession(j,{mode:"replace"})}else await X.hydrate?.();return await this.finalizeSectionControllerReady({...G,context:Q}),X}catch(j){throw await this.cleanupUnpublishedSectionController(G),j}}async assignSessionToPublishedController(Z,Q){if(!Q)return;if(!Z.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");let J=J5(Z.getSession?.()??null,Q);if(!J)return;await Z.applySession(J,{mode:"replace"})}createSectionControllerRetirementError(){return this.disposePromise!==null?new n:new Y5}async retireUnpublishedSectionControllerIfNeeded(Z){if(this.disposePromise===null&&!Z.token.retired)return;throw await this.cleanupUnpublishedSectionController(Z),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(Z){if(Z.token.candidateClaimed)return;Z.token.candidateClaimed=!0;try{await Z.controller.dispose?.()}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.key.sectionId,attemptId:Z.key.attemptId},recoverable:!0})}finally{if(this.sectionPersistenceStrategies.get(Z.mapKey)===Z.persistence)this.sectionPersistenceStrategies.delete(Z.mapKey)}}retirePublishedSectionControllerIfNeeded(Z){if(this.disposePromise!==null&&!Z.token.retired)this.disposeSectionController({sectionId:Z.key.sectionId,attemptId:Z.key.attemptId});if(Z.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(Z){await this.retireUnpublishedSectionControllerIfNeeded(Z),this.sectionControllers.set(Z.mapKey,Z.controller),this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(Z.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Z.key,controller:Z.controller}),await this.hooks.onSectionControllerReady?.(Z.context,Z.controller),this.retirePublishedSectionControllerIfNeeded(Z),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(Z)}handleSectionControllerInitError(Z,Q){if(Z instanceof n||Z instanceof Y5)return;this.handleError(Z,{phase:"section-controller-init",details:{sectionId:Q.sectionId,attemptId:Q.attemptId},recoverable:!1},{sectionId:Q.sectionId,attemptId:Q.attemptId})}deliverSectionStartError(Z,Q){if(Q instanceof n||Q instanceof Y5||this.latestRequestedActiveCohortMapKey!==Z)return;let J={type:"section-error",source:"section-runtime",error:Q,currentItemIndex:0,timestamp:Date.now()};for(let Y of Array.from(this.activeSubscriptions.values()))if(this.buildSectionEventPredicate(Y)(J))this.deliverSectionEventSafely(Y.listener,J)}disposeSectionController(Z){let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q),Y=this.sectionControllerInitEntries.get(J);if(Y)Y.token.retired=!0;let X=this.sectionControllers.get(J);if(!X){let q=this.sectionControllerDisposePromises.get(J);if(q)return q;if(!Y)return Promise.resolve();let U=MZ([Y.promise]).then(()=>{return});return this.trackSectionControllerDisposal(J,U)}let G=this.sectionPersistenceStrategies.get(J);if(this.clearActiveCohortIfMatches(J),this.sectionControllers.get(J)===X)this.sectionControllers.delete(J),this.sectionControllerKeys.delete(J),this.sectionPersistenceStrategies.delete(J),this.emitSectionControllerLifecycle({type:"disposed",key:Q});let j=this.createSectionControllerContext({key:Q,input:void 0}),B=this.disposeSectionControllerEntry({args:Z,key:Q,context:j,controller:X,persistenceStrategy:G}),V=Y?MZ([Y.promise]).then(()=>B):B;return this.trackSectionControllerDisposal(J,V)}trackSectionControllerDisposal(Z,Q){this.sectionControllerDisposePromises.set(Z,Q);let J=()=>{if(this.sectionControllerDisposePromises.get(Z)===Q)this.sectionControllerDisposePromises.delete(Z)};return Q.then(J,J),Q}async disposeSectionControllerEntry(Z){try{await this.runSectionControllerDisposePipeline({key:Z.key,context:Z.context,controller:Z.controller,persistBeforeDispose:Z.args.persistBeforeDispose})}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.args.sectionId,attemptId:Z.args.attemptId},recoverable:!0})}finally{await this.finalizeSectionControllerDispose({context:Z.context,persistenceStrategy:Z.persistenceStrategy,clearPersistence:Z.args.clearPersistence})}}async runSectionControllerDisposePipeline(Z){let Q=[];if(Z.persistBeforeDispose!==!1)try{await Z.controller.persist?.()}catch(J){Q.push(J)}try{await Z.controller.dispose?.()}catch(J){Q.push(J)}if(Q.length===1)throw Q[0];if(Q.length>1)throw AggregateError(Q,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(Z.context,Z.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId})}async finalizeSectionControllerDispose(Z){if(Z.clearPersistence)await Z.persistenceStrategy?.clearSession?.(Z.context)}dispose(){if(this.disposePromise)return this.disposePromise;return this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise}async disposeOwnedResources(){let Z=[],Q=async(Y)=>{try{await Y()}catch(X){Z.push(X)}};await this.waitForAdmittedInitialization();let J=new Map;for(let[Y,X]of this.sectionControllerInitEntries)J.set(Y,X.key);for(let[Y,X]of this.sectionControllerKeys)J.set(Y,X);for(let Y of J.values())this.disposeSectionController({sectionId:Y.sectionId,attemptId:Y.attemptId});await MZ(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let Y of this.activeSubscriptions.values())await Q(()=>Y.unsubscribeCurrent?.()),Y.unsubscribeCurrent=null;if(this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await Q(()=>this.ttsService.dispose()),await Q(()=>this.toolProviderRegistry.destroy()),await Q(()=>this.highlightCoordinator.destroy()),await Q(()=>this.ownedToolCoordinator.destroy()),await Q(()=>this.catalogResolver.destroy()),await Q(()=>this.toolRequests.dispose()),await Q(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.policyDiagnosticListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus)this.frameworkErrorBus.dispose();if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let Z=new Set;if(this.coordinatorReadyPromise)Z.add(this.coordinatorReadyPromise);this.tts.flushInitPromises(Z);for(let Q of this.providerInitPromises.values())Z.add(Q);await MZ(Z)}async ensureTTSReady(){return this.tts.ensureReady()}async waitUntilReady(){if(this.assertNotDisposed(),this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{if(await this.ensureStateLoaded(),this.assertNotDisposed(),this.tts.requiredForReadiness())await this.tts.startForReadiness();if(this.assertNotDisposed(),!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return(this.stateLoadSettled||!this.hooks.loadToolState)&&(this.tts.started||this.tts.failedUngranted||!this.tts.requiredForReadiness())}assertCanonicalToolId(Z){if(typeof Z!=="string"||Z.trim().length===0)throw Error("Tool id must be a non-empty string.");if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Z))throw Error(`Unknown tool id "${Z}".`)}installToolContextResolvers(Z){if(!Z)return;for(let[Q,J]of Object.entries(Z)){if(J==null)continue;if(this.assertCanonicalToolId(Q),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);this.toolContextResolvers.set(Q,J)}}setToolContextResolvers(Z){this.toolContextResolvers.clear(),this.installToolContextResolvers(Z??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Z of this.toolContextResolverChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Q)}}getToolConfig(Z){return this.assertCanonicalToolId(Z),this.config.tools?.providers?.[Z]||null}updateToolConfig(Z,Q){this.assertCanonicalToolId(Z);let J=this.getToolConfig(Z)||{};if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});if(!this.config.tools.providers)this.config.tools.providers={};let Y={...this.config.tools.providers,[Z]:c2(Z,J,Q)},X=this.validateToolsConfig({...this.config.tools,providers:Y},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X,this.policyEngine.updateInputs({tools:X}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Z}),this._applyToolConfigChange(Z)}updateToolsPlacement(Z){if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});let Q=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Z.section??Q.section??[]],item:[...Z.item??Q.item??[]],passage:[...Z.passage??Q.passage??[]]},Y=this.validateToolsConfig({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});Y.placement=J,this.config.tools=Y,this.policyEngine.updateInputs({tools:Y})}decideToolPolicy(Z){let Q=this.policyEngine.decide(Z);return this.warnPolicyDiagnostics(Q.diagnostics),Q}warnPolicyDiagnostics(Z){for(let Q of Z){let J=Q.code==="tool-policy.itemSettingNotApplied"?Q.details.itemId:"",Y=`${Q.code}\x00${Q.toolId}\x00${J}`;if(this.reportedPolicyDiagnostics.has(Y))continue;this.reportedPolicyDiagnostics.set(Y,Q),console.warn(`[ToolkitCoordinator] ${Q.message}`);for(let X of Array.from(this.policyDiagnosticListeners))this.notifyPolicyDiagnosticListener(X,Q)}}notifyPolicyDiagnosticListener(Z,Q){try{Z(Q)}catch(J){console.error("[ToolkitCoordinator] Policy diagnostic listener failed:",J)}}registerItemSettings(Z,Q){return this.policyEngine.registerItemSettings(Z,Q)}decideFeaturePolicy(Z,Q){let J=this.policyEngine.decideFeature(Z,Q);if(this.warnPolicyDiagnostics(J.diagnostics),!J.assessmentBound&&this.policyEngine.getInputs().assessmentExpected&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Z}" with no assessment bound, so profile, district and test-administration policy have nothing to read and only an item's requiredTools can grant. Pass the assessment to the toolkit's assessment property, or call updateAssessment(...), before relying on any accommodation. Reported once per coordinator.`);return J}reportFeatureDecisionApplied(Z,Q){if(Z.granted||Z.rule!=="support-conflict"||Z.overrode!=="attribute"&&Z.overrode!=="authored")return;let J=this.policyEngine.decideFeature(Z.featureId,Q);if(J.rule!=="support-conflict"||!J.withheldBy)return;this.warnPolicyDiagnostics([_Z(Z.featureId,J.withheldBy,Z.overrode)])}onPolicyChange(Z){return this.policyEngine.onPolicyChange(Z)}onPolicyDiagnostic(Z){this.policyDiagnosticListeners.add(Z);for(let Q of Array.from(this.reportedPolicyDiagnostics.values()))this.notifyPolicyDiagnosticListener(Z,Q);return()=>{this.policyDiagnosticListeners.delete(Z)}}onCatalogsChange(Z){return this.catalogResolver.onCatalogsChange(Z)}updateAssessment(Z){this.policyEngine.updateInputs({assessment:Z})}setPnpEnforcement(Z){this.policyEngine.updateInputs({pnpEnforcement:Z})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Z){return this.policyEngine.registerPolicySource(Z)}hasToolContextResolver(Z){return this.assertCanonicalToolId(Z),this.toolContextResolvers.has(Z)}resolveToolContext(Z){this.assertCanonicalToolId(Z.toolId);let Q=this.toolContextResolvers.get(Z.toolId);if(!Q)return null;let J;try{J=Q(Z)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Z.toolId}" threw:`,X),{toolId:Z.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Z.toolId,visible:!0,params:{}};let Y=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Z.toolId,visible:J.visible!==!1,params:Y,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Z){return this.toolContextResolverChangeListeners.add(Z),()=>{this.toolContextResolverChangeListeners.delete(Z)}}getToolRegistry(){return this.toolRegistry}registerToolRequestTarget(Z){return this.toolRequests.registerTarget(Z)}requestTool(Z){return this.assertCanonicalToolId(Z.toolId),this.toolRequests.request(Z)}canRequestTool(Z,Q,J){try{this.assertCanonicalToolId(Z)}catch{return!1}return this.toolRequests.canRequest(Z,Q,J)}onToolRequestTargetsChange(Z){return this.toolRequests.onTargetsChange(Z)}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Z){if(this.disposePromise!==null)return;if(this.tts.ownsTool(Z)){this.tts.scheduleReconfigure();return}this._registerChangedToolProvider(Z)}_registerChangedToolProvider(Z){let Q=this.getProviderDescriptorTools().find((J)=>J.toolId===Z);if(!Q)return;this.degradedTools.delete(Z),this.registerProviderFromTool(Q,!0)}}var s2=()=>{};function P1(Z){return Z===R.PLAYING||Z===R.LOADING}function N1(Z){let{ttsService:Q,silence:J}=Z;if(typeof Q?.onStateChange!=="function")return s2;let Y=Q.onStateChange((X)=>{if(P1(X))J()});return()=>{try{Y()}catch{}}}function w1(Z){try{if(P1(Z?.getState?.()))Z?.pause?.()}catch{}}import{timedMediaProjectionSignature as PQ}from"@pie-players/pie-players-shared/timed-media";function R1(Z,Q,J){let Y=Z.detail?.runtimeId;if(typeof Y==="string"&&Y!=="")return Y===Q;return J(Z.target)}function C1(Z,Q,J){let Y=[Z.catalogResolver.registerOwner({owner:{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:J.assessmentId,sectionId:J.sectionId},entity:Q.item})];if(Q.kind==="item"&&Q.settings)Y.push(Z.registerItemSettings(Q.canonicalItemId||Q.itemId,Q.settings));return Y}var n2=["a[href]","button","label","summary",...["button","checkbox","combobox","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","switch","tab","treeitem"].map((Z)=>`[role="${Z}"]`)].join(", "),b1=new Set(["mi","mn","mtext"]),r2=(Z)=>b1.has(Z.localName)||Z.localName==="mrow"&&Z.children.length===1&&b1.has(Z.children[0].localName),a2=(Z)=>Array.from(Z.getElementsByTagName("mfrac")).every((Q)=>Array.from(Q.children).every(r2))?"Fraction_Over":"Fraction_General",o2=(Z)=>!Z||Z.toLowerCase().split("-")[0]==="en",t2=(Z)=>{if(Z.localName!=="label")return Z;let Q=Z;if(Q.control)return Q.control;let J=Q.getAttribute("for"),Y=Q.getRootNode();return(J?Y.getElementById?.(J):null)??Q.querySelector("input, select, textarea, button")},E1=(Z,Q)=>{let J=t2(Z),Y=J?.getAttribute("aria-labelledby")?.split(/\s+/).filter(Boolean);if(!J||!Y?.length)return!1;let X=J.getRootNode(),G=Y.map((j)=>X.getElementById?.(j)??null).filter((j)=>j!==null);return G.length>0&&!G.some((j)=>j.contains(Q))};function S1(Z,Q={}){if(typeof MutationObserver>"u")return()=>{};let J=new Map,Y=!1,X=async(U,$,z)=>{let A=await QZ([{type:"math",mathml:U,fallbackText:""}],{language:z,loadSre:Q.loadSre,mathSpeech:{...o2(z)?{style:a2($)}:{},engineOptions:Q.getMathSpeech?.()?.engineOptions}});return A.usedMathSpeech?A.speechText:null},G=(U)=>{let $=p5(U,n2);if(!$||E1($,U))return;let z=b0(U,"math"),A=z&&ZZ(z.outerHTML);if(!z||!A)return;let O=s8(U,{contentLanguage:Q.getContentLanguage?.()}),P=`${O??""}\x00${A}`,D=J.get(P);if(!D)D=X(A,z,O),J.set(P,D);D.then((N)=>{if(Y||!N||!U.isConnected)return;if(E1($,U))return;if(U.getAttribute("aria-label")!==N)U.setAttribute("aria-label",N)})},j=new WeakSet,B=(U)=>{if(j.has(U))return;j.add(U),q.observe(U,{childList:!0,subtree:!0})},V=(U)=>{if(U.nodeType!==1)return;let $=U,z=p5($,"mjx-container");if(z){G(z);return}if($.shadowRoot)B($.shadowRoot);$Z($,(A)=>{if(A.nodeType!==1)return"skip";let O=A;if(O.localName==="mjx-container")return G(O),"skip";if(O.shadowRoot)B(O.shadowRoot);return})},q=new MutationObserver((U)=>{for(let $ of U)for(let z of $.addedNodes)V(z)});return B(Z),V(Z),()=>{Y=!0,q.disconnect()}}import{createPieLogger as ZQ,isGlobalDebugEnabled as QQ}from"@pie-players/pie-players-shared";function e2(Z,Q){if(Z===Q)return 0;let J=Z.compareDocumentPosition(Q);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class x7{shellsByElement=new Map;register(Z){let Q=this.shellsByElement.get(Z.element),J={...Z,sortKey:Date.now()};if(Q&&Q.kind===J.kind&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Z.element,J),!0}unregister(Z){return this.shellsByElement.delete(Z)}getOrderedShells(Z){let Q=Array.from(this.shellsByElement.values()).filter((J)=>!Z||J.kind===Z);return Q.sort((J,Y)=>e2(J.element,Y.element)),Q}getCanonicalIdMap(){let Z={};for(let Q of this.getOrderedShells("item")){if(!Q.itemId)continue;Z[Q.itemId]=Q.canonicalItemId||Q.itemId}return Z}clear(){this.shellsByElement.clear()}}var y1=ZQ("section-controller-binding",()=>QQ());function JQ(Z){let Q=Z?.renderables;if(!Array.isArray(Q))return null;let J=new Set;for(let Y of Q){let X=Y?.entity?.id;if(typeof X==="string"&&X)J.add(X)}return J}function T1(Z,Q){return Z.has(Q.itemId)||!!Q.canonicalItemId&&Z.has(Q.canonicalItemId)}class k7{registry=new x7;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;sectionRenderableIds=null;boundSections=new Map;loadedRenderableKeys=new Set;async initialize(Z){this.activeInitToken+=1;let Q=this.activeInitToken;this.coordinator=Z.coordinator,this.sectionId=Z.sectionId,this.attemptId=Z.attemptId,this.forgetUnregisteredLoads(Z.coordinator.getSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId}));let J;try{J=await Z.coordinator.getOrCreateSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId,input:{section:Z.section,sectionId:Z.sectionId,assessmentId:Z.assessmentId,view:Z.view},updateExisting:!0,initialSession:Z.initialSession,createDefaultController:Z.createDefaultController})}catch(X){if(Q===this.activeInitToken)this.unsubscribeController?.(),this.unsubscribeController=null,this.controller=null;throw X}if(Q!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.sectionRenderableIds=JQ(J.getCompositionModel?.());let Y=this.getSectionKey(Z.sectionId,Z.attemptId);this.boundSections.delete(Y),this.boundSections.set(Y,{sectionId:Z.sectionId,attemptId:Z.attemptId,renderableIds:this.sectionRenderableIds}),this.replayRegisteredShellsIntoController(J),Z.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.((X)=>{try{Z.onControllerEvent?.(X)}catch(G){y1.warn("onControllerEvent handler threw",G)}Z.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Z){if(!Z.handleContentRegistered)return;let Q=this.registry.getOrderedShells().filter((Y)=>this.isSectionRenderable(Y));if(Q.length===0)return;for(let Y of Q){let X=Y.canonicalItemId||Y.itemId;Z.handleContentRegistered({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind})}let J=Date.now();for(let Y of Q){let X=Y.canonicalItemId||Y.itemId,G=this.getLoadedKey(X,Y.contentKind);if(this.loadedRenderableKeys.has(G))Z.handleContentLoaded?.({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind,timestamp:J})}}getLoadedKey(Z,Q){return`${Q??""}:${Z}`}isSectionRenderable(Z){let Q=this.sectionRenderableIds;return!Q||T1(Q,Z)}getSectionKey(Z,Q){return`${Z}\x00${Q??""}`}controllerFor(Z){if(this.isSectionRenderable(Z))return this.controller;let Q=this.getSectionKey(this.sectionId,this.attemptId),J=[...this.boundSections.entries()].reverse();for(let[Y,X]of J){if(Y===Q||!X.renderableIds)continue;if(!T1(X.renderableIds,Z))continue;let G=this.coordinator?.getSectionController({sectionId:X.sectionId,attemptId:X.attemptId});if(G)return G}return null}requireControllerFor(Z,Q){let J=this.controllerFor(Z);if(!J)y1.warn(`Dropped ${Q} for "${Z.itemId}": no section this toolkit bound renders it.`);return J}forgetUnregisteredLoads(Z){if(!Z||Z===this.controller)return;let Q=Z.getRuntimeState?.()?.loadedRenderables??[];if(Q.length===0)return;let J=new Set;for(let Y of this.registry.getOrderedShells())if(J.add(Y.itemId),Y.canonicalItemId)J.add(Y.canonicalItemId);for(let Y of Q){if(J.has(Y.canonicalItemId)||J.has(Y.itemId))continue;Z.handleContentUnregistered?.({itemId:Y.itemId,canonicalItemId:Y.canonicalItemId,contentKind:Y.contentKind})}}register(Z){return this.registry.register(Z)}unregister(Z){return this.registry.unregister(Z)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Z){return this.registry.getCanonicalIdMap()[Z]||this.controller?.getCanonicalItemId?.(Z)||Z}handleContentRegistered(Z){if(!this.isSectionRenderable(Z))return;this.controller?.handleContentRegistered?.({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId||Z.itemId,contentKind:Z.contentKind||Z.kind})}handleContentUnregistered(Z){let Q=Z.canonicalItemId||Z.itemId,J=this.getLoadedKey(Q,Z.contentKind);if(this.registry.getOrderedShells().some((X)=>this.getLoadedKey(X.canonicalItemId||X.itemId,X.contentKind)===J))return;this.loadedRenderableKeys.delete(J),this.controllerFor(Z)?.handleContentUnregistered?.({itemId:Z.itemId,canonicalItemId:Q,contentKind:Z.contentKind||Z.kind})}handleContentLoaded(Z){let Q=Z.canonicalItemId||Z.itemId;if(this.loadedRenderableKeys.add(this.getLoadedKey(Q,Z.contentKind)),!this.isSectionRenderable(Z))return;this.controller?.handleContentLoaded?.(Z)}handleItemPlayerError(Z){this.requireControllerFor(Z,"an item player error")?.handleItemPlayerError?.(Z)}reportSectionError(Z){(Z.itemId?this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId},"a section error"):this.controller)?.reportSectionError?.(Z)}updateItemSession(Z,Q){let J=this.getCanonicalItemId(Z);return this.requireControllerFor({itemId:Z,canonicalItemId:J},"a session update")?.updateItemSession?.(J,Q)??null}recordServedContentIdentity(Z){let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId);this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a served content identity")?.recordServedContentIdentity?.({itemId:Q,identity:Z.identity})}navigateToItem(Z){return this.controller?.navigateToItem?.(Z)??null}handleTryAction(Z){if(!Z?.itemId)return;let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId),J=this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a Try action");if(Z.action==="retry"){J?.retryItem?.({itemId:Q});return}J?.recordTry?.({itemId:Q,outcomes:Z.outcomes})}handleMediaTimeSource(Z){if(!Z?.renderableId)return;let Q=this.requireControllerFor({itemId:Z.renderableId,canonicalItemId:this.getCanonicalItemId(Z.renderableId)},"a media time source");if(Z.action==="detach"){Q?.detachMediaTimeSource?.({origin:Z.origin??"host"});return}if(!Z.source)return;Q?.attachMediaTimeSource?.(Z.source,{origin:Z.origin??"host",renderableId:Z.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}async dispose(){this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null;let Z=this.coordinator;if(Z)for(let Q of this.boundSections.values())await Z.disposeSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId});this.registry.clear(),this.loadedRenderableKeys.clear(),this.boundSections.clear(),this.controller=null,this.sectionRenderableIds=null,this.coordinator=null}}function x1(Z){let Q=Z.section?.identifier;return Z.sectionId||(typeof Q==="string"?Q:"")||`section-${Z.assessmentId||"default"}`}function k1(Z,Q){return["pnpEnforcement","assessment"].filter((Y)=>Z?!Object.is(Z[Y],Q[Y]):Q[Y]!==null)}function I1(Z){if(!Z)return;let Q=Symbol.for("pie.assessmentToolkit.unclaimedRegistrationWatch"),J=Z;if(J[Q])return;J[Q]=!0,Z.addEventListener(X5,(Y)=>{let X=Y.detail,G=typeof X?.itemId==="string"?X.itemId:"";f1(Z,"unclaimedRegistration",`[pie-assessment-toolkit] Item "${G}" registered, but no toolkit claimed the registration, so its accessibility catalogs are not filed and it does not count toward its section's loading. Render its shell or scope inside the <pie-assessment-toolkit> that answered it. Reported once per page.`)})}function OZ(Z,Q){if(typeof Z==="function")return Z;if(Z===null)return null;return typeof Q==="function"?Q:null}function v1(Z={}){let Q=Z.frameDeadlineMs??100,J=!1,Y=null,X=null,G=null,j=null,B=null;function V(){if(J=!1,X!==null)j?.(X),X=null;if(G!==null)B?.(G),G=null;j=null,B=null}function q(z){if(!J)return;if(z==="frame")X=null;if(z==="timer")G=null;let A=Y;Y=null,V(),A?.()}function U(z){if(Y=z,J)return;J=!0;let A=globalThis,O=OZ(Z.requestFrame,A.requestAnimationFrame);j=OZ(Z.cancelFrame,A.cancelAnimationFrame);let P=OZ(Z.setTimer,A.setTimeout);if(B=OZ(Z.clearTimer,A.clearTimeout),O){let N=O(()=>q("frame"));if(!J)return;if(X=N,P){let M=P(()=>q("timer"),Q);if(J)G=M}return}let D=OZ(Z.queueMicrotaskFn,A.queueMicrotask);if(D){D(()=>q("microtask"));return}if(P){let N=P(()=>q("timer"),0);if(J)G=N;return}q("microtask")}function $(){if(!J)return;Y=null,V()}return{schedule:U,cancel:$,isPending:()=>J}}function h1(Z="runtime"){return`${Z}-${Math.random().toString(16).slice(2)}-${Date.now()}`}function m1(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function u1(Z){Z.lastSessionEventSignatureByItemId.clear(),Z.lastMetadataSignatureByItemId.clear()}function p1(Z){let{state:Q,itemId:J,payload:Y}=Z;if(XQ(Y)){let j=GQ(Y);if(Q.lastMetadataSignatureByItemId.get(J)===j)return!1;Q.lastMetadataSignatureByItemId.set(J,j)}let X=YQ(Y);if(Q.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Q.lastSessionEventSignatureByItemId.set(J,X),!0}function YQ(Z){let Q={...Z};delete Q.timestamp,delete Q.sourceRuntimeId;try{return JSON.stringify(Q)}catch{return String(Q.itemId||"")}}function XQ(Z){return Z.intent==="metadata-only"}function GQ(Z){try{return JSON.stringify({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId,intent:Z.intent,complete:Z.complete??null,component:Z.component??null})}catch{return String(Z.itemId||"")}}var jQ=(Z,Q)=>{if(customElements.get(Z))return;try{customElements.define(Z,Q)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Z))throw J}},NQ=h7('<div class="pie-assessment-toolkit-error svelte-15pthty" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-15pthty"> </div> <div class="pie-assessment-toolkit-error-message svelte-15pthty"> </div> <pre class="pie-assessment-toolkit-error-details svelte-15pthty"> </pre></div>'),wQ=h7('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),RQ={hash:"svelte-15pthty",code:`.pie-assessment-toolkit-anchor.svelte-15pthty {display:none;}.pie-assessment-toolkit-error.svelte-15pthty {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
224
+ color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-15pthty {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-15pthty {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-15pthty {margin:0;white-space:pre-wrap;word-break:break-word;}`};function U4(Z,Q){i1(Q,!0),e1(Z,RQ);let J=UQ("pie-assessment-toolkit",()=>$Q()),Y=h1("toolkit"),X=new k7,G=new UZ,j={mode:"gather",role:"student"},B={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},V="Unable to initialize assessment toolkit.",q=I(Q,"assessmentId",7,""),U=I(Q,"section",7,null),$=I(Q,"sectionId",7,""),z=I(Q,"attemptId",7,""),A=I(Q,"env",23,()=>({})),O=I(Q,"ndsIcons",7,!1),P=I(Q,"locale",7,""),D=I(Q,"i18n",7,null),N=I(Q,"contentLanguage",7,""),M=I(Q,"lazyInit",7,!1),C=I(Q,"toolConfigStrictness",7,"error"),E=I(Q,"tools",23,()=>({})),v=I(Q,"toolContextResolvers",7,null),S=I(Q,"enabledTools",7,""),g=I(Q,"toolRegistry",7,null),e=I(Q,"accessibility",23,()=>({})),r=I(Q,"player",7,null),q0=I(Q,"playerType",7,""),Z0=I(Q,"coordinator",7,null),M0=I(Q,"createSectionController",7,null),O0=I(Q,"onFrameworkError",7,null),LZ=I(Q,"errorRenderer",7,null),PZ=I(Q,"assessment",7,null),U0=I(Q,"isolation",7,"inherit"),L0=I(Q,"session",7,null),GZ=s(null),c=s(null),Y0=s(null),m7=null,u7=null,jZ=!1,p0=null,g0=null,c0=null,d0=null,NZ=s(0),K5=s(null),X0=s(null),q5=s(V),U5=s(s1([])),p7="",$5="",BZ=null,WZ=null,wZ=null,g7=null,F5=null,c7=null,RZ=null,d7=!1,i7=null,l7=!1,s7=s(""),z5=null,CZ=v1(),P0=[],bZ=new Map,A5=new WeakMap,EZ=new Map,n7=m1(),VZ=s(!1);function $4(){if(!F(GZ))return null;let W=F(GZ).getRootNode();if(W&&"host"in W)return W.host;return F(GZ).parentElement}let k=u(()=>$4());function N0(W,K){if(!F(k)){P0=[...P0,{name:W,detail:K}];return}v7(F(k),W,K)}y(()=>{if(!F(k))return;if(P0.length===0)return;let W=P0;P0=[],queueMicrotask(()=>{let K=F(k);if(!K){P0=[...W,...P0];return}for(let H of W)v7(K,H.name,H.detail)})});function r7(W){return W.details.length>0?W.details:[W.message]}function F4(W){if(!LZ())return{title:V,details:r7(W)};try{let K=LZ()(W)||{};return{title:typeof K.title==="string"&&K.title.trim().length>0?K.title:V,details:Array.isArray(K.details)&&K.details.length>0?K.details.map((H)=>String(H)):r7(W)}}catch(K){let H=K instanceof Error&&K.message.trim().length>0?K.message:String(K||"Unknown renderer error");return{title:V,details:[...W.details,`Error renderer failed: ${H}`]}}}function w0(W){let K=u5({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable,scope:W.cohort?"cohort":"runtime",cohort:W.cohort});return G.reportFrameworkError(K),K}function a7(W){return(W||[]).map((K)=>K?.message).filter((K)=>typeof K==="string")}function z4(W,K){if(W?.type==="timed-media-policy-degraded"){G.reportFrameworkError(IZ({kind:"timed-media",severity:"warning",source:"pie-assessment-toolkit",message:"A timed-media playback policy degraded to advisory: the media time source does not report the capability it needs.",details:a7(W.degradations),recoverable:!0,scope:"cohort",cohort:K}));return}if(W?.type!=="timed-media-invalid")return;G.reportFrameworkError(IZ({kind:"timed-media",severity:"error",source:"pie-assessment-toolkit",message:'This section declares sectionType: "timed-media" but its timedMedia data is not deliverable; the section renders without cue behavior.',details:a7(W.errors),recoverable:!1,scope:"cohort",cohort:K}))}function A4(W){if(W?.type!=="timed-media-audio-started")return;if(!F(b))return;w1(F(b).ttsService)}function H4(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function KZ(W){return`${W.kind}|${W.source}|${W.message}`}function o7(W){if(!O0())return;try{O0()(W),p7=KZ(W)}catch(K){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,K)}}let t7=new WeakSet,e7=new WeakMap;function D4(W){if(typeof W!=="object"||W===null)return null;return e7.get(W)??null}function Z8(W){let K=F4(W);h(X0,W,!0),h(q5,K.title,!0),h(U5,K.details,!0)}function Q8(){h(X0,null),h(q5,V),h(U5,[],!0)}y(()=>{let W=G.subscribeFrameworkErrors((K)=>{if(console.error(x8(K),K.cause),typeof K.cause==="object"&&K.cause!==null)e7.set(K.cause,K);if(H4(K.kind)&&!t7.has(K))Z8(K);N0("framework-error",K),o7(K)});return()=>{W()}}),y(()=>{let W=Z0();if(!W||F(b)!==W)return;if(typeof W.subscribeFrameworkErrors!=="function")return;return x(()=>W.subscribeFrameworkErrors((K)=>{t7.add(K),G.reportFrameworkError(K)}))}),y(()=>{let W=F(b),K=g();if(!W||F(TZ))return;if(typeof W.adoptToolRegistry!=="function")return;x(()=>{let H=W===F(c);if(H&&!K)return;if(W.adoptToolRegistry(K)&&H&&BZ)BZ={...BZ,toolRegistry:K}})}),y(()=>{if(!F(X0))return;if(p7===KZ(F(X0)))return;o7(F(X0))});function _4(W){let K=5381;for(let H=0;H<W.length;H+=1)K=(K<<5)+K^W.charCodeAt(H);return(K>>>0).toString(36)}function a(W){return W&&typeof W==="object"?W:{}}function M4(W){let K=a(W.section),H=typeof K.identifier==="string"?K.identifier:"",w=typeof W.sectionId==="string"?W.sectionId:"";return H||w}function O4(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function L4(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((H,w)=>{let L=a(H),_=a(L.entity),l=typeof _.id==="string"&&_.id||`renderable-${w}`,kZ=a(_.config),R5=typeof _.version==="string"&&_.version||(typeof _.version==="number"?String(_.version):"")||(typeof kZ.version==="string"?kZ.version:"");return{id:l,version:R5}})}function P4(W){let K=a(W.itemSessionsByItemId);return Object.keys(K).sort((H,w)=>H.localeCompare(w)).map((H)=>{let w=a(K[H]),L=typeof w.id==="string"?w.id:"",_=Array.isArray(w.data)?w.data:[],l="";try{l=_4(JSON.stringify(_))}catch{l=String(_.length)}return{itemId:H,sessionId:L,payloadSignature:l}})}function N4(W){let K=a(a(W.tries).states);return Object.entries(K).map(([H,w])=>{let L=a(w),_=a(L.lastOutcome).correctness??"";return`${H}:${L.tryCount??0}:${L.revealed===!0?1:0}:${String(_)}:${String(L.revealOverride??"")}`}).sort().join("|")}function w4(W){let K=W.timedMedia;return PQ(K)}function R4(W){let K=a(W),H=L4(K).map((L)=>`${L.id}:${L.version}`).join("|"),w=P4(K).map((L)=>`${L.itemId}:${L.sessionId}:${L.payloadSignature}`).join("|");return{sectionId:M4(K),currentItemIndex:O4(K),renderableSignature:H,itemSessionSignature:w,trySignature:N4(K),timedMediaSignature:w4(K)}}function C4(W){let K=R4(W);return`${K.sectionId}|${K.currentItemIndex}|${K.renderableSignature}|${K.itemSessionSignature}|${K.trySignature}|${K.timedMediaSignature}`}function J8(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function b4(W,K){let H=W?.type,w=J8(H)?H:J8(K)?K:W?.tagName?"custom":"iife",L=W?.tagName?.trim();if(w==="custom"&&!L)return{type:"iife",tagName:B.iife,version:void 0,source:void 0,isDefault:!0};return{type:w,tagName:L||B[w],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!K}}function Y8(W){let K=W||{},H=typeof K.mode==="string"&&K.mode.trim()?K.mode.trim():j.mode,w=typeof K.role==="string"&&K.role.trim()?K.role.trim():j.role;return{mode:H,role:w}}function E4(W){let K=Y8(W);if(K.mode==="author")return"author";if(K.role==="instructor")return"scorer";return"candidate"}function X8(W,K){return W.sectionId===K.sectionId&&W.attemptId===K.attemptId}function G8(){if(!L0()||L0()===g7)return;g7=L0(),wZ={value:L0(),cohort:{sectionId:F(Q0),attemptId:z()||void 0}}}function j8(W,K){G8();let H=wZ;if(!H)return null;if(!X8(H.cohort,W)){if(K)wZ=null;return null}return wZ=null,H.value}function B8(){let W=F5,K=F(b);if(!W||!K)return;let H=j8(W,!1);if(!H)return;let w=K.getSectionController(W);if(!w)return;let L=J5(w.getSession?.()??null,H);if(!L)return;Promise.resolve().then(()=>{if(!w.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");return w.applySession(L,{mode:"replace"})}).catch((_)=>{w0({kind:"unknown",source:"pie-assessment-toolkit",error:_,recoverable:!0})})}async function S4(){if(M0())return M0()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function H5(){let W=E()||{},K=X4(S());if(K.length===0)return W;let H=W.placement||{},w=Array.isArray(H.section)?H.section:null;if(w&&w.length>0)return W;return{...W,placement:{...H,section:K}}}function y4(){return M8(H5(),{strictness:C(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:g()}).config}function T4(){let W="",K="";try{W=JSON.stringify(H5())}catch{W="[unserializable-tools]"}try{K=JSON.stringify(Object.entries(v()??{}).map(([H,w])=>[H,typeof w]))}catch{K="[unserializable-resolvers]"}return[q()||"",String(C()||"error"),W,K].join("|")}function x4(W){let K=W?.pnpEnforcement;return K==="on"||K==="off"?K:null}function k4(W){let K=q()||U()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new T7({assessmentId:K,lazyInit:M(),eagerInit:!1,toolConfigStrictness:C(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:W,toolRegistry:g(),toolContextResolvers:v(),accessibility:e(),frameworkErrorBus:G})}function W8(W){try{return JSON.stringify(W??null)}catch{return"[unserializable]"}}function V8(){return{signatures:{assessmentId:q()||"",toolConfigStrictness:String(C()||"error"),lazyInit:String(M()),tools:W8({...H5(),pnpEnforcement:void 0}),accessibility:W8(e())},toolRegistry:g()}}function f4(){let W=BZ;if(!W)return[];let K=V8(),H=Object.keys(K.signatures).filter((w)=>K.signatures[w]!==W.signatures[w]);if(W.toolRegistry&&K.toolRegistry!==W.toolRegistry)H.push("toolRegistry");return H}function I4(W,K){if(d7)return;d7=!0,console.warn(`[pie-assessment-toolkit] ${W.join(", ")} changed after ${K} with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section or the first item scope, pass a coordinator of your own, or update this one from runtime-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`)}function v4(W){if(l7)return;l7=!0,console.warn(`[pie-assessment-toolkit] The toolkit above this one (runtime "${W}") had no coordinator when this one connected, so this one built its own and keeps it: the two share no tool state, policy or read-aloud. Give the outer toolkit its coordinator before the inner one connects, or set isolation="force" on the inner one to keep them apart on purpose. Reported once per toolkit.`)}function SZ(){let W=F(c);if(!W)return Promise.resolve();return h(c,null),W.dispose()}function yZ(W){w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}let TZ=u(()=>!Z0()&&U0()!=="force"&&F(Y0)?.coordinator!=null),b=u(()=>{if(F(TZ))return F(Y0)?.coordinator;return Z0()||F(c)}),D5=u(()=>U()!=null);y(()=>{F(k),Z0(),U0(),F(Y0),v(),F(D5),F(VZ),E(),S(),q(),C(),M(),e(),g(),x(()=>{if(!F(k))return;if(Z0()){if(F(c))SZ().catch(yZ);p0=null;return}if(U0()!=="force"&&F(Y0)?.coordinator){if(F(c))SZ().catch(yZ);p0=null;return}if(F(c)){let W=f4();if(W.length>0&&WZ)I4(W,WZ);else if(W.length>0&&(U()||F(VZ)))SZ().catch(yZ)}if(F(c)&&p0!==v()){try{F(c).setToolContextResolvers(v()),p0=v()}catch(W){w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:W})}return}if(!F(c)){if(U0()!=="force"&&!jZ){let K=g1(F(k),V5);if(K?.coordinator&&K.runtimeId!==Y){h(Y0,K,!0),p0=null;return}}let W=T4();if($5===W)return;try{let K=y4();h(c,k4(K),!0),jZ=U0()!=="force",BZ=V8(),WZ=null,p0=v(),$5="",Q8()}catch(K){h(c,null),$5=W,w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:K})}}})}),y(()=>{if(!F(VZ)||!F(b))return;let W=F(b);x(()=>{if(W===F(c))WZ??="an item registered"})});let _5=zQ(),i0=u(()=>D()??_5),l0=s(0);y(()=>{return F(i0).subscribe?.(()=>{h(l0,F(l0)+1)})}),y(()=>{let W=typeof P()==="string"?P().trim():"",K=F(i0);if(!W&&K!==_5)return;if(W&&K!==_5&&_Q(K,W))return;x(()=>{Promise.resolve(K.setLocale(W||AQ)).catch((H)=>{w0({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:H instanceof Error?H:Error(String(H)),recoverable:!0})})})});let K8=u(()=>{return F(l0),OQ({locale:P(),i18n:F(i0)})}),h4=u(()=>({locale:F(K8),direction:MQ(F(K8))})),M5=u(()=>{return F(l0),DQ({locale:P(),i18n:D()})}),q8=s(!1);y(()=>{if(F(M5))h(q8,!0)});let xZ=null;y(()=>{F(l0);let W=F(k),K=F(i0);if(!F(M5)||!W){if(xZ){let H=xZ;xZ=null,x(()=>{H.removeAttribute("lang"),H.removeAttribute("dir")})}return}x(()=>{LQ(W,K),xZ=W})});let R0=u(()=>q()||F(b)?.assessmentId||""),Q0=u(()=>x1({sectionId:$(),section:U(),assessmentId:q()})),O5=u(()=>Y8(A())),m4=u(()=>E4(F(O5))),s0=u(()=>b4(r(),q0())),qZ=u(()=>KQ({player:F(s0),component:"pie-assessment-toolkit"})),u4=u(()=>{if(!F(b))return null;return{toolkitCoordinator:F(b),toolCoordinator:F(b).toolCoordinator,ttsService:F(b).ttsService,highlightCoordinator:F(b).highlightCoordinator,catalogResolver:F(b).catalogResolver,elementToolStateStore:F(b).elementToolStateStore,assessmentId:F(R0),sectionId:F(Q0),attemptId:z()||void 0,itemPlayer:F(s0),ndsIcons:O()===!0,locale:(F(l0),F(i0).getLocale()),i18n:F(i0),interfaceLocaleChosen:F(M5),contentLanguage:N()?.trim()||void 0,contentLanguageDefault:HQ({contentLanguage:N(),interfaceLocale:P()}),reportSectionError:(W)=>{X.reportSectionError({source:"section-runtime",error:W,timestamp:Date.now()})}}}),p4=u(()=>{if(!F(b)||!F(k))return null;return{runtimeId:Y,coordinator:F(b),sectionBound:F(D5),eventTarget:F(k)}});function U8(W){if(W==null)return;let K=C4(W);if(K===F(s7))return;h(s7,K,!0),h(NZ,F(NZ)+1),h(K5,W,!0),N0("composition-changed",{composition:F(K5),version:F(NZ)})}function L5(W){z5=W??X.getCompositionModel(),CZ.schedule(()=>{U8(z5)})}function g4(){if(!CZ.isPending())return;CZ.cancel(),U8(z5)}function P5(W){if(!W)return;let K=A5.get(W);if(!K)return;for(let H of K)H();A5.delete(W)}function $8(){for(let W of bZ.values())P5(W.element)}function F8(W){if(P5(W.element),!F(b))return;A5.set(W.element,C1(F(b),W,{assessmentId:F(R0),sectionId:F(Q0)}))}function c4(){$8();for(let W of bZ.values())F8(W)}function N5(W){if(!W)return;EZ.get(W)?.(),EZ.delete(W)}function d4(W){N5(W),EZ.set(W,S1(W,{getMathSpeech:()=>F(b)?.ttsService.getMathSpeechOptions(),getContentLanguage:()=>N()}))}function i4(W){let H={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:Y};if(!p1({state:n7,itemId:W.itemId,payload:H}))return;N0("session-changed",H)}function l4(W){if(!(W instanceof HTMLElement))return!1;return g1(W,V5)?.runtimeId===Y}function $0(W){return W.detail??null}function s4(W,K){for(let H of K)W.addEventListener(H.name,H.handler);return()=>{for(let H of K)W.removeEventListener(H.name,H.handler)}}y(()=>{let W=F(k),K=U0();return x(()=>{if(!W)return;if(K==="force")return h(Y0,null),()=>{jZ=!1};let H=Y4(W,(w)=>{if(w.runtimeId===Y)return;if(jZ){v4(w.runtimeId);return}h(Y0,w,!0)});return()=>{H(),h(Y0,null),jZ=!1}})}),y(()=>{let W=F(b);if(!W)return;return x(()=>N1({ttsService:W.ttsService,silence:()=>X.requestMediaPauseForCompetingAudio()}))}),y(()=>{let W=F(TZ)?F(Y0)?.runtimeId??null:null,K=W?"inherited":"owned";if(K!==m7)m7=K,N0(K==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:Y,parentRuntimeId:W})}),y(()=>{let W=F(k);if(!W)return;x(()=>I1(W.ownerDocument))}),y(()=>{let W=F(b);if(!W)return;let K=F(TZ)?"inherited":"owned";x(()=>{if(W===u7)return;u7=W,N0("runtime-ready",{runtimeId:Y,coordinator:W,ownership:K})})}),y(()=>{let W=F(Q0),K=z()||"";u1(n7)}),y(()=>{if(!F(k))return;F(k).setAttribute("data-item-player-type",F(s0).type),F(k).setAttribute("data-item-player-tag",F(s0).tagName),F(k).setAttribute("data-env-mode",F(O5).mode),F(k).setAttribute("data-env-role",F(O5).role)}),y(()=>{return F(b),F(R0),F(Q0),c4(),()=>{$8()}}),y(()=>{if(!F(k))return;return VQ({host:F(k),instrumentationProvider:F(qZ),component:"pie-assessment-toolkit",eventMap:qQ,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:F(R0),sectionId:F(Q0),attemptId:z()||void 0}})});let w5=null;y(()=>{PZ(),E();let W=F(b);if(!W)return;if(W!==F(c))return;x(()=>{let K={pnpEnforcement:x4(E()),assessment:PZ()??null},H=w5?.coordinator===W?w5.inputs:null;w5={coordinator:W,inputs:K};for(let w of k1(H,K))if(w==="pnpEnforcement")W.setPnpEnforcement(K.pnpEnforcement);else W.updateAssessment(K.assessment)})}),y(()=>{if(!F(b))return;return F(b).subscribeTelemetry(({eventName:W,payload:K})=>{if(!FQ(F(qZ)))return;if(!F(qZ).isReady())return;let H=new Date().toISOString(),w={...K||{},instrumentationLayer:"toolkit",assessmentId:F(R0),sectionId:F(Q0),attemptId:z()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:H};F(qZ).trackEvent(W,w);let L=K&&typeof K.errorType==="string"?K.errorType:void 0;if(!W.endsWith("-error")&&!L)return;let _=K&&typeof K.message==="string"?K.message:`Toolkit telemetry error: ${W}`;F(qZ).trackError(Error(_),{component:"pie-assessment-toolkit",errorType:L||"ToolkitTelemetryError",...w})})}),y(()=>{if(!U()||!F(b))return;let W=!1;if(F(b)===x(()=>F(c)))WZ??="a section initialized";let K={sectionId:F(Q0),attemptId:z()||void 0},H=c7;if(c7=K,H&&!X8(H,K))x(()=>c1(F(k),{reason:"teardown",logger:J}));F5=null;let w=x(()=>j8(K,!0));return X.initialize({coordinator:F(b),section:U(),sectionId:F(Q0),assessmentId:F(R0),attemptId:z()||void 0,view:F(m4),initialSession:w,createDefaultController:S4,onCompositionChanged:(L)=>{if(W)return;L5(L)},onControllerEvent:(L)=>{if(W)return;A4(L),z4(L,K)}}).then(()=>{if(W)return;F5=K;let L=x(()=>F(X0));if(L&&KZ(L)===RZ)Q8();RZ=null,x(()=>B8()),x(()=>g4()),queueMicrotask(()=>{if(W)return;N0("toolkit-ready",{runtimeId:Y,assessmentId:F(R0),sectionId:F(Q0),itemPlayer:F(s0),coordinator:F(b)}),N0("section-ready",{sectionId:K.sectionId,attemptId:K.attemptId,controller:F(b).getSectionController(K)??null})})}).catch((L)=>{if(W)return;let _=x(()=>D4(L));if(_)x(()=>Z8(_)),RZ=KZ(_);else RZ=KZ(w0({kind:"runtime-init",source:"pie-assessment-toolkit",error:L,cohort:K}))}),()=>{W=!0}}),y(()=>{L0(),x(()=>{G8(),B8()})}),y(()=>{if(!F(k))return;let W=F(k),K=(L)=>{if(!R1(L,Y,l4))return!1;return L.stopPropagation(),!0},w=s4(W,[{name:X5,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.element||!_?.itemId)return;let l=X.register(_);if(bZ.set(_.element,_),h(VZ,!0),F8(_),d4(_.element),X.handleContentRegistered(_),l)L5()}},{name:G4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;let l=_?.element?X.unregister(_.element):!1;if(P5(_.element),N5(_.element),_.element)bZ.delete(_.element);if(X.handleContentUnregistered(_),l)L5()}},{name:j4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;let l=X.updateItemSession(_.itemId,_.session);i4({itemId:_.itemId,canonicalItemId:X.getCanonicalItemId(_.itemId),result:l,fallbackSession:_.session})}},{name:W4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;X.recordServedContentIdentity({itemId:_.itemId,canonicalItemId:_.canonicalItemId,identity:_.identity})}},{name:B4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;X.handleContentLoaded({itemId:_.itemId,canonicalItemId:_.canonicalItemId,contentKind:_.contentKind,detail:_.detail,timestamp:Date.now()})}},{name:V4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;X.handleItemPlayerError({itemId:_.itemId,canonicalItemId:_.canonicalItemId,contentKind:_.contentKind,error:_.error,timestamp:Date.now()})}},{name:K4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.itemId)return;if(_.action!=="check"&&_.action!=="retry")return;X.handleTryAction({itemId:_.itemId,canonicalItemId:_.canonicalItemId,action:_.action,outcomes:_.outcomes})}},{name:q4,handler:(L)=>{if(!K(L))return;let _=$0(L);if(!_?.renderableId)return;if(_.action!=="attach"&&_.action!=="detach")return;X.handleMediaTimeSource({renderableId:_.renderableId,action:_.action,source:_.source,origin:_.origin})}}]);return()=>{x(()=>c1(W,{reason:"teardown",logger:J})),w();for(let L of[...EZ.keys()])N5(L)}}),y(()=>{if(!F(k))return;return()=>{c0?.disconnect(),c0=null,g0?.disconnect(),g0=null,d0?.disconnect(),d0=null}}),y(()=>{let W=F(k),K=F(p4);if(!W||!K)return;x(()=>{if(c0){c0.setValue(K);return}c0=new f7(W,{context:V5,initialValue:K}),c0.connect()})}),y(()=>{let W=F(k),K=F(u4);if(!W||!K)return;x(()=>{if(g0){g0.setValue(K);return}g0=new f7(W,{context:J4,initialValue:K}),g0.connect()})}),y(()=>{let W=F(k),K=F(h4);if(!W||!F(q8))return;x(()=>{if(d0){d0.setValue(K);return}d0=new f7(W,{context:WQ,initialValue:K}),d0.connect()})});async function n4(){if(!F(b))throw Error("Coordinator not initialized");await F(b).waitUntilReady()}function r4(W){if(!F(b))throw Error("Coordinator not initialized");F(b).setHooks(W)}function a4(W){return X.navigateToItem(W)}function o4(){return X.getCompositionModel()}function t4(){return F(s0)}async function e4(){await X.persist()}async function Z6(){await X.hydrate()}y(()=>{let W=F(b);if(!W)return;let K=F(NZ)>0||F(K5)!==null,H=!F(D5)&&F(VZ);if(!K&&!H)return;x(()=>{if(W===i7)return;i7=W,W.waitUntilReady().catch(()=>{})})}),y(()=>{return()=>{CZ.cancel(),X.dispose().catch((W)=>{w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).then(()=>SZ()).catch(yZ).finally(()=>{G.dispose()})}});var Q6={waitUntilReady:n4,setHooks:r4,navigateToItem:a4,getCompositionModel:o4,getItemPlayerConfig:t4,persist:e4,hydrate:Z6,get assessmentId(){return q()},set assessmentId(W){q(W),f()},get section(){return U()},set section(W){U(W),f()},get sectionId(){return $()},set sectionId(W){$(W),f()},get attemptId(){return z()},set attemptId(W){z(W),f()},get env(){return A()},set env(W){A(W),f()},get ndsIcons(){return O()},set ndsIcons(W){O(W),f()},get locale(){return P()},set locale(W){P(W),f()},get i18n(){return D()},set i18n(W){D(W),f()},get contentLanguage(){return N()},set contentLanguage(W){N(W),f()},get lazyInit(){return M()},set lazyInit(W){M(W),f()},get toolConfigStrictness(){return C()},set toolConfigStrictness(W){C(W),f()},get tools(){return E()},set tools(W){E(W),f()},get toolContextResolvers(){return v()},set toolContextResolvers(W){v(W),f()},get enabledTools(){return S()},set enabledTools(W){S(W),f()},get toolRegistry(){return g()},set toolRegistry(W){g(W),f()},get accessibility(){return e()},set accessibility(W){e(W),f()},get player(){return r()},set player(W){r(W),f()},get playerType(){return q0()},set playerType(W){q0(W),f()},get coordinator(){return Z0()},set coordinator(W){Z0(W),f()},get createSectionController(){return M0()},set createSectionController(W){M0(W),f()},get onFrameworkError(){return O0()},set onFrameworkError(W){O0(W),f()},get errorRenderer(){return LZ()},set errorRenderer(W){LZ(W),f()},get assessment(){return PZ()},set assessment(W){PZ(W),f()},get isolation(){return U0()},set isolation(W){U0(W),f()},get session(){return L0()},set session(W){L0(W),f()}},z8=wQ(),A8=I7(z8);Z4(A8,(W)=>h(GZ,W),()=>F(GZ));var J6=j5(A8,2);{var Y6=(W)=>{var K=NQ(),H=n1(K),w=G5(H,!0),L=j5(H,2),_=G5(L,!0),l=j5(L,2),kZ=G5(l,!0);d1(K),r1((R5)=>{W5(w,F(q5)),W5(_,F(X0).message),W5(kZ,R5)},[()=>F(U5).join(`
225
+ `)]),B5(W,K)},X6=(W)=>{var K=a1(),H=I7(K);t1(H,Q,"default",{},null),B5(W,K)};o1(J6,(W)=>{if(F(X0)&&!F(X0).recoverable)W(Y6);else W(X6,-1)})}return B5(Z,z8),l1(Q6)}jQ("pie-assessment-toolkit",Q4(U4,{assessmentId:{attribute:"assessment-id",type:"String"},section:{attribute:"section",type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},env:{attribute:"env",type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},i18n:{type:"Object"},contentLanguage:{attribute:"content-language",type:"String"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},assessment:{type:"Object"},isolation:{attribute:"isolation",type:"String"},session:{type:"Object"}},["default"],["waitUntilReady","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"},BQ));export{U4 as default};