@pie-players/pie-assessment-toolkit 0.3.66 → 0.3.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/attempt/AssessmentSession.d.ts +7 -27
- package/dist/components/ItemToolBar.custom-element.js +1 -1
- package/dist/components/PieAssessmentToolkit.custom-element.js +13 -13
- package/dist/components/SectionToolBar.custom-element.js +1 -1
- package/dist/components/chunks/ItemToolBar-38mhtjsq.js +51 -0
- package/dist/components/chunks/ItemToolBar-9ymm7pd1.js +46 -0
- package/dist/components/item-toolbar-element.js +1 -0
- package/dist/components/pie-assessment-toolkit-element.js +1 -0
- package/dist/components/section-toolbar-element.js +1 -0
- package/dist/context/assessment-toolkit-context.d.ts +28 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +5 -2
- package/dist/policy/core/ToolPolicyEngine.d.ts +12 -0
- package/dist/policy/core/ToolPolicyEngine.js +28 -2
- package/dist/policy/core/feature-decision.d.ts +28 -2
- package/dist/policy/core/feature-decision.js +35 -0
- package/dist/policy/engine.d.ts +1 -1
- package/dist/policy/engine.js +1 -0
- package/dist/runtime/SectionRuntimeEngine.d.ts +56 -0
- package/dist/runtime/SectionRuntimeEngine.js +66 -1
- package/dist/runtime/core/engine-resolver.d.ts +25 -1
- package/dist/runtime/registration-events.d.ts +52 -0
- package/dist/runtime/registration-events.js +2 -0
- package/dist/services/AccessibilityCatalogResolver.js +21 -5
- package/dist/services/I18nService.d.ts +28 -100
- package/dist/services/I18nService.js +43 -233
- package/dist/services/TTSService.d.ts +12 -0
- package/dist/services/TTSService.js +18 -17
- package/dist/services/ToolRegistry.d.ts +86 -2
- package/dist/services/ToolRegistry.js +30 -0
- package/dist/services/ToolkitCoordinator.d.ts +39 -37
- package/dist/services/ToolkitCoordinator.js +40 -0
- package/dist/services/audio-handoff.d.ts +39 -0
- package/dist/services/audio-handoff.js +58 -0
- package/dist/services/catalog-media.d.ts +35 -4
- package/dist/services/catalog-media.js +92 -3
- package/dist/services/framework-error.d.ts +15 -1
- package/dist/services/interfaces.d.ts +28 -0
- package/dist/services/pnp-standard-features.d.ts +1 -1
- package/dist/services/section-controller-types.d.ts +218 -7
- package/dist/services/selection-action.d.ts +49 -0
- package/dist/services/selection-action.js +10 -0
- package/dist/services/spoken-audio-cards.js +5 -1
- package/dist/services/tool-context.d.ts +6 -5
- package/dist/services/tool-context.js +197 -152
- package/dist/services/tool-icons.d.ts +18 -0
- package/dist/services/tool-icons.js +31 -0
- package/dist/services/tool-providers/DesmosToolProvider.d.ts +6 -5
- package/dist/services/tool-request.d.ts +106 -0
- package/dist/services/tool-request.js +127 -0
- package/dist/services/toolbar-items.d.ts +6 -0
- package/dist/tools/client.d.ts +0 -1
- package/dist/tools/client.js +0 -2
- package/dist/tools/content-capability-resolution.d.ts +106 -0
- package/dist/tools/content-capability-resolution.js +136 -0
- package/dist/tools/internal.d.ts +8 -0
- package/dist/tools/internal.js +8 -0
- package/dist/tools/tool-surface-host.d.ts +57 -0
- package/dist/tools/tool-surface-host.js +610 -0
- package/package.json +14 -10
- package/dist/components/chunks/ItemToolBar-8jgdz50p.js +0 -51
- package/dist/components/chunks/ItemToolBar-cvs646j3.js +0 -36
- package/dist/tools/calculators/desmos-provider.d.ts +0 -46
- package/dist/tools/calculators/desmos-provider.js +0 -393
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{B as
|
|
1
|
+
import{B as N3,C as M3,I as O3,J as x,K as z3,L as P3,M as I8,O as L3,Q as L7,R as $3,S as R7,T as E8,b as EQ,c as d7,d as _3,e as V3,f as n,g as y,h,i as w,j as f8,k as i7,l as k8,m as C1,n as b,o as H3,p as _,q as m,t as v8,u as F3,v as T1,w as S1,x as A3}from"./chunks/ItemToolBar-38mhtjsq.js";import{ContextProvider as B3,ContextRoot as D3,requestContext as u9}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as p9,createStageTracker as g9,resolveInstrumentationProvider as c9,TOOLKIT_INSTRUMENTATION_EVENT_MAP as l9}from"@pie-players/pie-players-shared/pie";import{isInstrumentationProvider as d9}from"@pie-players/pie-players-shared";import{createPieI18n as i9,DEFAULT_LOCALE as s9}from"@pie-players/pie-players-shared/i18n";function j1(Q){return{kind:Q.kind,severity:Q.severity??"error",source:Q.source,message:Q.message,details:[...Q.details||[]],recoverable:Q.recoverable===!0,cause:Q.cause}}function K1(Q){let G=Q.error instanceof Error&&Q.error.message.trim().length>0?Q.error.message:String(Q.error||"Unknown framework error");return j1({kind:Q.kind,source:Q.source,message:G,recoverable:Q.recoverable,cause:Q.error})}var U5={"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"};function G6(Q){let G=U5[Q.context.phase],Y=Q.context.providerId?`pie-toolkit-coordinator/${Q.context.providerId}`:`pie-toolkit-coordinator:${Q.context.phase}`;return K1({kind:G,source:Y,error:Q.error,recoverable:Q.recoverable})}function Y6(Q){let G=`[pie-framework:${Q.kind}:${Q.source}]`;if(Q.details.length===0)return`${G} ${Q.message}`;return`${G} ${Q.message}
|
|
2
2
|
- ${Q.details.join(`
|
|
3
|
-
- `)}`}var
|
|
4
|
-
`);throw Error(`[tool-config-validation:${
|
|
5
|
-
${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=o0(Y.toolRegistry),j=$7(Q),Z=[],q=Object.values(j.placement).some((_)=>_.length>0)||Object.keys(j.providers).length>0||(j.policy.allowed?.length??0)>0||(j.policy.blocked?.length??0)>0;if(X.size===0&&q)Z.push(g({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated. Pass `toolRegistry` — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let K=Object.hasOwn(j.providers,"tts"),B={...j.providers||{}};for(let _ of Object.keys(B).sort()){if(_==="tts"){delete B.tts;continue}let A=X.get(_);B[_]=a0(_,B[_],A,Z),t0(_,B[_],A,Z)}let U={...j,providers:B};if(e0(U,X,Z),Q3(U,X,Z),Y3(U,X,K,Z),K)t8(Z.filter((_)=>_.code==="tools.removedProviderKey"),G);if(J==="warn")a8(Z,G);let H=Z.filter((_)=>_.severity==="error");if(J==="error"&&H.length>0)t8(H,G);if(J==="error"&&H.length===0)a8(Z,G);return{config:U,diagnostics:Z}}var p1=(Q)=>Array.isArray(Q)&&Q.length>0;function g1(Q){if(Q.kind==="passage")return{ownerKind:"passage",assessmentId:Q.assessmentId,sectionId:Q.sectionId,passageId:Q.canonicalItemId||Q.itemId};return{ownerKind:"itemModel",assessmentId:Q.assessmentId,sectionId:Q.sectionId,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId}}function e8(Q,Y){if(!Q)return[];let J=g1(Y),G=[];if(p1(Q.accessibilityCatalogs))G.push({context:J,catalogs:Q.accessibilityCatalogs});if(p1(Q.config?.extractedCatalogs))G.push({context:J,catalogs:Q.config.extractedCatalogs});if(Y.kind==="passage")return G;if(J.ownerKind!=="itemModel")return G;for(let X of Q.config?.models??[]){if(!p1(X.accessibilityCatalogs))continue;G.push({context:{...J,modelId:X.id},catalogs:X.accessibilityCatalogs})}return G}var d1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),Q9=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),Y9=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),J9=new Set(["break","mark","lexicon"]);function J3(Q){let Y=Q;for(let J of J9){let G=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Y=Y.replace(G,(X,j)=>{let Z=j?j.replace(/\s+$/,""):"";return`<${J}${Z}></${J}>`})}return Y}var G3=[/^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 X3(Q){if(typeof Q!=="string"||Q.length===0)return!1;let Y;try{Y=new URL(Q)}catch{return!1}if(Y.protocol!=="http:"&&Y.protocol!=="https:")return!1;let J=Y.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!G3.some((G)=>G.test(J))}function c1(Q){let Y=Array.from(Q.children);for(let G of Y){let X=G.tagName.toLowerCase();if(Q9.has(X)){G.remove();continue}if(c1(G),!d1.has(X)){let j=Q.ownerDocument.createTextNode(G.textContent??"");G.replaceWith(j)}}let J=Array.from(Q.attributes).map((G)=>G.name);for(let G of J)if(!Y9.has(G.toLowerCase()))Q.removeAttribute(G);if(Q.tagName.toLowerCase()==="audio"){let G=Q.getAttribute("src");if(G!==null&&!X3(G))Q.removeAttribute("src")}}function l1(Q){let Y=Q.tagName.toLowerCase(),J=Array.from(Q.attributes).filter((X)=>Y9.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${Z3(X.value)}"`).join("");if(J9.has(Y))return`<${Y}${J}/>`;let G=[];for(let X of Array.from(Q.childNodes))if(X.nodeType===3)G.push(X1(X.nodeValue??""));else if(X.nodeType===1){let j=X,Z=j.tagName.toLowerCase();if(Q9.has(Z))continue;if(d1.has(Z))G.push(l1(j));else G.push(X1(j.textContent??""))}return`<${Y}${J}>${G.join("")}</${Y}>`}function i1(Q){let Y=String(Q||"").trim();if(!Y||!Y.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let G=new DOMParser().parseFromString(J3(Y),"text/html"),X=G.querySelector("speak");if(X)return c1(X),l1(X);let j=G.createElement("speak");for(let Z of Array.from(G.body.childNodes))j.appendChild(Z);return c1(j),Array.from(j.childNodes).map((Z)=>{if(Z.nodeType===3)return X1(Z.nodeValue??"");if(Z.nodeType===1){let q=Z;if(d1.has(q.tagName.toLowerCase()))return l1(q);return X1(q.textContent??"")}return""}).join("")}function X1(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Z3(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var q9=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),s1="ext:";function G9(Q){if(q9.has(Q))return!0;return Q.startsWith(s1)&&Q.length>s1.length}var X9=new Set;function n1(Q,Y=new Set){if(Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"||typeof Q>"u")return Q;if(typeof Q!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Y.has(Q))throw TypeError("catalog cards must not contain cycles");Y.add(Q);try{if(Array.isArray(Q))return Object.freeze(Q.map((X)=>n1(X,Y)));let J=Object.getPrototypeOf(Q);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let G={};for(let[X,j]of Object.entries(Q))G[X]=n1(j,Y);return Object.freeze(G)}finally{Y.delete(Q)}}function Z9(Q,Y,J){let G=`${Y}|${Q}`;if(X9.has(G))return;X9.add(G);let X=`${Array.from(q9).join(", ")}, or an "${s1}" prefixed vendor extension`;if(Y==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Q}"; 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 "${Q}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var j9=(Q)=>Q.payload!==void 0?"payload":"content";class r1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Q,Y="en-US"){this.defaultLanguage=Y,this.indexCatalogs(Q??[],"assessment")}setDefaultLanguage(Q){this.defaultLanguage=Q}onCatalogsChange(Q){return this.catalogChangeListeners.add(Q),()=>{this.catalogChangeListeners.delete(Q)}}emitCatalogsChange(Q){for(let Y of Array.from(this.catalogChangeListeners))try{Y(Q)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Q,Y){let J=Y==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let G of this.sanitizeCatalogs(Q)){if(J.has(G.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Y} catalog "${G.identifier}" ignored`);continue}J.set(G.identifier,G)}}insertScopedCatalogs(Q,Y){if(!Y||Y.length===0)return null;let J=this.getOwnerKey(Q),G=this.scopedCatalogs.get(J),X=G?.catalogs??new Map,j=[];for(let Z of this.sanitizeCatalogs(Y)){if(X.has(Z.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${Z.identifier}" ignored for ${J}`);continue}X.set(Z.identifier,Z),j.push(Z.identifier)}if(!G&&j.length>0)this.scopedCatalogs.set(J,{context:{...Q},catalogs:X});return{key:J,context:{...Q},catalogs:X,insertedIds:j}}removeScopedInsertion(Q){let Y=this.scopedCatalogs.get(Q.key);if(Y?.catalogs!==Q.catalogs)return!1;let J=!1;for(let G of Q.insertedIds)J=Y.catalogs.delete(G)||J;if(Y.catalogs.size===0)this.scopedCatalogs.delete(Q.key);return J}registerCatalogs(Q,Y){let J=this.insertScopedCatalogs(Q,Y);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});let G=!0;return()=>{if(!G)return;if(G=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}registerOwner(Q){let{owner:Y,entity:J}=Q,G=g1(Y),X=[],j=[];try{j=e8(J,Y)}catch(K){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",K)}for(let K of j)try{let B=this.insertScopedCatalogs(K.context,K.catalogs);if(B)X.push(B)}catch(B){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",B)}if(X.some((K)=>K.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:G});let q=!0;return()=>{if(!q)return;q=!1;let K=!1;for(let B of X)K=this.removeScopedInsertion(B)||K;if(K)this.emitCatalogsChange({reason:"scoped-removed",context:G})}}forOwner(Q){let Y={...Q};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Y),onChange:(J)=>this.onCatalogsChange((G)=>{if(this.catalogChangeAffectsOwner(G,Y))J()})})}addItemCatalogs(Q){if(!Q||Q.length===0)return;this.indexCatalogs(Q,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Q){return this.itemCatalogs.has(Q)||this.assessmentCatalogs.has(Q)||Array.from(this.scopedCatalogs.values()).some((Y)=>Y.catalogs.has(Q))}getAlternative(Q,Y){if(!G9(Y.type))Z9(Y.type,"lookup",Q);let J=Y.context?this.scopedCatalogs.get(this.getOwnerKey(Y.context))?.catalogs.get(Q):null;if(J){let j=this.findMatchingCard(J,Y);if(j)return this.resolveCard(Q,j,"item")}if(Y.context){let j=this.findScopedCandidates(Q,Y.context);if(j.length===1){let Z=this.findMatchingCard(j[0],Y);if(Z)return this.resolveCard(Q,Z,"item")}else if(j.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Q}" for owner context`,Y.context),null}let G=this.itemCatalogs.get(Q);if(G){let j=this.findMatchingCard(G,Y);if(j)return this.resolveCard(Q,j,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let j=this.findMatchingCard(X,Y);if(j)return this.resolveCard(Q,j,"assessment")}return null}resolveCard(Q,Y,J){return{catalogId:Q,type:Y.catalog,language:Y.language,content:Y.catalog==="spoken"&&Y.content!==void 0?this.ensureSpokenSanitized(Y.content):Y.content,payload:Y.payload,source:J}}ensureSpokenSanitized(Q){let Y=this.sanitizedSpokenCache.get(Q);if(Y!==void 0)return Y;let J=i1(Q);return this.sanitizedSpokenCache.set(Q,J),J}getOwnerKey(Q){return[Q.ownerKind,Q.assessmentId||"",Q.sectionId||"",Q.canonicalItemId||"",Q.itemId||"",Q.passageId||"",Q.modelId||""].join("|")}scopedCatalogEntries(){let Q=[];for(let Y of this.scopedCatalogs.values())for(let J of Y.catalogs.entries())Q.push(J);return Q}findScopedCandidates(Q,Y){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Y)).map((J)=>J.catalogs.get(Q)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Q,Y){if(Q.ownerKind!==Y.ownerKind)return!1;if(Y.assessmentId&&Q.assessmentId!==Y.assessmentId)return!1;if(Y.sectionId&&Q.sectionId!==Y.sectionId)return!1;if(Y.canonicalItemId&&Q.canonicalItemId!==Y.canonicalItemId)return!1;if(Y.itemId&&Q.itemId!==Y.itemId)return!1;if(Y.passageId&&Q.passageId!==Y.passageId)return!1;if(Y.modelId&&Q.modelId!==Y.modelId)return!1;return!0}ownerScopedCatalogEntries(Q){let Y=[],J=this.scopedCatalogs.get(this.getOwnerKey(Q));if(J)Y.push(...J.catalogs.entries());for(let G of this.scopedCatalogs.values()){if(G===J)continue;if(!this.isCompatibleOwnerContext(G.context,Q))continue;Y.push(...G.catalogs.entries())}return Y}createOwnerSnapshot(Q){let Y=[],J=this.ownerScopedCatalogEntries(Q);if(Q.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[G,X]of J)for(let j of X.cards)try{Y.push(Object.freeze({catalogId:G,card:n1(j)}))}catch(Z){let q=`${this.getOwnerKey(Q)}\x00${G}`;if(!this.reportedSnapshotProblems.has(q))this.reportedSnapshotProblems.add(q),console.warn(`[AccessibilityCatalogResolver] Catalog "${G}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,Z)}return Object.freeze({cards:Object.freeze(Y)})}catalogChangeAffectsOwner(Q,Y){if(!Q.context)return!1;if(this.isCompatibleOwnerContext(Q.context,Y))return!0;if(Y.ownerKind==="itemModel"&&Y.modelId&&Q.context.ownerKind==="itemModel"&&!Q.context.modelId)return this.isCompatibleOwnerContext({...Q.context,modelId:Y.modelId},Y);return!1}sanitizeCatalogs(Q){return Q.map((Y)=>({...Y,cards:Y.cards.map((J)=>{if(!G9(J.catalog))Z9(J.catalog,"card",Y.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?i1(J.content):J.content}})}))}findMatchingCard(Q,Y){let{type:J,language:G,useFallback:X=!0,form:j}=Y,Z=[];if(G)Z.push((q)=>q.language===G);if(X)Z.push((q)=>q.language===this.defaultLanguage),Z.push(()=>!0);for(let q of Z){let K=Q.cards.filter((B)=>B.catalog===J&&q(B));if(K.length===0)continue;if(j){let B=K.find((U)=>j9(U)===j);if(B)return B}return K[0]}return null}getAllAlternatives(Q){let Y=[],J=new Set,G=(Z,q)=>{let K=`${Z.catalog}|${Z.language??""}|${j9(Z)}`;if(J.has(K))return;J.add(K),Y.push(this.resolveCard(Q,Z,q))},X=this.itemCatalogs.get(Q);if(X)for(let Z of X.cards)G(Z,"item");let j=this.assessmentCatalogs.get(Q);if(j)for(let Z of j.cards)G(Z,"assessment");for(let[Z,q]of this.scopedCatalogEntries()){if(Z!==Q)continue;for(let K of q.cards)G(K,"item")}return Y}getAllCatalogIds(){let Q=this.scopedCatalogEntries().map(([Y])=>Y);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Q]))}getStatistics(){let Q=new Set,Y=new Set;for(let J of this.assessmentCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.itemCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.scopedCatalogs.values())for(let G of J.catalogs.values())for(let X of G.cards)if(Q.add(X.catalog),X.language)Y.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),availableTypes:Q,availableLanguages:Y}}hasAlternativeType(Q,Y){return this.getAllAlternatives(Q).some((G)=>G.type===Y)}getCatalogsByType(Q){let Y=new Set;for(let[J,G]of this.assessmentCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.itemCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.scopedCatalogEntries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);return Array.from(Y)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}class o1{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Q,Y,J,G){return`${Q}:${Y}:${J}:${G}`}parseGlobalElementId(Q){let Y=Q.split(":");if(Y.length!==4)return null;return{assessmentId:Y[0],sectionId:Y[1],itemId:Y[2],elementId:Y[3]}}setState(Q,Y,J){let G=this.elementStates.get(Q);if(!G)G=new Map,this.elementStates.set(Q,G);G.set(Y,J),this._notifyListeners(),this._notifyStateChange()}getState(Q,Y){return this.elementStates.get(Q)?.get(Y)}getElementState(Q){let Y=this.elementStates.get(Q);if(!Y)return{};return Object.fromEntries(Y.entries())}getAllState(){let Q={};for(let[Y,J]of this.elementStates.entries())Q[Y]=Object.fromEntries(J.entries());return Q}subscribe(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}_notifyListeners(){for(let Q of this.listeners)Q(this.elementStates)}setOnStateChange(Q){this.onStateChange=Q}_notifyStateChange(){if(this.onStateChange)this.onStateChange(this.getAllState())}loadState(Q){this.elementStates.clear();for(let[Y,J]of Object.entries(Q)){let G=new Map(Object.entries(J));this.elementStates.set(Y,G)}this._notifyListeners()}clearElement(Q){this.elementStates.delete(Q),this._notifyListeners(),this._notifyStateChange()}clearTool(Q){for(let Y of this.elementStates.values())Y.delete(Q);this._notifyListeners(),this._notifyStateChange()}clearSection(Q,Y){let J=`${Q}:${Y}:`,G=[];for(let X of this.elementStates.keys())if(X.startsWith(J))G.push(X);for(let X of G)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}class v7{listeners=new Set;subscribeFrameworkErrors(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}reportFrameworkError(Q){let Y=Array.from(this.listeners);for(let J of Y)try{J(Q)}catch(G){console.warn("[FrameworkErrorBus] listener failed:",G)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}class a1{serialize(Q,Y){return{startContainer:this.getNodePath(Q.startContainer,Y),startOffset:Q.startOffset,endContainer:this.getNodePath(Q.endContainer,Y),endOffset:Q.endOffset,text:Q.toString()}}deserialize(Q,Y){let J=this.findNodeByPath(Q.startContainer,Y),G=this.findNodeByPath(Q.endContainer,Y);if(!J||!G)return null;try{let X=new Range;if(X.setStart(J,Q.startOffset),X.setEnd(G,Q.endOffset),X.toString()===Q.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Q,Y){if(Q===Y)return"";if(Q.nodeType===Node.TEXT_NODE){let J=Q.parentElement;if(!J)throw Error("Text node has no parent");let X=Array.from(J.childNodes).filter((Z)=>Z.nodeType===Node.TEXT_NODE).indexOf(Q);return`${this.getElementPath(J,Y)}::text[${X}]`}if(Q.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Q,Y);throw Error(`Unsupported node type: ${Q.nodeType}`)}getElementPath(Q,Y){if(Q===Y)return"";let J=[],G=Q;while(G&&G!==Y){if(G.id){J.unshift(`#${G.id}`);break}let X=G.parentElement;if(!X)break;let j=Array.from(X.children).filter((K)=>K.tagName===G.tagName),Z=j.indexOf(G),q=j.length>1?`${G.tagName.toLowerCase()}:nth-of-type(${Z+1})`:G.tagName.toLowerCase();J.unshift(q),G=X}return J.join(" > ")}findNodeByPath(Q,Y){if(Q==="")return Y;if(Q.includes("::text[")){let[J,G]=Q.split("::text["),X=Number.parseInt(G.replace("]",""),10),j=J?Y.querySelector(J):Y;if(!j)return null;return Array.from(j.childNodes).filter((q)=>q.nodeType===Node.TEXT_NODE)[X]||null}try{return Y.querySelector(Q)}catch(J){return console.warn("Invalid selector path:",Q,J),null}}serializeMany(Q,Y){return Q.map((J)=>this.serialize(J,Y))}deserializeMany(Q,Y){return Q.map((J)=>this.deserialize(J,Y))}}var m;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(m||(m={}));var D7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(D7||(D7={}));class h7{config;ttsWordHighlight=null;ttsSentenceHighlight=null;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;colorHighlights=new Map;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;explicitTTSColorOverride=null;constructor(Q={}){if(this.config=Q,this.rangeSerializer=new a1,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 Q=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(Q),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let Y of document.querySelectorAll("pie-theme"))this.themeObserver.observe(Y,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(Q){if(!Q)return null;let Y=Q.trim();if(!Y)return null;let J=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(Y);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 G=/^rgba?\((.+)\)$/i.exec(Y);if(G){let j=G[1].replace(/\//g,",").split(/[,\s]+/).map((B)=>B.trim()).filter(Boolean),Z=Number(j[0]),q=Number(j[1]),K=Number(j[2]);if(Number.isFinite(Z)&&Number.isFinite(q)&&Number.isFinite(K))return[Z,q,K]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=Y,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let j=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let Z=j.trim();if(Z&&Z!==Y)return this.parseColor(j)}}return null}relativeLuminance([Q,Y,J]){let G=(q)=>{let K=q/255;return K<=0.03928?K/12.92:((K+0.055)/1.055)**2.4},X=G(Q),j=G(Y),Z=G(J);return 0.2126*X+0.7152*j+0.0722*Z}contrastRatio(Q,Y){let J=this.relativeLuminance(Q),G=this.relativeLuminance(Y),X=Math.max(J,G),j=Math.min(J,G);return(X+0.05)/(j+0.05)}blend(Q,Y,J){return[Math.round(Q[0]*J+Y[0]*(1-J)),Math.round(Q[1]*J+Y[1]*(1-J)),Math.round(Q[2]*J+Y[2]*(1-J))]}resolveAdaptiveTTSStyle(Q){let Y=[255,235,59],J=[17,24,39],G=[255,255,255],X=Q||(typeof document<"u"?document.documentElement:null),j=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,Z=this.parseColor(j?.getPropertyValue("--pie-background")||j?.backgroundColor)||G,q=this.parseColor(j?.getPropertyValue("--pie-text"))||J,K=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||Y:this.parseColor(j?.getPropertyValue("--pie-missing"))||Y,B=this.explicitTTSColorOverride?[Math.max(0.3,Math.min(0.95,this.explicitTTSColorOverride.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],U=B[B.length-1],H=-1/0;for(let l of B){let Z7=this.blend(K,Z,l),j7=this.contrastRatio(Z7,Z),P7=this.contrastRatio(Z7,q),q7=j7*1.2+P7*0.8;if(j7>=1.25&&P7>=2.4){U=l;break}if(q7>H)H=q7,U=l}let _=Math.max(0.24,Math.min(0.85,U*0.55)),A=Math.max(0.55,Math.min(0.95,U+0.2)),M=Math.max(0.22,Math.min(0.6,U*0.45)),O=q,L=this.blend(O,Z,A),F=this.contrastRatio(L,Z),$=this.relativeLuminance(Z)>0.45?[0,0,0]:[255,255,255],b=F>=1.35?O:$,v=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${U})`,k=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${_})`,p=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${A})`,w=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${M})`;return{wordHighlight:v,sentenceHighlight:k,wordUnderline:p,wordShadow:w}}applyAdaptiveTTSStyle(Q){if(typeof document>"u")return;let Y=this.resolveAdaptiveTTSStyle(Q);document.documentElement.style.setProperty("--pie-tts-word-highlight",Y.wordHighlight),document.documentElement.style.setProperty("--pie-tts-sentence-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-line-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-word-underline",Y.wordUnderline),document.documentElement.style.setProperty("--pie-tts-word-shadow",Y.wordShadow)}initializeHighlights(){if(!this.supported)return;this.ttsWordHighlight=new Highlight,this.ttsSentenceHighlight=new Highlight,CSS.highlights.set("tts-word",this.ttsWordHighlight),CSS.highlights.set("tts-sentence",this.ttsSentenceHighlight);for(let Q of Object.values(D7)){let Y=new Highlight;this.colorHighlights.set(Q,Y),CSS.highlights.set(`annotation-${Q}`,Y)}}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById("pie-highlight-styles"))return;let Q=document.createElement("style");Q.id="pie-highlight-styles",Q.textContent=`
|
|
3
|
+
- `)}`}var B5="error";function l1(Q){if(Q==="off"||Q==="warn"||Q==="error")return Q;return B5}function c(Q){return Q}function D5(Q){if(!Q)return new Map;return new Map(Q.getAllTools().slice().sort((G,Y)=>G.toolId.localeCompare(Y.toolId)).map((G)=>[G.toolId,G]))}function _5(Q,G,Y,J){if(!G||!Y?.provider?.sanitizeConfig)return G;try{let X=Y.provider.sanitizeConfig(G);if(!X||typeof X!=="object"||Array.isArray(X))return J.push(c({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer for "${Q}" must return an object.`,providerId:Q,toolId:Q})),G;return X}catch(X){return J.push(c({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q})),G}}function V5(Q,G,Y,J){if(!G||!Y?.provider?.validateConfig)return;try{let X=Y.provider.validateConfig(G);if(!Array.isArray(X)){J.push(c({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Q}`,message:`Provider validator for "${Q}" must return an array.`,providerId:Q,toolId:Q}));return}for(let j of X)J.push({...j,path:j.path||`providers.${Q}`,providerId:j.providerId||Q,toolId:j.toolId||Q})}catch(X){J.push(c({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Q}`,message:`Provider validator failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q}))}}function H5(Q,G,Y){if(G.size===0)return;let J=["section","item","passage"];for(let X of J)for(let j of Q.placement[X]){let Z=G.get(j);if(!Z){Y.push(c({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${j}" in placement.${X}.`,toolId:j}));continue}if(Z.activation==="region"){Y.push(c({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${j}" 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:j}));continue}let K=Z.supportedLevels.includes(X),W=X==="item"&&Z.supportedLevels.includes("section");if(!K&&!W)Y.push(c({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${j}" does not support level "${X}".`,toolId:j}))}}function F5(Q,G,Y){if(G.size===0)return;for(let J of Q.policy.allowed||[]){if(G.has(J))continue;Y.push(c({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${J}" in policy.allowed.`,toolId:J}))}for(let J of Q.policy.blocked||[]){if(G.has(J))continue;Y.push(c({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${J}" in policy.blocked.`,toolId:J}))}}function A5(Q,G,Y,J){if(Y)J.push(c({code:"tools.removedProviderKey",severity:"error",path:"providers.tts",message:'Provider key "tts" is no longer supported. Use "providers.textToSpeech".',providerId:"tts",toolId:"textToSpeech"}));for(let X of Object.keys(Q.providers).sort()){if(G.size===0||G.has(X))continue;J.push(c({code:"tools.unknownProviderKey",severity:"error",path:`providers.${X}`,message:`Unknown provider key "${X}".`,providerId:X,toolId:X}))}}function J6(Q,G){if(Q.length===0)return;for(let Y of Q){let J=`[tool-config-validation:${G}]`;console.warn(`${J} ${Y.path} - ${Y.message}`)}}function X6(Q,G){let Y=Q.map((J)=>`- ${J.path}: ${J.message}`).join(`
|
|
4
|
+
`);throw Error(`[tool-config-validation:${G}] Invalid tools config:
|
|
5
|
+
${Y}`)}function X7(Q,G={}){let Y=l1(G.strictness),J=G.source??"tools",X=D5(G.toolRegistry),j=R7(Q),Z=[],K=Object.values(j.placement).some((H)=>H.length>0)||Object.keys(j.providers).length>0||(j.policy.allowed?.length??0)>0||(j.policy.blocked?.length??0)>0;if(X.size===0&&K)Z.push(c({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated. Pass `toolRegistry` — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let W=Object.hasOwn(j.providers,"tts"),B={...j.providers||{}};for(let H of Object.keys(B).sort()){if(H==="tts"){delete B.tts;continue}let N=X.get(H);B[H]=_5(H,B[H],N,Z),V5(H,B[H],N,Z)}let U={...j,providers:B};if(H5(U,X,Z),F5(U,X,Z),A5(U,X,W,Z),W)X6(Z.filter((H)=>H.code==="tools.removedProviderKey"),J);if(Y==="warn")J6(Z,J);let V=Z.filter((H)=>H.severity==="error");if(Y==="error"&&V.length>0)X6(V,J);if(Y==="error"&&V.length===0)J6(Z,J);return{config:U,diagnostics:Z}}import{languageTagLookupSequence as P5,normalizeLanguageTag as W6}from"@pie-players/pie-players-shared/i18n/language-tags";var d1=(Q)=>Array.isArray(Q)&&Q.length>0;function i1(Q){if(Q.kind==="passage")return{ownerKind:"passage",assessmentId:Q.assessmentId,sectionId:Q.sectionId,passageId:Q.canonicalItemId||Q.itemId};return{ownerKind:"itemModel",assessmentId:Q.assessmentId,sectionId:Q.sectionId,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId}}function Z6(Q,G){if(!Q)return[];let Y=i1(G),J=[];if(d1(Q.accessibilityCatalogs))J.push({context:Y,catalogs:Q.accessibilityCatalogs});if(d1(Q.config?.extractedCatalogs))J.push({context:Y,catalogs:Q.config.extractedCatalogs});if(G.kind==="passage")return J;if(Y.ownerKind!=="itemModel")return J;for(let X of Q.config?.models??[]){if(!d1(X.accessibilityCatalogs))continue;J.push({context:{...Y,modelId:X.id},catalogs:X.accessibilityCatalogs})}return J}var r1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),j6=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),K6=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),q6=new Set(["break","mark","lexicon"]);function N5(Q){let G=Q;for(let Y of q6){let J=new RegExp(`<${Y}\\b([^>/]*?)\\s*/>`,"gi");G=G.replace(J,(X,j)=>{let Z=j?j.replace(/\s+$/,""):"";return`<${Y}${Z}></${Y}>`})}return G}var M5=[/^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 O5(Q){if(typeof Q!=="string"||Q.length===0)return!1;let G;try{G=new URL(Q)}catch{return!1}if(G.protocol!=="http:"&&G.protocol!=="https:")return!1;let Y=G.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!M5.some((J)=>J.test(Y))}function s1(Q){let G=Array.from(Q.children);for(let J of G){let X=J.tagName.toLowerCase();if(j6.has(X)){J.remove();continue}if(s1(J),!r1.has(X)){let j=Q.ownerDocument.createTextNode(J.textContent??"");J.replaceWith(j)}}let Y=Array.from(Q.attributes).map((J)=>J.name);for(let J of Y)if(!K6.has(J.toLowerCase()))Q.removeAttribute(J);if(Q.tagName.toLowerCase()==="audio"){let J=Q.getAttribute("src");if(J!==null&&!O5(J))Q.removeAttribute("src")}}function n1(Q){let G=Q.tagName.toLowerCase(),Y=Array.from(Q.attributes).filter((X)=>K6.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${z5(X.value)}"`).join("");if(q6.has(G))return`<${G}${Y}/>`;let J=[];for(let X of Array.from(Q.childNodes))if(X.nodeType===3)J.push(q1(X.nodeValue??""));else if(X.nodeType===1){let j=X,Z=j.tagName.toLowerCase();if(j6.has(Z))continue;if(r1.has(Z))J.push(n1(j));else J.push(q1(j.textContent??""))}return`<${G}${Y}>${J.join("")}</${G}>`}function o1(Q){let G=String(Q||"").trim();if(!G||!G.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let J=new DOMParser().parseFromString(N5(G),"text/html"),X=J.querySelector("speak");if(X)return s1(X),n1(X);let j=J.createElement("speak");for(let Z of Array.from(J.body.childNodes))j.appendChild(Z);return s1(j),Array.from(j.childNodes).map((Z)=>{if(Z.nodeType===3)return q1(Z.nodeValue??"");if(Z.nodeType===1){let K=Z;if(r1.has(K.tagName.toLowerCase()))return n1(K);return q1(K.textContent??"")}return""}).join("")}function q1(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function z5(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var V6=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),a1="ext:";function U6(Q){if(V6.has(Q))return!0;return Q.startsWith(a1)&&Q.length>a1.length}var B6=new Set;function t1(Q,G=new Set){if(Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"||typeof Q>"u")return Q;if(typeof Q!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(G.has(Q))throw TypeError("catalog cards must not contain cycles");G.add(Q);try{if(Array.isArray(Q))return Object.freeze(Q.map((X)=>t1(X,G)));let Y=Object.getPrototypeOf(Q);if(Y!==Object.prototype&&Y!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let J={};for(let[X,j]of Object.entries(Q))J[X]=t1(j,G);return Object.freeze(J)}finally{G.delete(Q)}}function D6(Q,G,Y){let J=`${G}|${Q}`;if(B6.has(J))return;B6.add(J);let X=`${Array.from(V6).join(", ")}, or an "${a1}" prefixed vendor extension`;if(G==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${Y}" has a card of unknown type "${Q}"; 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 "${Q}" on "${Y}" cannot match any card. Expected one of: ${X}.`)}var _6=(Q)=>Q.payload!==void 0?"payload":"content";class e1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Q,G="en-US"){this.defaultLanguage=G,this.indexCatalogs(Q??[],"assessment")}setDefaultLanguage(Q){this.defaultLanguage=Q}onCatalogsChange(Q){return this.catalogChangeListeners.add(Q),()=>{this.catalogChangeListeners.delete(Q)}}emitCatalogsChange(Q){for(let G of Array.from(this.catalogChangeListeners))try{G(Q)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Q,G){let Y=G==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let J of this.sanitizeCatalogs(Q)){if(Y.has(J.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${G} catalog "${J.identifier}" ignored`);continue}Y.set(J.identifier,J)}}insertScopedCatalogs(Q,G){if(!G||G.length===0)return null;let Y=this.getOwnerKey(Q),J=this.scopedCatalogs.get(Y),X=J?.catalogs??new Map,j=[];for(let Z of this.sanitizeCatalogs(G)){if(X.has(Z.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${Z.identifier}" ignored for ${Y}`);continue}X.set(Z.identifier,Z),j.push(Z.identifier)}if(!J&&j.length>0)this.scopedCatalogs.set(Y,{context:{...Q},catalogs:X});return{key:Y,context:{...Q},catalogs:X,insertedIds:j}}removeScopedInsertion(Q){let G=this.scopedCatalogs.get(Q.key);if(G?.catalogs!==Q.catalogs)return!1;let Y=!1;for(let J of Q.insertedIds)Y=G.catalogs.delete(J)||Y;if(G.catalogs.size===0)this.scopedCatalogs.delete(Q.key);return Y}registerCatalogs(Q,G){let Y=this.insertScopedCatalogs(Q,G);if(Y&&Y.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});let J=!0;return()=>{if(!J)return;if(J=!1,Y&&this.removeScopedInsertion(Y))this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}registerOwner(Q){let{owner:G,entity:Y}=Q,J=i1(G),X=[],j=[];try{j=Z6(Y,G)}catch(W){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",W)}for(let W of j)try{let B=this.insertScopedCatalogs(W.context,W.catalogs);if(B)X.push(B)}catch(B){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",B)}if(X.some((W)=>W.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:J});let K=!0;return()=>{if(!K)return;K=!1;let W=!1;for(let B of X)W=this.removeScopedInsertion(B)||W;if(W)this.emitCatalogsChange({reason:"scoped-removed",context:J})}}forOwner(Q){let G={...Q};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(G),onChange:(Y)=>this.onCatalogsChange((J)=>{if(this.catalogChangeAffectsOwner(J,G))Y()})})}addItemCatalogs(Q){if(!Q||Q.length===0)return;this.indexCatalogs(Q,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Q){return this.itemCatalogs.has(Q)||this.assessmentCatalogs.has(Q)||Array.from(this.scopedCatalogs.values()).some((G)=>G.catalogs.has(Q))}getAlternative(Q,G){if(!U6(G.type))D6(G.type,"lookup",Q);let Y=G.context?this.scopedCatalogs.get(this.getOwnerKey(G.context))?.catalogs.get(Q):null;if(Y){let j=this.findMatchingCard(Y,G);if(j)return this.resolveCard(Q,j,"item")}if(G.context){let j=this.findScopedCandidates(Q,G.context);if(j.length===1){let Z=this.findMatchingCard(j[0],G);if(Z)return this.resolveCard(Q,Z,"item")}else if(j.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Q}" for owner context`,G.context),null}let J=this.itemCatalogs.get(Q);if(J){let j=this.findMatchingCard(J,G);if(j)return this.resolveCard(Q,j,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let j=this.findMatchingCard(X,G);if(j)return this.resolveCard(Q,j,"assessment")}return null}resolveCard(Q,G,Y){return{catalogId:Q,type:G.catalog,language:G.language,content:G.catalog==="spoken"&&G.content!==void 0?this.ensureSpokenSanitized(G.content):G.content,payload:G.payload,source:Y}}ensureSpokenSanitized(Q){let G=this.sanitizedSpokenCache.get(Q);if(G!==void 0)return G;let Y=o1(Q);return this.sanitizedSpokenCache.set(Q,Y),Y}getOwnerKey(Q){return[Q.ownerKind,Q.assessmentId||"",Q.sectionId||"",Q.canonicalItemId||"",Q.itemId||"",Q.passageId||"",Q.modelId||""].join("|")}scopedCatalogEntries(){let Q=[];for(let G of this.scopedCatalogs.values())for(let Y of G.catalogs.entries())Q.push(Y);return Q}findScopedCandidates(Q,G){return Array.from(this.scopedCatalogs.values()).filter((Y)=>this.isCompatibleOwnerContext(Y.context,G)).map((Y)=>Y.catalogs.get(Q)).filter((Y)=>Boolean(Y))}isCompatibleOwnerContext(Q,G){if(Q.ownerKind!==G.ownerKind)return!1;if(G.assessmentId&&Q.assessmentId!==G.assessmentId)return!1;if(G.sectionId&&Q.sectionId!==G.sectionId)return!1;if(G.canonicalItemId&&Q.canonicalItemId!==G.canonicalItemId)return!1;if(G.itemId&&Q.itemId!==G.itemId)return!1;if(G.passageId&&Q.passageId!==G.passageId)return!1;if(G.modelId&&Q.modelId!==G.modelId)return!1;return!0}ownerScopedCatalogEntries(Q){let G=[],Y=this.scopedCatalogs.get(this.getOwnerKey(Q));if(Y)G.push(...Y.catalogs.entries());for(let J of this.scopedCatalogs.values()){if(J===Y)continue;if(!this.isCompatibleOwnerContext(J.context,Q))continue;G.push(...J.catalogs.entries())}return G}createOwnerSnapshot(Q){let G=[],Y=this.ownerScopedCatalogEntries(Q);if(Q.ownerKind==="global")Y.push(...this.assessmentCatalogs.entries());for(let[J,X]of Y)for(let j of X.cards)try{G.push(Object.freeze({catalogId:J,card:t1(j)}))}catch(Z){let K=`${this.getOwnerKey(Q)}\x00${J}`;if(!this.reportedSnapshotProblems.has(K))this.reportedSnapshotProblems.add(K),console.warn(`[AccessibilityCatalogResolver] Catalog "${J}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,Z)}return Object.freeze({cards:Object.freeze(G)})}catalogChangeAffectsOwner(Q,G){if(!Q.context)return!1;if(this.isCompatibleOwnerContext(Q.context,G))return!0;if(G.ownerKind==="itemModel"&&G.modelId&&Q.context.ownerKind==="itemModel"&&!Q.context.modelId)return this.isCompatibleOwnerContext({...Q.context,modelId:G.modelId},G);return!1}sanitizeCatalogs(Q){return Q.map((G)=>({...G,cards:G.cards.map((Y)=>{if(!U6(Y.catalog))D6(Y.catalog,"card",G.identifier);return{...Y,content:Y.catalog==="spoken"&&Y.content!==void 0?o1(Y.content):Y.content}})}))}findMatchingCard(Q,G){let{type:Y,language:J,useFallback:X=!0,form:j}=G,Z=[],K=(W)=>{for(let B of P5(W))Z.push((U)=>W6(U.language)===B)};if(J)K(J);if(X)K(this.defaultLanguage),Z.push(()=>!0);for(let W of Z){let B=Q.cards.filter((U)=>U.catalog===Y&&W(U));if(B.length===0)continue;if(j){let U=B.find((V)=>_6(V)===j);if(U)return U}return B[0]}return null}getAllAlternatives(Q){let G=[],Y=new Set,J=(Z,K)=>{let W=`${Z.catalog}|${W6(Z.language)}|${_6(Z)}`;if(Y.has(W))return;Y.add(W),G.push(this.resolveCard(Q,Z,K))},X=this.itemCatalogs.get(Q);if(X)for(let Z of X.cards)J(Z,"item");let j=this.assessmentCatalogs.get(Q);if(j)for(let Z of j.cards)J(Z,"assessment");for(let[Z,K]of this.scopedCatalogEntries()){if(Z!==Q)continue;for(let W of K.cards)J(W,"item")}return G}getAllCatalogIds(){let Q=this.scopedCatalogEntries().map(([G])=>G);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Q]))}getStatistics(){let Q=new Set,G=new Set;for(let Y of this.assessmentCatalogs.values())for(let J of Y.cards)if(Q.add(J.catalog),J.language)G.add(J.language);for(let Y of this.itemCatalogs.values())for(let J of Y.cards)if(Q.add(J.catalog),J.language)G.add(J.language);for(let Y of this.scopedCatalogs.values())for(let J of Y.catalogs.values())for(let X of J.cards)if(Q.add(X.catalog),X.language)G.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((Y,J)=>Y+J.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((Y,J)=>Y+J.catalogs.size,0),availableTypes:Q,availableLanguages:G}}hasAlternativeType(Q,G){return this.getAllAlternatives(Q).some((J)=>J.type===G)}getCatalogsByType(Q){let G=new Set;for(let[Y,J]of this.assessmentCatalogs.entries())if(J.cards.some((X)=>X.catalog===Q))G.add(Y);for(let[Y,J]of this.itemCatalogs.entries())if(J.cards.some((X)=>X.catalog===Q))G.add(Y);for(let[Y,J]of this.scopedCatalogEntries())if(J.cards.some((X)=>X.catalog===Q))G.add(Y);return Array.from(G)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}class Q8{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Q,G,Y,J){return`${Q}:${G}:${Y}:${J}`}parseGlobalElementId(Q){let G=Q.split(":");if(G.length!==4)return null;return{assessmentId:G[0],sectionId:G[1],itemId:G[2],elementId:G[3]}}setState(Q,G,Y){let J=this.elementStates.get(Q);if(!J)J=new Map,this.elementStates.set(Q,J);J.set(G,Y),this._notifyListeners(),this._notifyStateChange()}getState(Q,G){return this.elementStates.get(Q)?.get(G)}getElementState(Q){let G=this.elementStates.get(Q);if(!G)return{};return Object.fromEntries(G.entries())}getAllState(){let Q={};for(let[G,Y]of this.elementStates.entries())Q[G]=Object.fromEntries(Y.entries());return Q}subscribe(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}_notifyListeners(){for(let Q of this.listeners)Q(this.elementStates)}setOnStateChange(Q){this.onStateChange=Q}_notifyStateChange(){if(this.onStateChange)this.onStateChange(this.getAllState())}loadState(Q){this.elementStates.clear();for(let[G,Y]of Object.entries(Q)){let J=new Map(Object.entries(Y));this.elementStates.set(G,J)}this._notifyListeners()}clearElement(Q){this.elementStates.delete(Q),this._notifyListeners(),this._notifyStateChange()}clearTool(Q){for(let G of this.elementStates.values())G.delete(Q);this._notifyListeners(),this._notifyStateChange()}clearSection(Q,G){let Y=`${Q}:${G}:`,J=[];for(let X of this.elementStates.keys())if(X.startsWith(Y))J.push(X);for(let X of J)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}class m7{listeners=new Set;subscribeFrameworkErrors(Q){this.listeners.add(Q);let G=!0;return()=>{if(!G)return;G=!1,this.listeners.delete(Q)}}reportFrameworkError(Q){let G=Array.from(this.listeners);for(let Y of G)try{Y(Q)}catch(J){console.warn("[FrameworkErrorBus] listener failed:",J)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}class G8{serialize(Q,G){return{startContainer:this.getNodePath(Q.startContainer,G),startOffset:Q.startOffset,endContainer:this.getNodePath(Q.endContainer,G),endOffset:Q.endOffset,text:Q.toString()}}deserialize(Q,G){let Y=this.findNodeByPath(Q.startContainer,G),J=this.findNodeByPath(Q.endContainer,G);if(!Y||!J)return null;try{let X=new Range;if(X.setStart(Y,Q.startOffset),X.setEnd(J,Q.endOffset),X.toString()===Q.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Q,G){if(Q===G)return"";if(Q.nodeType===Node.TEXT_NODE){let Y=Q.parentElement;if(!Y)throw Error("Text node has no parent");let X=Array.from(Y.childNodes).filter((Z)=>Z.nodeType===Node.TEXT_NODE).indexOf(Q);return`${this.getElementPath(Y,G)}::text[${X}]`}if(Q.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Q,G);throw Error(`Unsupported node type: ${Q.nodeType}`)}getElementPath(Q,G){if(Q===G)return"";let Y=[],J=Q;while(J&&J!==G){if(J.id){Y.unshift(`#${J.id}`);break}let X=J.parentElement;if(!X)break;let j=Array.from(X.children).filter((W)=>W.tagName===J.tagName),Z=j.indexOf(J),K=j.length>1?`${J.tagName.toLowerCase()}:nth-of-type(${Z+1})`:J.tagName.toLowerCase();Y.unshift(K),J=X}return Y.join(" > ")}findNodeByPath(Q,G){if(Q==="")return G;if(Q.includes("::text[")){let[Y,J]=Q.split("::text["),X=Number.parseInt(J.replace("]",""),10),j=Y?G.querySelector(Y):G;if(!j)return null;return Array.from(j.childNodes).filter((K)=>K.nodeType===Node.TEXT_NODE)[X]||null}try{return G.querySelector(Q)}catch(Y){return console.warn("Invalid selector path:",Q,Y),null}}serializeMany(Q,G){return Q.map((Y)=>this.serialize(Y,G))}deserializeMany(Q,G){return Q.map((Y)=>this.deserialize(Y,G))}}var u;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(u||(u={}));var _7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(_7||(_7={}));class u7{config;ttsWordHighlight=null;ttsSentenceHighlight=null;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;colorHighlights=new Map;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;explicitTTSColorOverride=null;constructor(Q={}){if(this.config=Q,this.rangeSerializer=new G8,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 Q=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(Q),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let G of document.querySelectorAll("pie-theme"))this.themeObserver.observe(G,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(Q){if(!Q)return null;let G=Q.trim();if(!G)return null;let Y=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(G);if(Y){let X=Y[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 J=/^rgba?\((.+)\)$/i.exec(G);if(J){let j=J[1].replace(/\//g,",").split(/[,\s]+/).map((B)=>B.trim()).filter(Boolean),Z=Number(j[0]),K=Number(j[1]),W=Number(j[2]);if(Number.isFinite(Z)&&Number.isFinite(K)&&Number.isFinite(W))return[Z,K,W]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=G,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let j=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let Z=j.trim();if(Z&&Z!==G)return this.parseColor(j)}}return null}relativeLuminance([Q,G,Y]){let J=(K)=>{let W=K/255;return W<=0.03928?W/12.92:((W+0.055)/1.055)**2.4},X=J(Q),j=J(G),Z=J(Y);return 0.2126*X+0.7152*j+0.0722*Z}contrastRatio(Q,G){let Y=this.relativeLuminance(Q),J=this.relativeLuminance(G),X=Math.max(Y,J),j=Math.min(Y,J);return(X+0.05)/(j+0.05)}blend(Q,G,Y){return[Math.round(Q[0]*Y+G[0]*(1-Y)),Math.round(Q[1]*Y+G[1]*(1-Y)),Math.round(Q[2]*Y+G[2]*(1-Y))]}resolveAdaptiveTTSStyle(Q){let G=[255,235,59],Y=[17,24,39],J=[255,255,255],X=Q||(typeof document<"u"?document.documentElement:null),j=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,Z=this.parseColor(j?.getPropertyValue("--pie-background")||j?.backgroundColor)||J,K=this.parseColor(j?.getPropertyValue("--pie-text"))||Y,W=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||G:this.parseColor(j?.getPropertyValue("--pie-missing"))||G,B=this.explicitTTSColorOverride?[Math.max(0.3,Math.min(0.95,this.explicitTTSColorOverride.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],U=B[B.length-1],V=-1/0;for(let g of B){let j7=this.blend(W,Z,g),K7=this.contrastRatio(j7,Z),q7=this.contrastRatio(j7,K),$7=K7*1.2+q7*0.8;if(K7>=1.25&&q7>=2.4){U=g;break}if($7>V)V=$7,U=g}let H=Math.max(0.24,Math.min(0.85,U*0.55)),N=Math.max(0.55,Math.min(0.95,U+0.2)),O=Math.max(0.22,Math.min(0.6,U*0.45)),P=K,$=this.blend(P,Z,N),F=this.contrastRatio($,Z),L=this.relativeLuminance(Z)>0.45?[0,0,0]:[255,255,255],C=F>=1.35?P:L,v=`rgba(${W[0]}, ${W[1]}, ${W[2]}, ${U})`,I=`rgba(${W[0]}, ${W[1]}, ${W[2]}, ${H})`,p=`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${N})`,E=`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${O})`;return{wordHighlight:v,sentenceHighlight:I,wordUnderline:p,wordShadow:E}}applyAdaptiveTTSStyle(Q){if(typeof document>"u")return;let G=this.resolveAdaptiveTTSStyle(Q);document.documentElement.style.setProperty("--pie-tts-word-highlight",G.wordHighlight),document.documentElement.style.setProperty("--pie-tts-sentence-highlight",G.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-line-highlight",G.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-word-underline",G.wordUnderline),document.documentElement.style.setProperty("--pie-tts-word-shadow",G.wordShadow)}initializeHighlights(){if(!this.supported)return;this.ttsWordHighlight=new Highlight,this.ttsSentenceHighlight=new Highlight,CSS.highlights.set("tts-word",this.ttsWordHighlight),CSS.highlights.set("tts-sentence",this.ttsSentenceHighlight);for(let Q of Object.values(_7)){let G=new Highlight;this.colorHighlights.set(Q,G),CSS.highlights.set(`annotation-${Q}`,G)}}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById("pie-highlight-styles"))return;let Q=document.createElement("style");Q.id="pie-highlight-styles",Q.textContent=`
|
|
6
6
|
/* TTS highlights - temporary */
|
|
7
7
|
::highlight(tts-word) {
|
|
8
8
|
background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
|
|
@@ -212,14 +212,14 @@ ${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=o0(Y.too
|
|
|
212
212
|
text-shadow: none;
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
|
-
`,document.head.appendChild(Q)}highlightTTSWord(Q,Y,J){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q.parentElement),this.clearTTSWord();let G=document.createRange();G.setStart(Q,Y),G.setEnd(Q,J),this.ttsWordHighlight.add(G)}highlightTTSWordElement(Q){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q),this.clearTTSWord(),Q.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Q)}highlightTTSSentence(Q){if(!this.ttsSentenceHighlight)return;let Y=Q[0]?.startContainer,J=Y?.nodeType===Node.ELEMENT_NODE?Y:Y?.parentElement;this.applyAdaptiveTTSStyle(J),this.clearTTSSentence();for(let G of Q)this.ttsSentenceHighlight.add(G);this.highlightTTSElementFallbacks(Q)}highlightTTSSentenceElements(Q){if(!this.ttsSentenceHighlight)return;this.applyAdaptiveTTSStyle(Q[0]||null),this.clearTTSSentence();for(let Y of Q)Y.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(Y)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,h7.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-word-element",this.ttsWordElementHighlights,h7.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Q,Y,J,G){for(let X of Q){let j=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!j)continue;let Z=[],q=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,K=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let B of[q,K]){let U=B;while(U){if(U.matches?.(G))Z.push(U);U=U.parentElement}}if(j.matches?.(G))Z.push(j);Z.push(...Array.from(j.querySelectorAll(G)));for(let B of new Set(Z)){try{if(!X.intersectsNode(B)&&!B.contains(q)&&!B.contains(K))continue}catch{continue}B.setAttribute(Y,"true"),J.add(B)}}}clearTTSWord(){if(!this.ttsWordHighlight)return;this.ttsWordHighlight.clear();for(let Q of this.ttsWordElementHighlights)Q.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.ttsSentenceHighlight)return;this.ttsSentenceHighlight.clear();for(let Q of this.ttsSentenceElementHighlights)Q.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){this.clearTTSWord(),this.clearTTSSentence()}addAnnotation(Q,Y=D7.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,G=Q.cloneRange(),X={id:J,range:G,type:m.ANNOTATION,color:Y,timestamp:Date.now()};this.annotations.set(J,X);let j=this.colorHighlights.get(Y);if(j)j.add(G);return J}removeAnnotation(Q){let Y=this.annotations.get(Q);if(!Y){console.warn(`[HighlightCoordinator] Annotation ${Q} not found`);return}console.log(`[HighlightCoordinator] Removing annotation ${Q} (color: ${Y.color})`);let J=this.colorHighlights.get(Y.color);if(J){let G=J.delete(Y.range);console.log("[HighlightCoordinator] Highlight.delete() returned:",G)}this.annotations.delete(Q),console.log(`[HighlightCoordinator] Annotation ${Q} removed from map. Remaining:`,this.annotations.size)}clearAnnotations(){for(let Q of this.colorHighlights.values())Q.clear();this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Q){return this.annotations.get(Q)??null}changeAnnotationColor(Q,Y){let J=this.annotations.get(Q);if(!J)return;let G=J.color;if(G===Y)return;let X=this.colorHighlights.get(G);if(X)X.delete(J.range);J.color=Y;let j=this.colorHighlights.get(Y);if(j)j.add(J.range)}exportAnnotations(Q=document.body){return this.getAnnotations().map((Y)=>({...this.rangeSerializer.serialize(Y.range,Q),id:Y.id,color:Y.color,timestamp:Y.timestamp}))}importAnnotations(Q,Y=document.body){let J=0;for(let G of Q){let X=this.rangeSerializer.deserialize(G,Y);if(X)this.addAnnotation(X,G.color),J++}return J}highlightRange(Q,Y,J=D7.YELLOW){if(!this.supported)return;switch(Y){case m.TTS_WORD:case m.TTS_SENTENCE:{let G=Y===m.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(G){if(G.clear(),G.add(Q),Y===m.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case m.ANNOTATION:this.addAnnotation(Q,J);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case m.TTS_WORD:this.clearTTSWord();break;case m.TTS_SENTENCE:this.clearTTSSentence();break;case m.ANNOTATION:this.clearAnnotations();break}}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}isSupported(){return this.supported}updateTTSHighlightStyle(Q,Y){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById("pie-highlight-styles"))return;let X=((j)=>{let Z=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(j);return Z?{r:parseInt(Z[1],16),g:parseInt(Z[2],16),b:parseInt(Z[3],16)}:null})(Q);if(!X)return;this.explicitTTSColorOverride={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,Y))},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),typeof document<"u"){let Q=document.getElementById("pie-highlight-styles");if(Q)Q.remove()}this.themeObserver?.disconnect(),this.themeObserver=null}}function K9(Q){return(...Y)=>{console.debug(`[${Q}]`,...Y)}}var o=K9("ToolCoordinator"),X7;(function(Q){Q[Q.BASE=0]="BASE",Q[Q.TOOL=1000]="TOOL",Q[Q.MODAL=2000]="MODAL",Q[Q.CONTROL=3000]="CONTROL",Q[Q.HIGHLIGHT=4000]="HIGHLIGHT"})(X7||(X7={}));class t1{config;tools=new Map;layerCounters=new Map;listeners=new Set;visibilityState=new Map;constructor(Q={}){this.config=Q,this.layerCounters.set(X7.BASE,0),this.layerCounters.set(X7.TOOL,0),this.layerCounters.set(X7.MODAL,0),this.layerCounters.set(X7.CONTROL,0),this.layerCounters.set(X7.HIGHLIGHT,0)}subscribe(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}notifyListeners(){this.listeners.forEach((Q)=>Q())}registerTool(Q,Y,J,G=X7.MODAL){if(o("registerTool called:",{id:Q,name:Y,hasElement:!!J,layer:G}),this.tools.has(Q)){o(`Tool ${Q} is already registered`);return}let X=this.visibilityState.get(Q)??!1;if(!J){this.tools.set(Q,{id:Q,name:Y,element:null,layer:G,isVisible:X,baseZIndex:G}),o("Tool registered without element:",Q);return}let j=G+this.getNextLayerOffset(G);J.style.zIndex=String(j),J.style.display=X?"":"none";let Z=()=>this.bringToFront(J);if(J.addEventListener("mousedown",Z),this.tools.set(Q,{id:Q,name:Y,element:J,layer:G,isVisible:X,baseZIndex:j,mouseDownHandler:Z}),X)this.bringToFront(J);o("Tool registered with element:",Q)}unregisterTool(Q){let Y=this.tools.get(Q);if(!Y)return;if(Y.element&&Y.mouseDownHandler)Y.element.removeEventListener("mousedown",Y.mouseDownHandler);this.tools.delete(Q)}releaseTool(Q){this.unregisterTool(Q),this.visibilityState.delete(Q)}showTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="",this.bringToFront(Y.element);Y.isVisible=!0,this.visibilityState.set(Q,!0),this.notifyListeners()}hideTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="none";Y.isVisible=!1,this.visibilityState.set(Q,!1),this.notifyListeners()}toggleTool(Q){o("toggleTool called for:",Q);let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found. Registered tools:`,Array.from(this.tools.keys()));return}if(o("Tool found, current visibility:",Y.isVisible),Y.isVisible)this.hideTool(Q);else this.showTool(Q)}isToolVisible(Q){let Y=this.tools.get(Q);if(Y)return Y.isVisible;return this.visibilityState.get(Q)??!1}bringToFront(Q){let Y=Array.from(this.tools.values()).find((X)=>X.element===Q);if(!Y)return;let J=this.getMaxZIndexInLayer(Y.layer),G=Math.max(J+1,Y.layer+1);Q.style.zIndex=String(G),Y.baseZIndex=G}getRegisteredTools(){return Array.from(this.tools.keys())}getToolElement(Q){return this.tools.get(Q)?.element??null}getNextLayerOffset(Q){let Y=this.layerCounters.get(Q)??0;return this.layerCounters.set(Q,Y+1),Y}getMaxZIndexInLayer(Q){let Y=Q;for(let J of this.tools.values())if(J.layer===Q)Y=Math.max(Y,J.baseZIndex);return Y}resetZIndices(){for(let Q of this.tools.values())if(Q.element)Q.element.style.zIndex=String(Q.baseZIndex)}updateToolElement(Q,Y){let J=this.tools.get(Q);if(!J){o(`Tool ${Q} not found`);return}if(J.element&&J.mouseDownHandler)J.element.removeEventListener("mousedown",J.mouseDownHandler);let G=()=>this.bringToFront(Y);if(Y.addEventListener("mousedown",G),J.element=Y,J.mouseDownHandler=G,Y.style.zIndex=String(J.baseZIndex),J.isVisible)Y.style.display="";else Y.style.display="none"}hideAllTools(){for(let Q of this.tools.keys())this.hideTool(Q);this.notifyListeners()}getToolState(Q){let Y=this.tools.get(Q);if(!Y)return;return{id:Y.id,name:Y.name,isVisible:Y.isVisible,element:Y.element??null,layer:Y.layer}}getVisibleTools(){return Array.from(this.tools.values()).filter((Q)=>Q.isVisible).map((Q)=>({id:Q.id,name:Q.name,isVisible:Q.isVisible,element:Q.element??null,layer:Q.layer}))}}var j3=/^[a-z][a-z0-9+.-]*:/i,q3=new Set(["http:","https:","data:","blob:"]);function K3(Q){if(typeof Q!=="string")return!1;let Y=Q.trim();if(!Y)return!1;if(Y.startsWith("//")||!j3.test(Y))return!0;let J=Y.slice(0,Y.indexOf(":")+1).toLowerCase();return q3.has(J)}function W9(Q){if(!Array.isArray(Q))return[];let Y=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J;if(!K3(G.src))continue;let X={src:G.src.trim()};if(typeof G.type==="string"&&G.type.trim())X.type=G.type.trim();if(Number.isFinite(G.width))X.width=G.width;if(Number.isFinite(G.height))X.height=G.height;if(Y.some((j)=>j.src===X.src))continue;Y.push(X)}return Y}function U9(Q){if(!Q||typeof Q!=="object")return;let Y=Q,J=Number(Y.startSeconds);if(!Number.isFinite(J)||J<0)return;let G=Number(Y.endSeconds);if(!Number.isFinite(G)||G<=J)return{startSeconds:J};return{startSeconds:J,endSeconds:G}}function B9(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}function D9(Q,Y){if(!Y)return Q;if(Q.includes("#"))return Q;let J=Y.endSeconds!==void 0?`,${Y.endSeconds}`:"";return`${Q}#t=${Y.startSeconds}${J}`}function V9(Q){if(!Q)return null;let Y=Q.payload;if(!Y||typeof Y!=="object")return null;let J=Y.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(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 G=W9(J.sources);if(G.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:G,fragment:U9(Y.fragment),label:B9(J.label)}}var w7=(Q,Y)=>{let J=Y?.useSentenceSegmenter!==!1;try{if(!J)throw Error("Segmenter disabled by policy");let q=globalThis.Intl?.Segmenter;if(typeof q==="function"){let K=new q(Y?.locale,{granularity:"sentence"}),B=Array.from(K.segment(Q)).map((U)=>({text:U.segment,offset:U.index})).filter((U)=>U.text.trim().length>0);if(B.length>0)return B}}catch{}let G=/[^.!?]+(?:[.!?]+|$)/g,X=Q.match(G)||[Q],j=[],Z=0;for(let q of X){let K=Q.indexOf(q,Z);if(K===-1)continue;j.push({text:q,offset:K}),Z=K+q.length}return j.length>0?j:[{text:Q,offset:0}]};var H9=5000,_9=2000,F9=(Q)=>String(Q||"").trim().toLowerCase(),W3=()=>{let Q=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return F9(Q||"en-US")},U3=(Q,Y)=>{if(Y)return Q.find((Z)=>Z.voiceURI===Y)||Q.find((Z)=>Z.name===Y)||null;let J=W3(),G=J.split("-")[0]||"en",X=(Z)=>{let q=F9(Z.lang);return q===J||q.startsWith(`${G}-`)},j=[(Z)=>Z.localService&&X(Z),(Z)=>Z.default&&X(Z),(Z)=>X(Z),(Z)=>Z.localService,(Z)=>Z.default];for(let Z of j){let q=Q.find(Z);if(q)return q}return Q[0]||null},B3=(Q)=>!Q.default;class R7{providerId="browser";providerName="Browser Speech Synthesis";version="1.0.0";async initialize(Q){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return new A9(Q)}supportsFeature(Q){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}}class A9{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;settlePendingVoiceWait=null;settlePendingChunk=null;onPlaybackStart=void 0;constructor(Q){this.config=Q}waitForBrowserVoices(Q,Y){return new Promise((J,G)=>{let X=speechSynthesis,j=typeof X.addEventListener==="function"&&typeof X.removeEventListener==="function",Z=j?null:X.onvoiceschanged,q=!1,K=null,B=null,U=()=>{if(K!==null)clearTimeout(K),K=null;if(j)X.removeEventListener("voiceschanged",A);else if(X.onvoiceschanged===M)X.onvoiceschanged=Z;if(B&&this.settlePendingVoiceWait===B)this.settlePendingVoiceWait=null},H=(O,L)=>{if(q)return;if(q=!0,U(),L)G(L);else J(O)},_=()=>{if(Q!==this.speakRunId){H(!1);return}if(X.getVoices().length>0)H(!0)},A=()=>_(),M=(O)=>{try{Z?.call(X,O)}finally{_()}};if(B=()=>H(!1),this.settlePendingVoiceWait=B,K=setTimeout(()=>H(!1,Error(`Configured browser voice "${Y}" could not be resolved because the browser did not publish its voice inventory within ${_9/1000} seconds.`)),_9),j)X.addEventListener("voiceschanged",A);else X.onvoiceschanged=M;_()})}async resolveBrowserVoice(Q){let Y=typeof this.config?.voice==="string"?this.config.voice.trim():"",J=speechSynthesis.getVoices();if(Y&&J.length===0){if(!await this.waitForBrowserVoices(Q,Y)||Q!==this.speakRunId)return{shouldContinue:!1,voice:null};J=speechSynthesis.getVoices()}if(Q!==this.speakRunId)return{shouldContinue:!1,voice:null};let G=U3(J,Y||void 0);if(Y&&!G)throw Error(`Configured browser voice "${Y}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:G}}async speak(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;let G=this.splitIntoChunks(Q);for(let X of G){if(Y!==this.speakRunId)break;if(!await this.speakChunk(X.text,X.offset,Y,J.voice))break}}async speakSegments(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;for(let G of Q){if(Y!==this.speakRunId)break;let X=this.splitIntoChunks(G.text);for(let Z of X){if(Y!==this.speakRunId)break;if(!await this.speakChunk(Z.text,G.startOffset+Z.offset,Y,J.voice))break}let j=Math.max(0,Number(G.pauseMsAfter||0));if(j>0&&Y===this.speakRunId){if(!await this.waitForPause(j,Y))break}}}async waitForPause(Q,Y){return await new Promise((J)=>setTimeout(J,Q)),Y===this.speakRunId}splitIntoChunks(Q){if(Q.length<=260)return[{text:Q,offset:0}];let J=this.segmentSentences(Q),G=[],X="",j=0;for(let Z of J){let q=Z.text.trim();if(!q)continue;let K=Z.text.search(/\S/),B=Z.offset+(K===-1?0:K);if(!X){X=q,j=B;continue}let U=`${X} ${q}`;if(U.length<=260)X=U;else G.push({text:X,offset:j}),X=q,j=B}if(X)G.push({text:X,offset:j});return G.length?G:[{text:Q,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){let Q=this.config?.providerOptions||{},Y=Q.segmenter||{},G=Y.mode!=="regexOnly",X=typeof Y.locale==="string"&&Y.locale.trim().length>0?Y.locale:typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:void 0;return{useSentenceSegmenter:G,useWordSegmenter:G,locale:X}}segmentSentences(Q){let Y=this.getSegmentationPolicy();return w7(Q,{locale:Y.locale,useSentenceSegmenter:Y.useSentenceSegmenter})}inferWordLength(Q,Y){let J=Math.max(0,Math.min(Y,Math.max(0,Q.length-1)));return Q.slice(J).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Q,Y,J,G){return new Promise((X,j)=>{if(J!==this.speakRunId){X(!1);return}let Z=new SpeechSynthesisUtterance(Q);if(this.utterance=Z,G&&B3(G))Z.voice=G;if(this.config?.rate)Z.rate=this.config.rate;if(this.config?.pitch)Z.pitch=this.config.pitch;let q=!1,K=!1,B=null,U=null,H=()=>{if(this.utterance===Z)this.utterance=null},_=()=>{if(B!==null)clearTimeout(B),B=null},A=()=>{Z.onstart=null,Z.onend=null,Z.onerror=null,Z.onpause=null,Z.onresume=null,Z.onboundary=null},M=(L,F)=>{if(K)return;if(K=!0,_(),A(),H(),U&&this.settlePendingChunk===U)this.settlePendingChunk=null;if(J===this.speakRunId)this._isPlaying=!1,this._isPaused=!1;if(F)j(F);else X(L)},O=(L)=>Error(L==="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 ${H9/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);U=()=>M(!1),this.settlePendingChunk=U,Z.onstart=()=>{if(J!==this.speakRunId){M(!1);return}q=!0,_(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch(L){console.error("Browser TTS playback-start callback failed",L)}},Z.onend=()=>{if(J!==this.speakRunId){M(!1);return}if(!q){M(!1,O("ended"));return}M(!0)},Z.onerror=(L)=>{if(J!==this.speakRunId){M(!1);return}if(L.error==="interrupted"||L.error==="canceled"){M(!1);return}M(!1,Error(`Speech synthesis error: ${L.error}`))},Z.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},Z.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},Z.onboundary=(L)=>{if(J!==this.speakRunId)return;if(console.log("[BrowserProvider] Boundary event:",L.name,"charIndex:",L.charIndex,"charLength:",L.charLength),L.name!=="word"||!this.onWordBoundary)return;if(this.getHighlightMode()==="sentence")return;let F=Math.max(0,Math.min(L.charIndex,Math.max(0,Q.length-1))),$=Number(L.charLength||0),b=this.inferWordLength(Q,F),v=Number.isFinite($)&&$>0&&$<=80&&F+$<=Q.length?$:b,k=Q.substring(F,Math.min(Q.length,F+v)).trim(),p=Y+F;console.log("[BrowserProvider] Calling onWordBoundary with word:",k,"at position:",p),this.onWordBoundary(k,p,v)},B=setTimeout(()=>{if(K||q||J!==this.speakRunId)return;M(!1,O("timedOut")),speechSynthesis.cancel()},H9);try{speechSynthesis.speak(Z)}catch(L){M(!1,L instanceof Error?L:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPlaying&&!this._isPaused)speechSynthesis.pause()}resume(){if(this._isPlaying&&this._isPaused)speechSynthesis.resume()}stop(){let Q=this.utterance,Y=this._isPlaying||Q!==null;if(this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),Y)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(Q){if(!this.config)this.config={};if(Q.rate!==void 0)this.config.rate=Q.rate;if(Q.pitch!==void 0)this.config.pitch=Q.pitch;if(Q.voice!==void 0)this.config.voice=Q.voice;if(Q.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Q.providerOptions||{}}}onWordBoundary}var S=(Q)=>Q.trim().replace(/\s+/g," "),Z1=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,e1=(Q)=>{if(Q.hidden)return!0;if(Q.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Q.getAttribute("aria-hidden")==="true")return!0;if(Q.hasAttribute("inert"))return!0;let Y=Q.classList;if(Y?.contains("sr-only")||Y?.contains("pie-sr-only")||Y?.contains("visually-hidden"))return!0;if(typeof window<"u"){let J=window.getComputedStyle(Q);if(J.display==="none"||J.visibility==="hidden")return!0;let G=Number.parseFloat(J.width||"0"),X=Number.parseFloat(J.height||"0"),j=Number.isFinite(G)&&Number.isFinite(X)&&G<=1&&X<=1,Z=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")&&j&&(J.overflow==="hidden"||Z))return!0;if(J.opacity==="0"&&j)return!0}return!1},j1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(e1(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1};var z9=new Set(["computer-read-aloud","all"]),M9=new Set([...z9,"screen-reader"]),N9=new Set,D3=(Q)=>{let Y=Q.getAttribute?.("data-tts-suppress");if(Y===null||Y===void 0)return!1;let J=Y.trim().toLowerCase();if(z9.has(J))return!0;if(M9.has(J))return!1;if(!N9.has(J))N9.add(J),console.warn(`[tts] data-tts-suppress="${Y}" is not one of ${Array.from(M9).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},q1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(D3(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1},V7=(Q,Y)=>j1(Q,Y)||q1(Q),Q8=(Q,Y)=>{if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u"||typeof Q.intersectsNode!=="function")return{text:Q.toString(),filtered:!1};let J=[],G=!1,X=document.createTreeWalker(Y,NodeFilter.SHOW_TEXT),j=X.nextNode();while(j){let Z=j;if(Q.intersectsNode(Z))if(V7(Z,Y))G=!0;else{let q=Z.textContent||"",K=Z===Q.startContainer?Q.startOffset:0,B=Z===Q.endContainer?Q.endOffset:q.length;J.push(q.slice(K,B))}j=X.nextNode()}return{text:J.join(""),filtered:G}},Y8=(Q,Y,J)=>{if(!Q||!Y)return!1;if(/\s/.test(Q)||/\s/.test(Y))return!1;let G=J?.boundarySpacingMode??"segmenterPreferred";if(G==="none")return!1;if(G==="segmenterPreferred")try{let Z=globalThis.Intl?.Segmenter;if(typeof Z==="function"){let q=new Z(J?.locale,{granularity:"word"});if(Array.from(q.segment(`${Q}${Y}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Q),j=/[A-Za-z0-9]/.test(Y);return X&&j},E7=(Q,Y)=>{let J=new Map;if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u")return{text:"",map:J};let G=[],X=0,j=!0,Z=!1,q=null,K=null,B=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),U=B.nextNode();while(U){let _=U;if(_.parentElement&&!V7(_,Q)){let M=_.textContent||"",O=M.match(/\S/),L=O?O[0]:null;if(!j&&!Z&&Y8(K,L,Y)){if(G.push(" "),q)J.set(X,q);X++,Z=!0}for(let F=0;F<M.length;F++){let $=M[F],b=/\s/.test($);if(j){if(!b)j=!1,G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}else if(b){if(!Z)G.push(" "),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++;Z=!0}else G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}}U=B.nextNode()}let H=G.join("").trimEnd();while(J.has(H.length))J.delete(H.length);return{text:H,map:J}};var V3=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),O9=new Set(["audio","phoneme"]),L9=(Q)=>Q.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/ /g," ").replace(/&/g,"&"),K1=(Q,Y,J)=>{for(let G=0;G<Y.length;G++)Q.push({char:Y[G],rawOffset:J===null?null:J+G})},H3=(Q,Y,J)=>{let G=Y.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!G)return 0;return K1(Q,L9(G[0]),J),G[0].length},P9=(Q)=>{Q.push({char:" ",rawOffset:null})},_3=(Q)=>{let Y=new Map,J=[],G=!0;for(let X of Q){if(/\s/.test(X.char)){if(!G&&J.length>0){if(J.push(" "),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1)}G=!0;continue}if(J.push(X.char),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1);G=!1}while(J.length>0&&J[J.length-1]===" ")J.pop();for(let[X,j]of Y)if(j>=J.length)Y.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Y}},F3=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},A3=(Q,Y)=>{let J=new RegExp(`${Y}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),G=Q.match(J);return L9(G?.[2]??G?.[3]??"")||null},W1=(Q)=>{let Y=[],J=!1,G=!1,X=0;while(X<Q.length){let Z=Q[X];if(Z!=="<"){if(Z==="&"){let _=H3(Y,Q,X);if(_>0){X+=_;continue}}K1(Y,Z,X),X++;continue}let q=Q.indexOf(">",X+1);if(q<0){K1(Y,Z,X),X++;continue}G=!0;let K=Q.slice(X,q+1),B=F3(K),U=/^<\s*\//.test(K),H=/\/\s*>$/.test(K);if(!U&&B==="sub"){let _=A3(K,"alias");if(!_){J=!0,X=q+1;continue}K1(Y,_,null);let A=Q.toLowerCase().indexOf("</sub>",q+1);X=A>=0?A+6:q+1;continue}if(!U&&B==="break"){P9(Y),X=q+1;continue}if(!U&&O9.has(B)){if(J=!0,H){X=q+1;continue}}if(B&&!V3.has(B)&&!O9.has(B)&&B!=="break"&&B!=="sub")J=!0;if(!U&&(B==="p"||B==="s"))P9(Y);X=q+1}let j=_3(Y);return{spokenText:S(j.text),rawToSpokenOffsetMap:j.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:G}};var M3=Z1(),b9=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),N3=[{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}],J8=(Q)=>{let Y=[];for(let J of Q.matchAll(M3)){let G=J[0],X=J.index??0;Y.push({text:G,normalized:G.toLowerCase(),start:X,end:X+G.length})}return Y},G8=(Q)=>b9.get(Q.normalized)||Q.normalized,z3=(Q,Y)=>{let J=[];for(let G=0;G<Q.length;G++){for(let X=0;X<Y.length;X++){let j=G8(Q[G]),Z=G8(Y[X]);if(j===Z)J.push({spokenStartToken:G,spokenEndToken:G+1,visibleToken:X,score:10})}for(let X of N3){let j=Q.slice(G,G+X.phrase.length);if(j.length!==X.phrase.length)continue;if(!j.every((Z,q)=>Z.normalized===X.phrase[q]))continue;for(let Z=0;Z<Y.length;Z++){if(Y[Z].normalized!==X.visible)continue;J.push({spokenStartToken:G,spokenEndToken:G+X.phrase.length,visibleToken:Z,score:X.score})}}}return J},O3=(Q,Y)=>{let J=z3(Q,Y).sort((K,B)=>Q[K.spokenStartToken].start-Q[B.spokenStartToken].start||Y[K.visibleToken].start-Y[B.visibleToken].start),G=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let K=0;K<J.length;K++){let B=J[K];G[K]=B.score;for(let U=0;U<K;U++){let H=J[U];if(H.spokenEndToken<=B.spokenStartToken&&H.visibleToken<B.visibleToken){let _=B.spokenStartToken-H.spokenEndToken,A=B.visibleToken-H.visibleToken-1,M=Math.max(0,Math.abs(_-A)-2),O=G[U]+B.score-M;if(O>G[K])G[K]=O,X[K]=U}}}let j=-1;for(let K=0;K<G.length;K++)if(j<0||G[K]>G[j])j=K;if(j<0)return[];let Z=[],q=j;while(q>=0)Z.unshift(J[q]),q=X[q];return Z.map((K)=>{let B=Q[K.spokenStartToken],U=Q[K.spokenEndToken-1],H=Y[K.visibleToken];return{spokenStart:B.start,spokenEnd:U.end,visibleStart:H.start,visibleEnd:H.end,score:K.score}})},P3=(Q,Y,J)=>{if(Q.length===0)return 0;let G=Q.length/Math.max(1,Math.min(Y.length,J.length)),X=Q.reduce((j,Z)=>j+Z.score,0)/Q.length/10;return Math.min(1,G*X)},U1=(Q)=>{let Y=W1(Q.speechText),J=S(Q.visibleText),G=Y.spokenText,X=J8(G),j=J8(J),Z=Y.unsupportedSemantic?[]:O3(X,j),q=P3(Z,X,j),K=G===J&&G.length>0,B=Z.length===1&&Z[0].score===10&&X.length<=2&&j.length<=2,U=Y.unsupportedSemantic?"region-fallback":K?"exact-word":Z.length>=2||B?q>=0.12?"anchor-span":"region-fallback":"region-fallback",H=Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:G,visibleText:J,playbackMode:U,boundaryOffsetMode:H,anchors:Z,confidence:q,spokenTokens:X,visibleTokens:j,rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap}},X8=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,S9=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=J8(Q)[0];if(!Y)return null;return b9.get(Y.normalized)||Y.normalized},$9=(Q,Y,J)=>{let G=S9(J);if(!Y||!G)return!1;let X=X8(Q.spokenTokens,Y.start);if(!X)return!1;return G8(X)===G},w9=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},R9=(Q,Y,J)=>{let G=w9(Q,Y);if(G===null)return null;let X=w9(Q,Math.max(Y,Y+J-1)),j=X8(Q.spokenTokens,G),Z=X!==null&&X>=G?X-G+1:j?j.end-G:J;return{start:G,length:Math.max(1,Z)}},E9=(Q,Y,J)=>{if(Y<0||Y>=Q.spokenText.length)return null;let G=X8(Q.spokenTokens,Y);if(!G)return null;return{start:Y,length:Math.min(J,G.end-Y)}},T9=(Q,Y,J=1,G)=>{if(Q.boundaryOffsetMode==="unsupported"||!Number.isFinite(Y))return null;let X=Math.max(1,Number.isFinite(J)?J:1);if(G&&/^<[^>]+>$/.test(G.trim()))return null;if(Q.boundaryOffsetMode==="raw-ssml"){let j=R9(Q,Y,X),Z=E9(Q,Y,X);if(G){if($9(Q,j,G))return j;if($9(Q,Z,G))return Z;if(S9(G))return null}return j||Z}return E9(Q,Y,X)||R9(Q,Y,X)},C9=(Q,Y)=>{if(Q.playbackMode==="region-fallback")return null;let J=Q.anchors.find((j)=>j.spokenStart<=Y&&Y<j.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let G=null,X=null;for(let j of Q.anchors){if(j.spokenEnd<=Y){G=j;continue}if(j.spokenStart>Y){X=j;break}}if(G&&X)return{start:Math.min(G.visibleStart,X.visibleStart),end:Math.max(G.visibleEnd,X.visibleEnd)};return null};var L3=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"]]]),$3=new Map([["","function-application"],["","implicit-multiply"],["","invisible-separator"],["","invisible-plus"]]),y9=new Map([["2",["squared"]],["3",["cubed"]]]),w3=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),R3=(Q)=>Q.replace(/\s+/g," ").trim(),H7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),E3=(Q)=>Q.nodeType===Node.ELEMENT_NODE,b7=(Q)=>Array.from(Q.childNodes).filter(E3),Z8=(Q)=>R3(Q.textContent||""),e=(Q,Y)=>({type:"element-range",quality:Y,element:Q}),b3=(Q)=>{switch(Q){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"}},S3=(Q,Y)=>{if(Y==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},T3=(Q,Y,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return y9.get(Q)??[];if(Q==="|")return["absolute value"];if(Y==="operator")return L3.get(Q)||[];return[]},_7=(Q)=>{let Y=Q.normalized??S3(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:Y,spokenAliases:T3(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||e(Q.sourceElement,"element-range"),optional:Q.optional}},F7=(Q,Y,J="tokens")=>{Q[J].push(Y)},x9=(Q,Y,J)=>{b7(Q).forEach((G,X)=>Q7(G,Y,`${J}/${H7(G)}[${X}]`))},C3=(Q,Y,J)=>{let G=b7(Q);if(G[0])Q7(G[0],Y,`${J}/numerator`);if(F7(Y,_7({state:Y,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:J,target:e(Q,"element-range")})),G[1])Q7(G[1],Y,`${J}/denominator`)},y3=(Q,Y,J)=>{let G=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";F7(Y,_7({state:Y,kind:"operator",role:G==="|"?"absolute-value-fence":"open-fence",text:G,sourceElement:Q,path:`${J}/open`,target:e(Q,"element-range")})),x9(Q,Y,J),F7(Y,_7({state:Y,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${J}/close`,target:e(Q,"element-range")}))},x3=(Q,Y,J)=>{let G=b7(Q);if(G[0])Q7(G[0],Y,`${J}/base`);let X=G[1];if(!X)return;let j=Z8(X);if(y9.has(j)){F7(Y,_7({state:Y,kind:"structure",role:"superscript",text:j,normalized:j,sourceElement:X,path:`${J}/exponent`,target:e(Q,"element-range")}));return}Q7(X,Y,`${J}/exponent`)},f3=(Q,Y,J,G)=>{F7(Y,_7({state:Y,kind:"structure",role:G,text:Z8(Q)||G,normalized:`\x00${G}`,sourceElement:Q,path:J,target:e(Q,"element-range")}))},k3=(Q,Y,J)=>{let G=0;for(let X of b7(Q)){if(H7(X)==="mtr"||H7(X)==="mlabeledtr")G++,F7(Y,_7({state:Y,kind:"layout",role:"table-row",text:`row-${G}`,normalized:`row-${G}`,sourceElement:X,path:`${J}/row[${G}]`,target:e(X,"region-fallback")}),"layoutTargets");Q7(X,Y,`${J}/${H7(X)}[${G}]`)}},I3=(Q,Y,J)=>{let G=Z8(Q);if(!G)return;let X=b3(H7(Q)),j=X==="operator"?$3.get(G):void 0,Z=j??(X==="operator"&&(G==="("||G===")")?"grouping-fence":X);F7(Y,_7({state:Y,kind:X,role:Z,text:G,sourceElement:Q,path:J,target:j&&Q.parentElement?e(Q.parentElement,"region-fallback"):void 0,optional:Boolean(j)||Z==="grouping-fence"}))},Q7=(Q,Y,J)=>{let G=H7(Q);switch(G){case"annotation":case"annotation-xml":return;case"semantics":{let X=b7(Q).find((j)=>{let Z=H7(j);return Z!=="annotation"&&Z!=="annotation-xml"});if(X)Q7(X,Y,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":I3(Q,Y,J);return;case"mfrac":C3(Q,Y,J);return;case"msup":x3(Q,Y,J);return;case"mfenced":y3(Q,Y,J);return;case"mtable":k3(Q,Y,J);return;case"mphantom":return;case"maction":{let X=b7(Q)[0];if(X)Q7(X,Y,`${J}/action`);return}default:{let X=w3.get(G);if(X){f3(Q,Y,J,X);return}x9(Q,Y,J)}}},f9=(Q)=>{let Y={tokens:[],layoutTargets:[],nextId:0};return Q7(Q,Y,"/math"),{tokens:Y.tokens,layoutTargets:Y.layoutTargets,expressionTarget:e(Q,"region-fallback")}};var k9=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((J)=>J.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var v3=(Q)=>{let Y=[],J=new Set,G=(X)=>{let j=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(j.length===0)return;let Z=j.join(" ");if(J.has(Z))return;J.add(Z),Y.push(j)};G(Q.normalized);for(let X of Q.spokenAliases)G(X);return Y},I9=(Q,Y,J)=>{let G=0;for(let X of J){if(X.length<=G)continue;let j=!0;for(let Z=0;Z<X.length;Z++){let q=Q[Y+Z];if(!q||q.normalized.toLowerCase()!==X[Z]){j=!1;break}}if(j)G=X.length}return G},h3=(Q,Y)=>{let J=[],G=0;for(let X of Y){let j=v3(X);if(X.optional){let Z=I9(Q,G,j);if(Z>0)J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;continue}while(G<Q.length){let Z=I9(Q,G,j);if(Z>0){J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;break}G++}}return J},m3=(Q,Y,J)=>{let G=J.filter((Z)=>!Z.optional).length,X=Q.filter((Z)=>!Z.math.optional).length,j=Q.reduce((Z,q)=>Z+q.speechTokens.length,0);return G>0&&X===G&&j===Y.length},u3=(Q)=>Q.map(({speechTokens:Y,math:J})=>({speechTokenIds:Y.map((G)=>G.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),v9=(Q)=>{let Y=Q.minExactWordConfidence??0.95,J=h3(Q.speech.tokens,Q.math.tokens),G=m3(J,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:G>=Y?u3(J):[],confidence:G,fallbackTarget:Q.math.expressionTarget}};var h9=Z1(),p3=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),m9=(Q)=>{let Y=Q.toLowerCase();return p3.get(Y)||Y},g3=(Q)=>{let Y=[];for(let J of Q.matchAll(h9)){let G=J[0],X=J.index??0;Y.push({id:`speech-token-${Y.length}`,text:G,normalized:m9(G),start:X,end:X+G.length,sourceStart:X,sourceEnd:X+G.length,coordinateSystem:"normalized-speech"})}return Y},A7=(Q)=>{let Y=W1(Q.speechText);return{speechText:Q.speechText,spokenText:Y.spokenText,tokens:g3(Y.spokenText),rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap,boundaryOffsetSpace:Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Y.unsupportedSemantic,hasMarkup:Y.hasMarkup}},K8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=Q.match(h9);if(!Y?.[0])return null;return m9(Y[0])},c3=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,l3=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},j8=(Q,Y,J)=>{if(Y===null)return null;let G=c3(Q.tokens,Y);if(!G)return null;return{token:G,start:Y,length:Math.max(1,Math.min(J,G.end-Y)),confidence:0.75}},q8=(Q,Y)=>{let J=K8(Y);return Boolean(Q&&J&&Q.token.normalized===J)},W8=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,l3(Q.tokenization,Q.position),Y),G=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(q8(G,Q.boundaryWord))return{...G,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return Q.tokenization.boundaryOffsetSpace==="raw-ssml"?J||G:G||J},u9=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return J};var S7=(Q)=>{let Y=A7({speechText:Q.speechText}),J=f9(Q.mathElement);return{speech:Y,math:J,result:v9({speech:Y,math:J})}};var p9=(Q,Y)=>{let J=u9({tokenization:Q.speech,position:Y.position,length:Y.length,boundaryWord:Y.boundaryWord});return k9({alignment:Q.result,boundary:J})},g9=(Q,Y)=>{if(!Y.boundaryWord||/^<[^>]+>$/.test(Y.boundaryWord.trim()))return null;let J=A7({speechText:Y.boundaryWord}).tokens[0];if(!J)return null;let G=Q.math.tokens.filter((X)=>{let j=J.normalized.toLowerCase();return X.normalized.toLowerCase()===j||X.spokenAliases.some((Z)=>Z.toLowerCase()===j)});return G.length===1?G[0].target:null};var d3=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"]),i3=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"]),c9=(Q)=>Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),s3=(Q)=>c9(Q).replace(/"/g,"""),n3=(Q,Y)=>{let J=Q.toLowerCase(),G=Y.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!i3.has(J))return!0;if(G.includes("javascript:"))return!0;if(G.includes("data:text/html"))return!0;return!1},r3=(Q)=>{let Y=Q.localName.toLowerCase();if(!d3.has(Y))return!1;let J=Q.namespaceURI;return!J||J==="http://www.w3.org/1998/Math/MathML"||J==="http://www.w3.org/1999/xhtml"},l9=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return c9(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let Y=Q;if(!r3(Y))return null;let J=Y.localName.toLowerCase(),G=[];for(let Z of Array.from(Y.attributes)){let q=Z.name.toLowerCase();if(n3(q,Z.value))continue;if(q==="xmlns"&&Z.value!=="http://www.w3.org/1998/Math/MathML")return null;G.push(`${q}="${s3(Z.value)}"`)}if(J==="math"&&!G.some((Z)=>Z.startsWith("xmlns=")))G.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let Z of Array.from(Y.childNodes)){let q=l9(Z);if(q===null)return null;X.push(q)}let j=G.length>0?` ${G.join(" ")}`:"";return`<${J}${j}>${X.join("")}</${J}>`},o3=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},B1=(Q)=>{let Y=String(Q||"").trim();if(!Y)return null;let J=o3(Y);if(!J)return null;if(J.getElementsByTagName("parsererror").length>0)return null;let G=J.documentElement;if(!G||G.localName.toLowerCase()!=="math")return null;return l9(G)};var d9=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),i9=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",s9=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",n9=(Q)=>{let Y=Q.tagName?.toLowerCase();return Y==="annotation"||Y==="annotation-xml"},a3=(Q)=>{let Y=Q.getAttribute("data-mathml");return Y&&Y.trim()?Y:null},t3=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},e3=(Q)=>{if(Q.tagName.toLowerCase()==="math")return B1(Q.outerHTML);let Y=a3(Q);if(Y){let J=B1(Y);if(J)return J}if(i9(Q)){let J=t3(Q);if(J){let G=B1(J);if(G)return G}}return null};var Q2=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),Y2=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),J2=(Q,Y)=>{let J=Q.parentElement,G=null;while(J&&J!==Y){let X=(J.getAttribute("role")||"").toLowerCase(),j=J.tagName.toUpperCase();if(Q2.has(j)||Y2.has(X)){G=J;break}J=J.parentElement}return G||Y},G2=(Q)=>Boolean(typeof Q.querySelector==="function"&&Q.querySelector("math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Q.tagName?.toLowerCase()==="math"||Q.hasAttribute?.("data-mathml")||i9(Q),M7=(Q,Y,J)=>{if(/[.,;:!?]/.test(Y)&&Q.chars.length>0&&Q.chars[Q.chars.length-1]===" ")Q.chars.pop(),Q.position--,Q.map.delete(Q.position);if(Q.chars.push(Y),J)Q.map.set(Q.position,J),Q.lastMapped=J;else if(Q.lastMapped)Q.map.set(Q.position,Q.lastMapped);Q.position++},r9=(Q,Y)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let J=Q.chars[Q.chars.length-1];return Y8(J,Y,Q.options)},o9=(Q,Y)=>{let J=Y.textContent||"",G=!1;for(let X=0;X<J.length;X++){let j=J[X],Z=/\s/.test(j);if(Q.inLeadingWhitespace){if(!Z)Q.inLeadingWhitespace=!1,M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1;continue}if(Z){if(!Q.lastCharWasWhitespace)M7(Q," ",{node:Y,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!G&&r9(Q,j))M7(Q," ",{node:Y,offset:X});M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1}},X2=(Q,Y)=>{for(let J=0;J<Y.text.length;J++){let G=Y.text[J],X=/\s/.test(G),j=Y.map.get(J)||null,Z=j?.node||Q.lastMapped?.node||null,q=j?.offset??Q.lastMapped?.offset??0,K=j?{node:j.node,offset:j.offset}:Z?{node:Z,offset:q}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)M7(Q," ",K);Q.lastCharWasWhitespace=!0;continue}if(J===0&&r9(Q,G))M7(Q," ",K);if(M7(Q,G,K),Q.lastCharWasWhitespace=!1,j)Q.map.set(Q.position-1,{node:j.node,offset:j.offset}),Q.lastMapped={node:j.node,offset:j.offset};else if(Z)Q.map.set(Q.position-1,{node:Z,offset:q})}},Z2=(Q)=>{if(typeof DOMParser>"u")return"";let Y=new DOMParser().parseFromString(Q,"application/xml");if(Y.getElementsByTagName("parsererror").length>0)return"";let J=[],G=(X)=>{if(X.nodeType===3){let Z=X.textContent||"";if(Z.trim())J.push(Z);return}if(X.nodeType!==1)return;let j=X;if(n9(j))return;for(let Z of Array.from(j.childNodes))G(Z)};return G(Y.documentElement),S(J.join(" "))},j2=(Q,Y,J)=>{let G=d9(J),X=(q)=>{if(V7(q,Q))return;if(q.nodeType===3){o9(G,q);return}if(q.nodeType!==1)return;let K=q;if(s9(K)||n9(K))return;for(let B of Array.from(K.childNodes))X(B)};X(Q),a9(G);let j=S(G.chars.join(""));if(j)return{text:j,map:G.map};let Z=Z2(Y);if(!Z)return E7(Q,J);return{text:Z,map:new Map}},a9=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},q2=(Q,Y)=>{let J=d9(Y),G=[],X=0,j,Z=!1,q=()=>{let U=S(J.chars.slice(X,J.chars.length).join(""));if(U)G.push({type:"text",text:U,sourceElement:j});X=J.chars.length,j=void 0},K=(U)=>{if(V7(U,Q))return;if(U.nodeType===Node.TEXT_NODE){let A=J2(U,Q);if(j&&A!==j)q();j=A,o9(J,U);return}if(U.nodeType!==Node.ELEMENT_NODE)return;let H=U;if(s9(H))return;let _=e3(H);if(_){q();let A=j2(H,_,Y);X2(J,A);let M=S(A.text);G.push({type:"math",mathml:_,fallbackText:M,sourceElement:H}),X=J.chars.length,Z=!0;return}for(let A of Array.from(H.childNodes))K(A)};for(let U of Array.from(Q.childNodes))K(U);a9(J),q();let B=J.chars.join("");while(J.map.has(B.length))J.map.delete(B.length);return{visibleText:B,map:J.map,chunks:G,containsMathMarkup:Z}},N7=(Q,Y)=>{if(!G2(Q)){let{text:J,map:G}=E7(Q,Y);return{visibleText:J,map:G,chunks:J?[{type:"text",text:J}]:[],containsMathMarkup:!1}}return q2(Q,Y)};var U8=null,t9=Promise.resolve(),W2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",U2=async()=>{if(!U8)U8=import("speech-rule-engine").then((Q)=>{let Y=Q.default||Q;if(!Y||typeof Y.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return Y});return U8},B2=(Q)=>Q==="en"?"clearspeak":"mathspeak",e9=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),Q6=(Q)=>typeof Q==="string"&&Q.trim()?Q.trim():void 0,z7=(Q)=>{if(!e9(Q))return;let Y=Q6(Q.domain),J=Q6(Q.style),G=e9(Q.engineOptions)?Q.engineOptions:void 0;if(!Y&&!J&&!G)return;return{...Y?{domain:Y}:{},...J?{style:J}:{},...G?{engineOptions:G}:{}}},D2=async(Q,Y,J,G)=>{let X=W2(Y),j=z7(G);await Q.setupEngine?.({...j?.engineOptions||{},locale:X,domain:j?.domain||B2(X),...j?.style?{style:j.style}:{},modality:"speech",markup:J}),await Q.engineReady?.()},V2=async(Q)=>{let Y=t9.then(Q,Q);return t9=Y.then(()=>{return},()=>{return}),Y},Y6=async(Q,Y,J,G,X)=>V2(async()=>{return await D2(Q,J,G,X),Q.toSpeech(Y)}),H2=(Q)=>Q.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),_2=async(Q,Y,J,G)=>{try{let X=H2(await Y6(Q,Y,J,"ssml",G));return X.includes("<speak")?X:null}catch(X){return console.debug("[TTSService] Math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},D1=async(Q,Y={})=>{if(!Q.some((B)=>B.type==="math"))return{speechText:S(Q.map((B)=>B.type==="text"?B.text:B.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,G=!1,X=!1,j=Y.loadSre||U2,Z=[];for(let B of Q){if(B.type==="text"){Z.push(B.text);continue}try{if(!J)J=await j();let U=S(await Y6(J,B.mathml,Y.language,"none",Y.mathSpeech));if(U){Z.push(U),G=!0;continue}X=!0,Z.push(B.fallbackText)}catch(U){X=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),Z.push(B.fallbackText)}}let q=S(Z.join(" ")),K;if(Y.produceSsml&&J&&G&&Q.length===1&&Q[0].type==="math")K=await _2(J,Q[0].mathml,Y.language,Y.mathSpeech)??void 0;return{speechText:q,usedMathSpeech:G,usedFallback:X,ssml:K}};var F2=(Q,Y)=>D1([Q],Y),A2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",M2=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),N2=new Set(["heading","listitem","option","radio"]),z2=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let Y=Q.sourceElement.tagName.toUpperCase(),J=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return M2.has(Y)||N2.has(J)},B8=async(Q)=>{let Y=Q.resolveMathSpeech??F2,{visibleText:J}=Q,G=[],X=0,j=(q)=>{let K=S(q),B=J.indexOf(K,X),U=B>=0?B:X,H=U+K.length;return X=H,{start:U,end:H}},Z=[];for(let q=0;q<Q.chunks.length;q++){let K=Q.chunks[q];if(K.type==="text"){let A=z2(K)?[{text:K.text,offset:0}]:w7(K.text,{locale:Q.language});for(let M of A){let O=S(M.text);if(!O)continue;let L=j(O);G.push({sourceChunkIndex:q,segment:{kind:"prose",spokenText:O,visibleText:O,visibleSpan:L}}),Z.push(O)}continue}let B=j(K.fallbackText),U=await Y(K,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),H=!U.speechText,_=U.speechText||K.fallbackText;G.push({sourceChunkIndex:q,segment:{kind:"math",spokenText:_,mathml:K.mathml,fallbackText:K.fallbackText,visibleSpan:B,usedFallback:H,ssml:U.ssml}}),Z.push(_)}return{segments:G,locale:A2(Q.language),visibleText:J,plainSpeechText:S(Z.join(" "))}};var O2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",P2="sre-v1",L2=256,D8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(D8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([Y],[J])=>Y.localeCompare(J)).map(([Y,J])=>`${JSON.stringify(Y)}:${D8(J)}`).join(",")}}`;if(Q===null)return"null:null";if(typeof Q>"u")return"undefined:";if(typeof Q==="function")return`function:${Q.name||"anonymous"}`;if(typeof Q==="symbol")return`symbol:${String(Q)}`;if(typeof Q==="bigint")return`bigint:${Q.toString()}`;if(typeof Q==="number")return Number.isFinite(Q)?`number:${Q}`:`number:${String(Q)}`;return`${typeof Q}:${JSON.stringify(Q)}`},J6=(Q,Y,J,G)=>`${P2}\x00${O2(Q)}\x00${Y?"ssml":"plain"}\x00${D8(J??null)}\x00${G}`,V8=(Q={})=>{let Y=Math.max(1,Q.maxEntries??L2),J=Q.resolve??((j,Z)=>D1([j],Z)),G=new Map,X=(j,Z)=>{G.delete(j),G.set(j,Z);while(G.size>Y){let q=G.keys().next().value;if(q!==void 0)G.delete(q)}};return async(j,Z)=>{let q=z7(Z.mathSpeech),K=Z.produceSsml===!0,B=J6(Z.language,K,q,j.mathml),U=G.get(B);if(U)return G.delete(B),G.set(B,U),U;let H=await J(j,{...Z,mathSpeech:q});if(K&&H.ssml&&Y>1)X(J6(Z.language,!1,q,j.mathml),{speechText:H.speechText,usedMathSpeech:H.usedMathSpeech,usedFallback:H.usedFallback});return X(B,H),H}};var $2=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return A7({speechText:Q}).tokens[0]?.normalized||null},w2=(Q,Y)=>{let J=A7({speechText:Q.speechText});if(!Number.isFinite(Y.position))return{boundary:null,spokenText:J.spokenText};let G=W8({tokenization:J,position:Y.position,length:Y.length,boundaryWord:Y.word});return{boundary:G?{start:G.start,length:G.length}:null,spokenText:J.spokenText}},R2=(Q,Y,J)=>{if(!J)return!0;return A7({speechText:Q}).tokens.find((X)=>X.start<=Y&&Y<X.end)?.normalized===J},G6=(Q,Y)=>{let J=$2(Y.word);if(Q.id!==Y.chunkId)return{chunkId:Y.chunkId,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(Y.providerOffsetSpace==="unknown"||Q.offsetSpace==="unsupported")return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let G,X;if(Q.catalogAlignment)G=T9(Q.catalogAlignment,Y.position,Y.length,Y.word),X=Q.catalogAlignment.spokenText;else{let j=w2(Q,Y);G=j.boundary,X=j.spokenText}if(!G)return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};if(!R2(X,G.start,J))return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to matching word"};return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:G.start,chunkSpokenEnd:G.start+G.length,confidence:J?1:0.75,reason:Q.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var O7=(Q)=>{if(Q.semanticTarget)return{activeTarget:Q.semanticTarget,regionTarget:Q.regionTarget,quality:Q.semanticTarget.quality==="exact-word"?"exact-word":Q.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Q.confidence,reason:Q.reason};if(Q.expressionTarget)return{activeTarget:Q.expressionTarget,regionTarget:Q.regionTarget,quality:"expression",confidence:Q.confidence,reason:Q.reason};return{activeTarget:null,regionTarget:Q.regionTarget,quality:"region",confidence:Q.confidence,reason:Q.reason}};var Z6=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),H8="mi,mn,mo,mtext",j6="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",q6=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),K6=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},V1=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="mjx-container")return Y;Y=Y.parentElement}return null},X6=(Q)=>{if(!Q)return!1;if(V1(Q))return!1;return!j1(Q)},W6=(Q)=>{let Y=Q.getBoundingClientRect?.();return Boolean(Y&&Y.width>0&&Y.height>0)},_8=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="math")return Y;Y=Y.parentElement}return null},U6=(Q,Y)=>{if(Q.length===0)return!1;if(Q.length!==Y.length)return!1;for(let J=0;J<Q.length;J+=1){let G=Z6.get(Q[J].localName.toLowerCase());if(!G)return!1;if(Y[J].localName.toLowerCase()!==G)return!1}return!0},E2=(Q,Y)=>{if(!Q)return null;if(!Z6.has(Q.localName.toLowerCase()))return null;if(Y.querySelector(q6))return null;let J=_8(Q),G=Y.querySelector("mjx-math");if(!J||!G)return null;let X=Array.from(J.querySelectorAll(H8)),j=X.indexOf(Q);if(j<0)return null;let Z=Array.from(G.querySelectorAll(j6));if(!U6(X,Z))return null;let q=Z[j];if(!q||!W6(q))return null;return q},B6=(Q)=>{let Y=V1(Q);if(Y){if(Y.querySelector(q6))return"expression";let X=_8(Q)??Q,j=Y.querySelector("mjx-math");if(!j)return"expression";let Z=Array.from(X.querySelectorAll(H8)),q=Array.from(j.querySelectorAll(j6));if(!U6(Z,q))return"expression";return q.some((K)=>W6(K))?"token":"expression"}let J=_8(Q)??Q;return Array.from(J.querySelectorAll(H8)).some((X)=>!j1(X))?"token":"expression"},F8=(Q)=>{let Y=K6(Q),J=V1(Y);if(J){let G=E2(Y,J);if(G)return{type:"element",quality:"semantic-token",element:G};return{type:"element",quality:"expression",element:J}}if(Q.type==="text-range"){if(!X6(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!X6(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},D6=F8,V6=()=>{let Q=new WeakMap;return(Y)=>{let J=K6(Y),G=V1(J);if(!J||!G)return F8(Y);if(Q.has(J))return Q.get(J)??null;let X=F8(Y);return Q.set(J,X),X}};var H6=(Q,Y,J,G=Q.mathAlignments,X=D6)=>{if(Y.chunkSpokenStart===null||Y.chunkSpokenEnd===null)return null;let j=null;for(let Z of G){let q=p9(Z.alignment,{position:Y.chunkSpokenStart,length:Math.max(1,Y.chunkSpokenEnd-Y.chunkSpokenStart),boundaryWord:J.word})||g9(Z.alignment,{boundaryWord:J.word});if(!q)continue;let K=X(q);if(!K)continue;if(K.quality==="semantic-token")return K;j??=K}return j};var H1=(Q,Y,J)=>{if(!Q||typeof document>"u")return null;if(J<=Y)return null;let G=Q.get(Y),X=Q.get(Math.max(Y,J-1));if(!G)return null;if(!X)X=G;try{let j=document.createRange();return j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),j}catch{return null}};var _6=(Q,Y)=>{if(!Q.catalogAlignment||Y.chunkSpokenStart===null)return null;let J=C9(Q.catalogAlignment,Y.chunkSpokenStart);if(!J)return null;let G=H1(Q.visibleMap,J.start,J.end);if(!G)return null;return{type:"range",quality:Q.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:G}};var b2=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,F6=(Q,Y=Q.chunk.mathAlignments)=>{if(Y.length!==1)return null;let J=Y[0]?.alignment.result.fallbackTarget;return J?Q.renderedMathTargetResolver(J):null},S2=(Q,Y)=>{if(!Q)return Y.mathAlignments;return Y.mathAlignments.filter(({element:J})=>{try{if(Q.type==="range")return Q.range.intersectsNode(J);if(Q.type==="element")return Q.element===J||Q.element.contains(J);return Q.node.parentElement?.contains(J)||!1}catch{return!1}})},A6=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),M6=(Q)=>Q.length===1?Q[0].element:null,T2=(Q,Y)=>Y.length>0&&Y.every(({element:J})=>Q.mathCapabilityByElement.get(J)==="token"),C2=3,y2=(Q,Y,J)=>{if(!Y||Y.type!=="range")return!1;let{startContainer:G,endContainer:X}=Y.range;if(G===X&&G.nodeType===C2)return!1;return J.some(({element:Z})=>Q.mathCapabilityByElement.get(Z)==="token"&&Z.contains(G)&&Z.contains(X))},x2=(Q,Y)=>({chunk:Q,regionTarget:b2(Q),renderedMathTargetResolver:V6(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:J})=>[J,Y?B6(J):"expression"])),heldTokenByElement:new Map}),N6=(Q)=>{let Y=Q.mathTokenHighlighting!==!1,J=new Map(Q.chunks.map((G)=>[G.id,x2(G,Y)]));return{chunks:Q.chunks,resolveInitial(G){let X=J.get(G);if(!X)return A6();let j=X.chunk.mathAlignments,Z=j.length===1?j[0].element:null,q=Z?X.mathCapabilityByElement.get(Z):null;if(q==="expression")return O7({semanticTarget:null,expressionTarget:F6(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return O7({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:q==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(G){let X=J.get(G.chunkId);if(!X)return A6();let{chunk:j}=X,Z=G6(j,G),q=_6(j,Z),K=S2(q,j),B=(!q||K.length>0?H6(j,Z,G,K,X.renderedMathTargetResolver):null)||null,U=Y&&B&&B.quality!=="expression"?B:null,H=B&&B.quality==="expression"?B:null;if(U){let _=M6(K);if(_)X.heldTokenByElement.set(_,U);return O7({semanticTarget:U,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}if(q&&(Y?!y2(X,q,K):K.length===0))return O7({semanticTarget:q,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason});if(T2(X,K)){let _=M6(K),A=_?X.heldTokenByElement.get(_)??null:null;return O7({semanticTarget:A,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:A?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return O7({semanticTarget:null,expressionTarget:H??F6(X,K),regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}}};var f2=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let Y=Q.mathAlignment?.speech.boundaryOffsetSpace;if(Y)return Y;return"plain-spoken-text"},k2=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},z6=(Q)=>{return(Q.chunks&&Q.chunks.length?Q.chunks:[{speechText:Q.speechText||"",visibleText:Q.visibleText||Q.speechText||"",sourceElement:Q.sourceElement||Q.contentRoot,regionElement:Q.regionElement||Q.sourceElement||Q.contentRoot,regionRange:Q.regionRange,visibleMap:Q.visibleMap}]).map((J,G)=>({id:`tts-chunk-${G}`,speechText:J.speechText,visibleText:J.visibleText,sourceElement:J.sourceElement,contentRoot:Q.contentRoot,regionElement:J.regionElement??J.sourceElement,regionRange:J.regionRange,visibleMap:J.visibleMap,catalogAlignment:J.alignment,mathAlignments:k2(J),offsetSpace:f2(J)}))};var I2=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),_1=(Q,Y)=>{let J=Q.closest(I2);if(J&&Y.contains(J))return J;return Q};var v2=(Q,Y,J)=>{let G=new Map;for(let X=Y;X<J;X++){let j=Q.get(X);if(j)G.set(X-Y,j)}return G},A8=async(Q)=>{let Y=N7(Q.contentRoot,Q.textProcessingOptions),J=await B8({chunks:Y.chunks,visibleText:Y.visibleText,language:Q.language,mathSpeech:Q.mathSpeech,produceSsml:Q.produceSsml,resolveMathSpeech:Q.resolveMathSpeech});return{plan:{items:J.segments.map(({segment:X,sourceChunkIndex:j})=>{let Z=Y.chunks[j];if(X.kind==="prose"){let K=Z?.type==="text"?Z.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:K,regionElement:_1(K,Q.contentRoot),visibleMap:v2(Y.map,X.visibleSpan.start,X.visibleSpan.end)}}}let q=Z?.type==="math"?Z.sourceElement??null:null;return{segment:X,anchor:{sourceElement:q,regionElement:q}}}),locale:J.locale,visibleText:J.visibleText,plainSpeechText:J.plainSpeechText},containsMathMarkup:Y.containsMathMarkup,visibleText:Y.visibleText}};var h2=(Q,Y)=>{let J=U1({speechText:Q.spokenText,visibleText:Q.spokenText});return{speechText:Q.spokenText,visibleText:Q.visibleText,sourceElement:Y.sourceElement,regionElement:Y.regionElement,regionRange:H1(Y.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Y.visibleMap}},O6=(Q,Y)=>{let J=Y.sourceElement;return{speechText:Q.spokenText,visibleText:Q.fallbackText,sourceElement:J,regionElement:Y.regionElement,speechMatchesVisibleText:Q.spokenText===Q.fallbackText,mathAlignment:J?S7({mathElement:J,speechText:Q.spokenText}):void 0}},m2=(Q,Y,J)=>{let G=Y.sourceElement;return{speechText:J,visibleText:Q.fallbackText,sourceElement:G,regionElement:Y.regionElement,speechMatchesVisibleText:!1,mathAlignment:G?S7({mathElement:G,speechText:J}):void 0,plainFallback:O6(Q,Y)}},M8=(Q,Y={})=>Q.items.map(({segment:J,anchor:G})=>{if(J.kind==="prose")return h2(J,G);if(Y.format==="ssml"&&J.ssml)return m2(J,G,J.ssml);return O6(J,G)});var P6="pie-tts-control-handoff";var E;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})(E||(E={}));var L6=(Q,Y)=>Q===Y||Q.startContainer===Y.startContainer&&Q.startOffset===Y.startOffset&&Q.endContainer===Y.endContainer&&Q.endOffset===Y.endOffset,u2=(Q,Y)=>{if(Q===Y)return!0;if(!Q||!Y||Q.type!==Y.type||Q.quality!==Y.quality)return!1;if(Q.type==="range"&&Y.type==="range")return L6(Q.range,Y.range);if(Q.type==="element"&&Y.type==="element")return Q.element===Y.element;if(Q.type==="text-range"&&Y.type==="text-range")return Q.node===Y.node&&Q.startOffset===Y.startOffset&&Q.endOffset===Y.endOffset;return!1};class m7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=E.IDLE;ttsConfig={};currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Map;lastError=null;speakRunId=0;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];currentSeekSegmentIndex=0;activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=V8();static debugEnabled=(()=>{try{if(typeof process<"u"&&process.env?.PIE_TTS_DEBUG==="1")return!0}catch{}return globalThis.__PIE_TTS_DEBUG__===!0})();constructor(){}debugLog(Q,Y){if(!m7.debugEnabled)return;if(Y===void 0)console.debug(Q);else console.debug(Q,Y)}clearPlaybackStartBarrier(Q=this.playbackStartBarrierCleanup){if(Q?.(),this.playbackStartBarrierCleanup===Q)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Q){if(this.playbackStartDeferredRunId!==Q||Q!==this.speakRunId)return;this.setState(E.PLAYING);let Y=this.pendingPlaybackStartHighlights.splice(0);for(let J of Y)J()}installPlaybackStartBarrier(Q,Y=!1){this.clearPlaybackStartBarrier();let J=this.provider,G=J&&"onPlaybackStart"in J?J:null;if(!G&&!Y)return null;let X=G?.onPlaybackStart,j=()=>{try{this.notifyPlaybackStarted(Q)}finally{X?.()}};if(G)G.onPlaybackStart=j;this.playbackStartDeferredRunId=Q;let Z=()=>{if(G?.onPlaybackStart===j)G.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Q)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=Z,Z}runWhenPlaybackStarts(Q,Y){if(this.playbackStartDeferredRunId===Q){this.pendingPlaybackStartHighlights.push(Y);return}Y()}async emitTelemetry(Q,Y){try{await this.telemetryReporter?.(Q,Y)}catch(J){console.warn("[TTSService] telemetry callback failed:",J)}}async initialize(Q,Y={}){this.currentProvider=Q,this.ttsConfig={...Y};let J=Y.providerOptions&&typeof Y.providerOptions==="object"?Y.providerOptions:{};this.telemetryReporter=typeof J.__pieTelemetry==="function"?J.__pieTelemetry:null;try{this.provider=await Q.initialize(Y)}catch(G){if(Q.providerId.toLowerCase()==="browser")throw G;if(!this.isBrowserSpeechFallbackAvailable())throw G;if(!await this.switchProviderToBrowser(G,{operation:"tts-initialize"}))throw G}}async updateSettings(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.provider;if(typeof Y.updateSettings==="function"){let J={...Q,...Q.providerOptions?{providerOptions:{...this.ttsConfig.providerOptions||{},...Q.providerOptions}}:{}};await Y.updateSettings(J),this.ttsConfig={...this.ttsConfig,...J}}else console.warn("[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.")}setHighlightCoordinator(Q){this.highlightCoordinator=Q}setHighlightTargetResolverProvider(Q){return this.highlightTargetResolverProvider=Q,()=>{if(this.highlightTargetResolverProvider===Q)this.highlightTargetResolverProvider=null}}setCatalogResolver(Q){this.catalogResolver=Q}hasSpokenAlternate(Q,Y="en-US"){if(!Q||!this.catalogResolver)return!1;return this.catalogResolver.getAlternative(Q,{type:"spoken",language:Y,useFallback:!0,form:"content"})?.content!==void 0}getHighlightResolverRuntime(){let Q=null;try{Q=this.highlightTargetResolverProvider?.()??null}catch{Q=null}let Y=Q?.context??{},J=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...Y,scopeElement:Y.scopeElement??J},resolver:Q?.resolver??null}}getNodeElement(Q){if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:Q.parentElement}isElementWithinScope(Q,Y){if(!Y)return!0;return Q===Y||Y.contains(Q)}isRangeWithinScope(Q,Y){let J=this.getNodeElement(Q.startContainer),G=this.getNodeElement(Q.endContainer);if(!J||!G)return!1;return this.isElementWithinScope(J,Y)&&this.isElementWithinScope(G,Y)}resolveWordHighlightRange(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveWordRange?.(Q,Y);if(X&&this.isRangeWithinScope(X,G))return{range:X,remapped:!L6(Q,X)}}catch{}return{range:Q,remapped:!1}}resolveSentenceHighlightTargets(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveSentenceRanges?.(Q,Y);if(!X)return{ranges:Q,elements:[]};let j=[],Z=[];for(let q of X){if(typeof Range<"u"&&q instanceof Range){if(!this.isRangeWithinScope(q,G))return{ranges:Q,elements:[]};j.push(q);continue}if(typeof Element<"u"&&q instanceof Element){if(!this.isElementWithinScope(q,G))return{ranges:Q,elements:[]};Z.push(q);continue}return{ranges:Q,elements:[]}}return{ranges:j,elements:Z}}catch{return{ranges:Q,elements:[]}}}createTextRange(Q,Y,J){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let G=document.createRange();if(G.setStart(Q,Y),G.setEnd(Q,J),G.startContainer!==Q||G.endContainer!==Q)return null;return G}catch{return null}}paintTTSWordRange(Q){if(!this.highlightCoordinator)return;try{if(Q.startContainer===Q.endContainer&&Q.startContainer.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(Q.startContainer,Q.startOffset,Q.endOffset);return}}catch{}this.highlightCoordinator.highlightRange(Q,m.TTS_WORD,D7.YELLOW)}paintTTSSentenceRanges(Q){if(!this.highlightCoordinator)return;let{ranges:Y,elements:J}=this.resolveSentenceHighlightTargets(Q);if(J.length>0&&Y.length===0&&this.highlightCoordinator.highlightTTSSentenceElements){this.highlightCoordinator.highlightTTSSentenceElements(J);return}let G=[...Y];for(let X of J){let j=document.createRange();j.selectNodeContents(X),G.push(j)}this.highlightCoordinator.highlightTTSSentence(G)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}getTextProcessingOptions(Q){let J=(this.ttsConfig.providerOptions||{}).textNormalization||{},G=J.boundarySpacingMode,X=G==="none"||G==="alnum"||G==="segmenterPreferred"?G:void 0;return{locale:Q||(typeof J.locale==="string"?J.locale:void 0),boundarySpacingMode:X}}getMathSpeechOptions(){let Y=(this.ttsConfig.providerOptions||{}).mathSpeech;return z7(Y)}buildPositionMap(Q,Y,J){this.normalizedToDOM.clear();let{text:G,map:X}=E7(Q,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!m7.debugEnabled)return;this.debugLog("[TTSService] Text comparison:",{spokenLength:Y.length,normalizedDomLength:G.length,match:Y===G,spokenPreview:Y.substring(0,150),normalizedPreview:G.substring(0,150),differAtIndex:Y===G?null:(()=>{for(let j=0;j<Math.min(Y.length,G.length);j++)if(Y[j]!==G[j])return{index:j,spokenChar:Y[j],normalizedChar:G[j],spokenContext:Y.substring(Math.max(0,j-20),j+20),normalizedContext:G.substring(Math.max(0,j-20),j+20)};return null})()}),this.debugLog("[TTSService] Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:Y.length,normalizedDomLength:G.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===Y.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([j,{node:Z,offset:q}])=>({pos:j,offset:q,char:Z.textContent?.[q],expected:Y[j]}))})}getStructuralPauseProfile(){let Y=(this.ttsConfig.providerOptions||{}).structuralPauses||{},J=Y.units||{},G=(X,j)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let Z=Number(X);return Number.isFinite(Z)?Z:j}return j};return{baseMs:G(Y.baseMs,280),units:{minor:G(J.minor,0.65),section:G(J.section,1),major:G(J.major,1.35)},minMs:G(Y.minMs,120),maxMs:G(Y.maxMs,900)}}resolvePauseMsFromUnits(Q){let Y=this.getStructuralPauseProfile(),J=Math.max(0.25,Math.min(4,Number(this.ttsConfig.rate||1))),G=Y.baseMs*Math.max(0,Q)/J;return Math.max(Y.minMs,Math.min(Y.maxMs,Math.round(G)))}resolveHighlightMode(){let Y=(this.ttsConfig.providerOptions||{}).highlightMode;if(Y==="word"||Y==="sentence")return Y;if((this.currentProvider?.providerId||"").toLowerCase()==="browser")return"sentence";return this.currentProvider?.getCapabilities().supportsWordBoundary??!1?"word":"sentence"}hasExplicitBreakSemantics(Q){if(!Q.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Q)}isElementHidden(Q){return e1(Q)}getBoundaryStrength(Q){let Y=Number(Q.getAttribute("data-tts-break-ms"));if(Number.isFinite(Y)&&Y>0)return"major";let J=Q.tagName.toUpperCase();if(J.match(/^H[1-6]$/))return"major";let G=(Q.getAttribute("role")||"").toLowerCase();if(G==="heading")return"major";if(G==="listitem"||G==="row"||G==="option"||G==="radio"||J==="LI")return"section";if(typeof window<"u"){let X=window.getComputedStyle(Q).display;if(X==="block"||X==="list-item"||X.startsWith("table")||X==="flex"||X==="grid")return"minor"}return"minor"}getBoundaryAnchor(Q,Y){let J=Q.parentElement,G=null;while(J&&J!==Y){if(this.isElementHidden(J))return null;let j=Number(J.getAttribute("data-tts-break-ms"));if(Number.isFinite(j)&&j>0)return{anchor:J,units:j/this.getStructuralPauseProfile().baseMs};let Z=(J.getAttribute("role")||"").toLowerCase(),q=J.tagName.toUpperCase();if(q.match(/^H[1-6]$/)||Z==="heading"||Z==="listitem"||q==="LI"){G=J;break}if(!G){if(typeof window<"u"){let K=window.getComputedStyle(J).display;if(K==="block"||K==="list-item"||K.startsWith("table")||K==="flex"||K==="grid")G=J}}J=J.parentElement}if(!G)return null;let X=this.getBoundaryStrength(G);return{anchor:G,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Q,Y){let J=this.collectSpeechPlanBoundaries(Q,Y);return this.createSpeechPlanSegments(Y,J)}collectSpeechPlanBoundaries(Q,Y){let J=new Map,{map:G}=E7(Q,this.getTextProcessingOptions()),X=this.createNodeStartOffsets(G),j=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),Z=j.nextNode(),q=null;while(Z){let K=Z,B=K.parentElement;if(B&&!this.isElementHidden(B)&&!q1(K)){let U=this.getBoundaryAnchor(K,Q),H=X.get(K);if(U&&H!==void 0&&U.anchor!==q&&H>0)J.set(H,Math.max(J.get(H)||0,U.units)),q=U.anchor}Z=j.nextNode()}return J}createNodeStartOffsets(Q){let Y=new Map;for(let[J,G]of Q.entries())if(!Y.has(G.node))Y.set(G.node,J);return Y}createSpeechPlanSegments(Q,Y){let J=Array.from(Y.keys()).filter((K)=>K>0&&K<Q.length).sort((K,B)=>K-B),G=[],X=0;for(let K of J){let B=Q.substring(X,K),U=B.match(/^\s*/)?.[0].length||0,H=B.match(/\s*$/)?.[0].length||0,_=X+U,A=K-H;if(A>_){let M=Q.substring(_,A);G.push({text:M,startOffset:_,pauseMsAfter:this.resolvePauseMsFromUnits(Y.get(K)||0)})}X=K}let Z=Q.substring(X).match(/^\s*/)?.[0].length||0,q=X+Z;if(q<Q.length)G.push({text:Q.substring(q).trimEnd(),startOffset:q,pauseMsAfter:0});return G.filter((K)=>K.text.trim().length>0)}segmentSentences(Q){let Y=this.ttsConfig.providerOptions?.locale||void 0;return w7(Q,{locale:Y})}createSeekSegmentsFromText(Q){return this.segmentSentences(Q).map((Y)=>{let J=Y.text.match(/^\s*/)?.[0].length||0;return{text:Y.text.trim(),startOffset:Y.offset+J,pauseMsAfter:0}}).filter((Y)=>Y.text.length>0)}splitSegmentsAtBoundaries(Q,Y,J){if(Q.length===0||Y.length===0)return Q;let G=Array.from(new Set(Y)).filter((j)=>Number.isFinite(j)&&j>0).sort((j,Z)=>j-Z);if(G.length===0)return Q;let X=[];for(let j of Q){let Z=j.startOffset,q=j.startOffset+j.text.length,K=G.filter((U)=>U>Z&&U<q);if(K.length===0){X.push(j);continue}let B=Z;for(let U of[...K,q]){let H=J.substring(B,U),_=H.match(/^\s*/)?.[0].length||0,A=H.match(/\s*$/)?.[0].length||0,M=B+_,O=U-A;if(O>M)X.push({text:J.substring(M,O),startOffset:M,pauseMsAfter:0});B=U}}return X}createSentenceHighlightSegments(Q){let Y=this.createSeekSegmentsFromText(Q.contentToSpeak);if(!Q.shouldUsePlan||Q.playbackSegments.length===0)return Y;let J=Q.playbackSegments.map((G)=>G.startOffset).filter((G)=>G>0);return this.splitSegmentsAtBoundaries(Y,J,Q.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Q){let Y=0;return Q.map((J)=>{let G=J.plainFallback?.speechText||(this.hasExplicitBreakSemantics(J.speechText)?J.visibleText:J.speechText)||J.visibleText,X=S(G)||J.visibleText||"",j={text:X,startOffset:Y,pauseMsAfter:0};return Y+=Math.max(1,X.length+1),j})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let Q=0;for(let Y=0;Y<this.seekSegments.length;Y++)if(this.seekSegments[Y].startOffset<=this.currentBoundaryOffset)Q=Y;else break;return Q}async speakWithPlan(Q,Y,J){if(!this.provider||Q.length===0)return;let G=J?.highlightMode==="sentence",X=this.provider;if(!G&&typeof X.speakSegments==="function"){this.currentBoundaryOffset=0;let j=this.provider.onWordBoundary;this.provider.onWordBoundary=(Z,q,K)=>{if(j?.(Z,q,K),Number.isFinite(q))this.currentBoundaryOffset=q,this.currentSeekSegmentIndex=this.getCurrentSeekSegmentIndex()};try{await X.speakSegments(Q)}finally{if(Y===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=j}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let j of Q){if(Y!==this.speakRunId)return;let Z=this.seekSegments.findIndex((K)=>K.startOffset===j.startOffset);if(Z>=0)this.currentSeekSegmentIndex=Z;if(this.currentBoundaryOffset=j.startOffset,G)this.runWhenPlaybackStarts(Y,()=>{this.highlightSentenceSegment(j.startOffset,j.text)});await this.provider.speak(j.text);let q=j.pauseMsAfter??0;if(q>0)await new Promise((K)=>setTimeout(K,q))}}highlightSentenceSegment(Q,Y){if(!this.highlightCoordinator||typeof document>"u")return;let J=Y.trimEnd().length;if(J<=0)return;let G=this.normalizedToDOM.get(Q),X=this.normalizedToDOM.get(Q+J-1);if(!G||!X)return;let j=document.createRange();j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([j]),this.activeSentenceStartOffset=Q}getSegmentIndexForOffset(Q,Y){if(Q.length===0)return-1;let J=-1;for(let G=0;G<Q.length;G++)if(Q[G].startOffset<=Y)J=G;else break;return J}highlightSentenceForOffset(Q){let Y=this.sentenceHighlightSegments;if(!this.highlightCoordinator||Y.length===0)return;let J=this.getSegmentIndexForOffset(Y,Q);if(J<0)return;let G=Y[J];if(!G)return;if(this.activeSentenceStartOffset===G.startOffset)return;this.highlightSentenceSegment(G.startOffset,G.text)}findHighlightRange(Q,Y){let J=this.normalizedToDOM.get(Q);if(!J)return console.warn(`[TTSService] No mapping found for start position ${Q}`,{totalMappings:this.normalizedToDOM.size,nearbyMappings:Array.from(this.normalizedToDOM.entries()).filter(([j])=>Math.abs(j-Q)<5).map(([j,{offset:Z,node:q}])=>({pos:j,offset:Z,char:q.textContent?.[Z]}))}),null;let G=Q+Y-1,X=this.normalizedToDOM.get(G);if(!X)return console.warn(`[TTSService] No mapping found for end position ${G}`,{startChar:Q,length:Y,totalMappings:this.normalizedToDOM.size}),null;if(J.node!==X.node)return console.warn("[TTSService] Word spans multiple nodes, highlighting in first node only"),{node:J.node,start:J.offset,end:(J.node.textContent||"").length};return{node:J.node,start:J.offset,end:X.offset+1}}async speak(Q,Y){if(!this.provider)throw Error("TTS service not initialized");let J=++this.speakRunId;this.clearPlaybackStartBarrier();let G=null;try{if(await this.applyLanguageSettings(Y),J!==this.speakRunId)return;let X=await this.resolveSpeechContent(Q,Y);if(J!==this.speakRunId)return;let{contentToSpeak:j,speechText:Z,highlightText:q,normalizedText:K,usedCatalogSpoken:B,speechSource:U,speechMatchesVisibleText:H,speechChunks:_}=X;this.logResolvedSpeechContent({contentToSpeak:j,speechSource:U,catalogId:Y?.catalogId}),this.initializeSpeakTracking(q,Y);let A=Y?.highlightModeOverride||(H?this.resolveHighlightMode():"sentence");this.activeHighlightMode=A,this.activeWordBoundaryOffset=Y?.wordBoundaryOffset||0;let M=this.hasExplicitBreakSemantics(j),O=!!this.currentContentElement&&!B&&!M&&H;if(this.playbackChunks=_?.length?_:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):M||!H?[]:O&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,K):this.createSeekSegmentsFromText(q),this.sentenceHighlightSegments=M?[]:this.createSentenceHighlightSegments({contentToSpeak:q,shouldUsePlan:O,playbackSegments:this.seekSegments}),this.setState(E.LOADING),G=this.installPlaybackStartBarrier(J,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:q,options:Y,highlightMode:A,shouldUsePlan:O,runId:J}),H)this.configureWordBoundaryHighlighting({highlightMode:A,wordBoundaryOffset:Y?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(!G)this.setState(E.PLAYING);if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:O,runId:J,highlightMode:A,contentToSpeak:Z,speechChunks:_}),J!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking()}catch(X){let j=X;if(console.error("TTS error:",j),this.lastError=j instanceof Error?j.message:String(j),J!==this.speakRunId)return;throw this.setState(E.ERROR),this.clearHighlightsAndTracking(),j}finally{this.clearPlaybackStartBarrier(G)}}async switchProviderToBrowser(Q,Y){if(!this.currentProvider)return!1;let J=new R7,G=this.currentProvider.providerId,X={};if(this.ttsConfig.rate!==void 0)X.rate=this.ttsConfig.rate;if(this.ttsConfig.pitch!==void 0)X.pitch=this.ttsConfig.pitch;if(this.ttsConfig.mathTokenHighlighting!==void 0)X.mathTokenHighlighting=this.ttsConfig.mathTokenHighlighting;let j=Y?.operation||"tts-initialize",Z=Y?.contentToSpeak??"",q=Z.replace(/\s+/g," ").trim().slice(0,120),K=Z.length>0?{textLength:Z.length,textPreview:q.length<Z.length?`${q}…`:q}:{};try{return this.provider?.stop(),this.currentProvider.destroy(),this.currentProvider=J,this.provider=await J.initialize(X),this.ttsConfig=X,await this.emitTelemetry("pie-tool-runtime-fallback",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:J.providerId,reason:Q instanceof Error?Q.message:String(Q),...K}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:G,reason:Q,...K}),!0}catch(B){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:B instanceof Error?B.message:String(B)}),console.error("[TTSService] Failed to switch to browser fallback provider",B),!1}}isBrowserSpeechFallbackAvailable(){if(typeof window>"u")return!1;if(!("speechSynthesis"in window))return!1;return typeof globalThis.SpeechSynthesisUtterance==="function"}async applyLanguageSettings(Q){if(!Q?.language||!this.provider)return;let Y=this.ttsConfig.providerOptions||{},J=Y.textNormalization||{},G=Y.segmenter||{},X={...Y,locale:Q.language,textNormalization:{...J,locale:Q.language},segmenter:{...G,locale:Q.language}};if(this.ttsConfig={...this.ttsConfig,providerOptions:X},"updateSettings"in this.provider&&typeof this.provider.updateSettings==="function")await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Q,Y){let J=S(Q);if(Y?.ignoreCatalogs)return{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,usedCatalogSpoken:!1,speechSource:"dom-or-input",normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0};if(Y?.catalogId&&this.catalogResolver){let j=this.catalogResolver.getAlternative(Y.catalogId,{type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext,form:"content"}),Z=j?.content;if(j&&Z!==void 0){let q=Y?.contentElement?N7(Y.contentElement,this.getTextProcessingOptions(Y.language)).visibleText||J:J,K=S(Z);return this.debugLog(`[TTSService] Using catalog content for "${Y.catalogId}" (${j.language})`),{contentToSpeak:Z,speechText:Z,visibleText:q,highlightText:q,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:K===q}}this.debugLog(`[TTSService] No catalog found for "${Y.catalogId}", falling back to generated TTS`)}let G=Y?.contentElement?this.resolveCatalogComposedSpeechContent(Y.contentElement,J,Y):null;if(G)return G;return{...Y?.contentElement?await this.resolveGeneratedSpeechContent(Y.contentElement,J,Y.language):{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0},usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Q,Y,J){if(!this.catalogResolver)return null;let G=this.collectCatalogSpeechChunks(Q,J);if(!G.some((Z)=>Z.sourceElement))return null;let X=S(G.map((Z)=>Z.speechText).join(" ")),j=N7(Q,this.getTextProcessingOptions(J.language)).visibleText||Y;return{contentToSpeak:X,speechText:X,visibleText:j,highlightText:j,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:j,containsMathMarkup:!1,speechMatchesVisibleText:G.every((Z)=>Z.speechMatchesVisibleText),speechChunks:G}}collectCatalogSpeechChunks(Q,Y){let J=[],G="",X=()=>{let B=S(G);if(G="",!B)return;J.push({speechText:B,visibleText:B,sourceElement:null,speechMatchesVisibleText:!0})},j=(B)=>{let U=B.getAttribute("data-catalog-idref");if(!U)return null;let H={type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext},_=this.catalogResolver.getAlternative(U,{...H,form:"payload"}),A=_?.payload?V9({payload:_.payload})??void 0:void 0,O=this.catalogResolver.getAlternative(U,{...H,form:"content"})?.content;if(A===void 0&&O===void 0)return null;return{script:O,audio:A}},Z=(B,U)=>{let H=q(B);if(H.length!==1)return null;let _=H[0],A=N7(_,this.getTextProcessingOptions(Y.language)).visibleText||S(_.textContent||""),M=(O)=>S(O).replace(/\s+/g,"");return M(A)===M(U)?_:null},q=(B)=>{let U=Array.from(B.querySelectorAll("math"));if(B.localName?.toLowerCase()==="math")return[B,...U];return U},K=(B)=>{if(V7(B,Q))return;if(B.nodeType===Node.TEXT_NODE){G+=` ${B.textContent||""}`;return}if(B.nodeType!==Node.ELEMENT_NODE)return;let U=B,H=j(U);if(H){X();let _=N7(U,this.getTextProcessingOptions(Y.language)),A=_.visibleText||S(U.textContent||""),M=_1(U,Q),O=H.script!==void 0?(()=>{let L=H.script,F=U1({speechText:L,visibleText:A}),$=Z(U,A),b=$?S7({mathElement:$,speechText:L}):void 0,v=b?void 0:q(U).map((k)=>({element:k,alignment:S7({mathElement:k,speechText:L})}));return{speechText:L,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:S(L)===A,playbackMode:F.playbackMode,alignment:F,mathAlignment:b,mathAlignments:v,visibleMap:_.map}})():null;if(H.audio){J.push(O?{...O,audio:H.audio,plainFallback:O}:{speechText:A,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:!1,visibleMap:_.map,audio:H.audio});return}if(O)J.push(O);return}for(let _ of Array.from(U.childNodes))K(_)};return K(Q),X(),J}resolveGeneratedPlaybackFormat(){let Q=this.currentProvider;if(!Q)return"plain";if(Q.providerId?.toLowerCase()==="browser")return"plain";return Q.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Q,Y,J){let G=this.resolveGeneratedPlaybackFormat(),{plan:X,containsMathMarkup:j,visibleText:Z}=await A8({contentRoot:Q,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:G==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),q=Z||Y;if(!j)return{contentToSpeak:q,speechText:q,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:!0};let K=M8(X,{format:G}),B=X.plainSpeechText;return{contentToSpeak:B,speechText:B,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!0,speechMatchesVisibleText:B===q,speechChunks:K}}logResolvedSpeechContent(Q){let Y=Q.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);this.debugLog("[TTSService] Speak resolved content",{source:Q.speechSource,catalogId:Q.catalogId||null,length:Q.contentToSpeak.length,preview:Y})}initializeSpeakTracking(Q,Y){this.currentText=Q,this.currentContentElement=Y?.contentElement||null,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Q){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Q.contentToSpeak,Q.options?.language),Q.highlightMode==="sentence"&&Q.shouldUsePlan)return;let Y=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Q.runId,()=>{if(Y)this.highlightSentenceSegment(Y.startOffset,Y.text),this.debugLog("[TTSService] Applied initial sentence highlighting");else try{let J=document.createRange();J.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([J])}catch{}})}configureWordBoundaryHighlighting(Q){if(!this.provider||Q.highlightMode!=="word"||!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(Y,J,G)=>{let X=G||Y.length,j=J+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(j);let Z=this.findHighlightRange(j,X);if(Z&&this.highlightCoordinator){let q=Z.node.textContent?.substring(Z.start,Z.end)||"";this.debugLog(`[TTSService] Highlighting "${q}" (word: "${Y}") at position ${j}`);let K=this.createTextRange(Z.node,Z.start,Z.end);if(K)this.paintTTSWordRange(this.resolveWordHighlightRange(K).range);else this.highlightCoordinator.highlightTTSWord(Z.node,Z.start,Z.end)}else console.warn(`[TTSService] Could not find highlight range for position ${j}, length ${X}`)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Q){let Y=Q.regionElement||Q.sourceElement;if(!Y&&!Q.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Q.regionRange){this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!Y)return;let J=document.createRange();J.selectNodeContents(Y),this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([J])}catch{}}highlightCatalogActiveRange(Q){if(!this.highlightCoordinator)return;this.paintTTSWordRange(this.resolveWordHighlightRange(Q).range)}highlightRenderableRegionTarget(Q){if(!this.highlightCoordinator||!Q||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&u2(this.lastRenderedRegionTarget,Q))return;try{let Y=document.createRange();if(Q.type==="element")Y.selectNodeContents(Q.element);else if(Q.type==="range"){this.paintTTSSentenceRanges([Q.range]),this.lastRenderedRegionTarget=Q;return}else Y.setStart(Q.node,Q.startOffset),Y.setEnd(Q.node,Q.endOffset);this.paintTTSSentenceRanges([Y]),this.lastRenderedRegionTarget=Q}catch{}}highlightRenderableActiveTarget(Q){if(!this.highlightCoordinator||typeof document>"u")return;if(!Q){this.highlightCoordinator.clearHighlights(m.TTS_WORD);return}if(Q.type==="text-range"){let X=this.createTextRange(Q.node,Q.startOffset,Q.endOffset);if(X)this.paintTTSWordRange(this.resolveWordHighlightRange(X).range);else this.highlightCoordinator.highlightTTSWord(Q.node,Q.startOffset,Q.endOffset);return}if(Q.type==="range"){this.highlightCatalogActiveRange(Q.range);return}let Y=document.createRange();Y.selectNodeContents(Q.element);let J=this.resolveWordHighlightRange(Y);if(J.remapped){this.paintTTSWordRange(J.range);return}let G=Q.element.childNodes.length===1?Q.element.firstChild:null;if(Q.quality==="semantic-token"&&G?.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(G,0,G.textContent?.length||0);return}this.highlightCoordinator.highlightTTSWordElement?.(Q.element)}renderHighlightDecision(Q){this.highlightRenderableRegionTarget(Q.regionTarget),this.highlightRenderableActiveTarget(Q.activeTarget)}async speakCatalogChunk(Q,Y){try{await this.speakCatalogChunkOnce(Q,Y)}catch(J){if(Q.plainFallback&&Y===this.speakRunId){if(this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),this.playbackStartDeferredRunId===Y&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.setState(E.PLAYING);await this.speakCatalogChunkOnce(Q.plainFallback,Y);return}throw J}}async playRecordedAudio(Q,Y){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let J=Q.sources[0],G=document.createElement("audio");G.preload="auto",G.src=D9(J.src,Q.fragment),G.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,j)=>{let Z,q=!1,K=!1,B=()=>{if(K||q)return;q=!0,Y?.()},U=()=>{if(G.removeEventListener("ended",H),G.removeEventListener("error",_),G.removeEventListener("playing",B),Z!==void 0)clearInterval(Z);if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null},H=()=>{if(K)return;K=!0,U(),X()},_=()=>{if(K)return;K=!0,U(),j(Error(`[tts] recorded audio failed to play: ${J.src}`))};this.activeRecordedAudio={element:G,cancel:()=>{if(K)return;K=!0,U(),G.pause(),X()}},G.addEventListener("ended",H),G.addEventListener("error",_),G.addEventListener("playing",B);let A=Q.fragment?.endSeconds;if(A!==void 0)Z=setInterval(()=>{if(G.currentTime>=A)H()},100);Promise.resolve(G.play()).then(B).catch(_)}).finally(()=>{if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null;G.pause(),G.removeAttribute("src")})}cancelRecordedAudio(){let Q=this.activeRecordedAudio;if(!Q)return;this.activeRecordedAudio=null,Q.cancel()}async speakCatalogChunkOnce(Q,Y){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Q.audio){this.runWhenPlaybackStarts(Y,()=>{this.highlightCatalogRegion(Q)}),await this.playRecordedAudio(Q.audio,()=>{this.notifyPlaybackStarted(Y)});return}let J=Q.regionElement||Q.sourceElement||this.currentContentElement,G=J?z6({contentRoot:J,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,j=G?N6({chunks:[G],mathTokenHighlighting:X}):null;if(this.runWhenPlaybackStarts(Y,()=>{if(j&&G&&Q.mathAlignment)this.renderHighlightDecision(j.resolveInitial(G.id));else this.highlightCatalogRegion(Q)}),!(Q.sourceElement&&(Q.mathAlignment&&Q.mathAlignment.speech.tokens.length>0||Q.mathAlignments&&Q.mathAlignments.length>0||Q.alignment&&Q.visibleMap&&(Q.playbackMode==="exact-word"||Q.playbackMode==="anchor-span")))){let U=this.provider,H=U.onWordBoundary;U.onWordBoundary=void 0;try{await U.speak(Q.speechText)}finally{if(this.provider===U&&Y===this.speakRunId&&U.onWordBoundary===void 0)U.onWordBoundary=H}return}let q=this.provider,K=q.onWordBoundary,B=(U,H,_)=>{if(Y!==this.speakRunId)return;if(j&&G){let A=G.offsetSpace==="unsupported"?"unknown":G.offsetSpace;this.renderHighlightDecision(j.resolveBoundary({chunkId:G.id,word:U,position:H,length:_,providerOffsetSpace:A}));return}};q.onWordBoundary=B;try{await q.speak(Q.speechText)}finally{if(this.provider===q&&Y===this.speakRunId&&q.onWordBoundary===B)q.onWordBoundary=K}}async executeSpeakPlayback(Q){if(Q.speechChunks?.length&&this.provider){for(let Y=0;Y<Q.speechChunks.length;Y++){if(Q.runId!==this.speakRunId)return;this.currentSeekSegmentIndex=Y;let J=this.seekSegments[Y];if(J)this.currentBoundaryOffset=J.startOffset;let G=Q.speechChunks[Y];await this.speakCatalogChunk(G,Q.runId)}return}if(Q.shouldUsePlan&&this.currentContentElement){let Y=this.seekSegments;if(Y.length>0)await this.speakWithPlan(Y,Q.runId,{highlightMode:Q.highlightMode});else if(this.provider)await this.provider.speak(Q.contentToSpeak);return}if(this.provider)await this.provider.speak(Q.contentToSpeak)}clearHighlightsAndTracking(){if(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.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}async speakRange(Q,Y){if(!this.provider)throw Error("TTS service not initialized");if(q1(Q.commonAncestorContainer)){console.warn("[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.");return}let G=Y?.contentRoot||null;if(!G){let U=Q.commonAncestorContainer;G=U.nodeType===Node.ELEMENT_NODE?U:U.parentElement}if(!G)return;let X=Q8(Q,G),j=X.text.trim();if(!j){if(X.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return}let Z=document.createRange();Z.selectNodeContents(G),Z.setEnd(Q.startContainer,Q.startOffset);let q=Q8(Z,G).text,K=S(q),B=K.length+(/\s$/.test(q)&&K?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:j,textBeforeRange:q.substring(0,100),offset:B,rootTag:G.tagName}),await this.speak(j,{contentElement:G,ignoreCatalogs:!0,wordBoundaryOffset:B})}pause(){if(!this.provider)return;if(this.state===E.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(E.PAUSED)}resume(){if(!this.provider)return;if(this.state===E.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState(E.PLAYING)}}normalizePlaybackRate(Q){if(!Number.isFinite(Q))return 1;return Math.max(0.25,Math.min(4,Q))}async restartFromSeekIndex(Q){if(!this.provider||this.seekSegments.length===0)return;let Y=Math.max(0,Math.min(this.seekSegments.length-1,Q)),J=this.playbackChunks.length?this.playbackChunks.slice(Y):null;this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=Y;let G=++this.speakRunId,X=this.seekSegments.slice(Y);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.setState(E.LOADING);let j=this.installPlaybackStartBarrier(G,!!J?.[0]?.audio);if(!j)this.setState(E.PLAYING);this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),J)for(let Z=0;Z<J.length;Z++){if(G!==this.speakRunId)return;let q=Y+Z;this.currentSeekSegmentIndex=q;let K=this.seekSegments[q];if(K)this.currentBoundaryOffset=K.startOffset;await this.speakCatalogChunk(J[Z],G)}else await this.speakWithPlan(X,G,{highlightMode:this.activeHighlightMode});if(G!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null}catch(Z){if(G!==this.speakRunId)return;throw this.lastError=Z instanceof Error?Z.message:String(Z),this.setState(E.ERROR),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null,Z}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.normalizePlaybackRate(Q),J=this.pendingPlaybackRateRequest;if(J?.rate===Y){await J.promise;return}let G=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let q=this.speakRunId;if(G!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:q};let K=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Y===K)return{didUpdate:!1,playbackRunId:q};return await this.updateSettings({rate:Y}),{didUpdate:!0,playbackRunId:q}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let j=X.then(async(q)=>{if(G!==this.playbackRateRequestId||q.playbackRunId!==this.speakRunId)return;let K=this.activePlaybackRate!==null&&this.activePlaybackRate!==Y;if(!q.didUpdate&&!K)return;if(this.state!==E.PLAYING&&this.state!==E.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),Z;Z=j.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===Z)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:Y,promise:Z},await Z}async seekBy(Q){if(!this.provider||!this.currentText)return;if(this.state!==E.PLAYING&&this.state!==E.PAUSED)return;if(this.hasExplicitBreakSemantics(this.currentText))return;if(this.seekSegments.length===0)return;let Y=Number.isFinite(Q)?Math.trunc(Q):0;if(Y===0)return;let J=this.getCurrentSeekSegmentIndex(),G=Math.max(0,Math.min(this.seekSegments.length-1,J+Y));if(G===J)return;await this.restartFromSeekIndex(G)}async seekForward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(Y)}async seekBackward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(-Y)}stop(){if(!this.provider)return;if(this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.highlightTargetResolverProvider=null,this.setState(E.IDLE),this.currentText=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.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null,this.activePlaybackRate=null}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(P6,{detail:Q}))}isPlaying(){return this.state===E.PLAYING}isPaused(){return this.state===E.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(Q,Y){if(!this.listeners.has(Q))this.listeners.set(Q,new Set);this.listeners.get(Q).add(Y)}offStateChange(Q,Y){let J=this.listeners.get(Q);if(J){if(J.delete(Y),J.size===0)this.listeners.delete(Q)}}setState(Q){if(this.state===Q)return;let Y=this.state;this.state=Q;for(let J of this.listeners.values())for(let G of J)G(Q);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q}),Q===E.PLAYING){let J=Y===E.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(J,{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q,message:this.lastError||void 0});return}if(Q===E.IDLE&&(Y===E.PLAYING||Y===E.PAUSED||Y===E.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q})}}var p2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),$6=(Q)=>Q&&typeof Q==="object"?Q:{},g2=(Q)=>Q==="polly"||Q==="google"||Q==="server",c=(Q,Y)=>Q===void 0?Y:Q,c2=(Q,Y="left-aligned")=>typeof Q==="string"&&p2.has(Q)?Q:Y,y4=Object.freeze([0.8,1.25]),x4=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 f4=Object.freeze([0.8,1,1.25]);var l2=(Q)=>{let Y={...Q,layoutMode:c2(Q.layoutMode)},J=Q.backend||"browser";if(!g2(J))return Y;let G={...Y,apiEndpoint:c(Y.apiEndpoint,"/api/tts"),transportMode:c(Y.transportMode,"pie"),endpointValidationMode:c(Y.endpointValidationMode,"voices"),validateEndpoint:c(Y.validateEndpoint,!0),includeAuthOnAssetFetch:c(Y.includeAuthOnAssetFetch,!1),rate:c(Y.rate,1),language:c(Y.language,"en-US")};if(J==="polly")return{...G,defaultVoice:c(G.defaultVoice,"Joanna"),engine:c(G.engine,"neural"),format:c(G.format,"mp3"),speechMarksMode:c(G.speechMarksMode,"word+sentence")};if(J==="google")return{...G,defaultVoice:c(G.defaultVoice,"en-US-Wavenet-A")};return G},w6=(Q)=>{let Y=$6(Q),J=$6(Y.settings);return l2({...Y,...J})},N8=(Q)=>Q.backend||"browser",d2=(Q,Y)=>{if(Y==="polly"||Y==="google")return Y;if(Y==="server")return Q.serverProvider||Q.provider;return Q.serverProvider||Q.provider},i2=(Q,Y)=>Q.transportMode||(Y==="custom"?"custom":"pie"),R6=(Q)=>{let Y=N8(Q),J=d2(Q,Y),G=i2(Q,J),X=z7(Q.mathSpeech);return{voice:Q.defaultVoice,rate:Q.rate,pitch:Q.pitch,providerOptions:{...Q.language?{locale:Q.language}:{},...Y==="polly"&&Q.engine?{engine:Q.engine}:{},...Y==="polly"&&typeof Q.sampleRate==="number"?{sampleRate:Q.sampleRate}:{},...Y==="polly"&&Q.format?{format:Q.format}:{},...Y==="polly"?{speechMarkTypes:Q.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...G==="custom"&&typeof Q.cache==="boolean"?{cache:Q.cache}:{},...G==="custom"&&Q.speedRate?{speedRate:Q.speedRate}:{},...G==="custom"&&Q.lang_id?{lang_id:Q.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Q.apiEndpoint,provider:J,language:Q.language,transportMode:G,endpointMode:Q.endpointMode,endpointValidationMode:Q.endpointValidationMode,includeAuthOnAssetFetch:Q.includeAuthOnAssetFetch,validateEndpoint:Q.validateEndpoint,...typeof Q.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Q.mathTokenHighlighting}:{}}};class F1{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Q,Y,J){try{await Q.onTelemetry?.(Y,J)}catch(G){console.warn("[ToolProviderRegistry] Telemetry callback failed:",G)}}register(Q,Y){if(this.providers.has(Q)){console.warn(`[ToolProviderRegistry] Provider "${Q}" already registered, skipping`);return}if(this.providers.set(Q,Y.provider),this.configs.set(Q,Y),this.initialized.set(Q,!1),console.log(`[ToolProviderRegistry] Registered provider "${Q}" (${Y.provider.providerName})`),Y.lazy===!1)this.initialize(Q).catch((J)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Q}":`,J)})}async initialize(Q){if(this.initialized.get(Q))return;let Y=this.initializationPromises.get(Q);if(Y)return Y;let J=this._doInitialize(Q);this.initializationPromises.set(Q,J);try{await J}finally{this.initializationPromises.delete(Q)}}async _doInitialize(Q){let Y=this.providers.get(Q),J=this.configs.get(Q);if(!Y||!J)throw Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);let G={...J.config},X=(Z)=>{if(!Z||typeof Z!=="object")return"unknown";let q=Z;return(typeof q.backend==="string"?q.backend:typeof q.provider==="string"?q.provider:typeof q.serverProvider==="string"?q.serverProvider:typeof q.providerId==="string"?q.providerId:"")||"unknown"},j=Date.now();if(await this.emitTelemetry(J,"pie-tool-init-start",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize"}),Y.requiresAuth&&J.authFetcher){let Z=Date.now();await this.emitTelemetry(J,"pie-tool-backend-call-start",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch"}),console.log(`[ToolProviderRegistry] Fetching auth for "${Q}"...`);try{let q=await J.authFetcher();G={...G,...q},await this.emitTelemetry(J,"pie-tool-backend-call-success",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z})}catch(q){throw await this.emitTelemetry(J,"pie-tool-backend-call-error",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z,errorType:"ProviderAuthFetchError",message:q instanceof Error?q.message:String(q)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Q}":`,q),Error(`Failed to fetch auth credentials for provider "${Q}"`)}}try{await Y.initialize(G),this.initialized.set(Q,!0),await this.emitTelemetry(J,"pie-tool-init-success",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j}),console.log(`[ToolProviderRegistry] Provider "${Q}" initialized`)}catch(Z){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j,errorType:"ProviderInitializationError",message:Z instanceof Error?Z.message:String(Z)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Q}":`,Z),Z}}async getProvider(Q,Y=!0){console.log("[ToolProviderRegistry] getProvider called",{providerId:Q,autoInitialize:Y,isRegistered:this.providers.has(Q),isInitialized:this.initialized.get(Q),allProviderIds:Array.from(this.providers.keys())});let J=this.providers.get(Q);if(!J)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Q,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);if(Y&&!this.initialized.get(Q))console.log("[ToolProviderRegistry] Auto-initializing provider:",Q),await this.initialize(Q);return console.log("[ToolProviderRegistry] Returning provider:",{providerId:Q,providerName:J.providerName,isReady:J.isReady()}),J}getProvidersByCategory(Q){return Array.from(this.providers.entries()).filter(([Y,J])=>J.category===Q).map(([Y])=>Y)}getProviderIds(){return Array.from(this.providers.keys())}has(Q){return this.providers.has(Q)}isInitialized(Q){return this.initialized.get(Q)===!0}isInitializing(Q){return this.initializationPromises.has(Q)}async unregister(Q){let Y=this.providers.get(Q);if(Y){let J=this.initializationPromises.get(Q);if(J)try{await J}catch{}Y.destroy(),this.providers.delete(Q),this.configs.delete(Q),this.initialized.delete(Q),this.initializationPromises.delete(Q),console.log(`[ToolProviderRegistry] Unregistered provider "${Q}"`)}}async destroy(){let Q=Array.from(this.providers.keys());await Promise.all(Q.map((Y)=>this.unregister(Y))),console.log("[ToolProviderRegistry] Registry destroyed")}}var s2=(Q)=>`No assessment is bound, so no policy source could grant "${Q}"`;function E6(Q,Y,J){let G=Y.decisions[0],X=Array.from(Y.perToolFlags.values())[0],j=G?.action==="enable",Z=G?.reason??`Feature "${Q}" not configured`;return{featureId:Q,granted:j,action:G?.action??"skip",rule:G?.rule??"pnp-support",precedence:G?.precedence??6,sourceType:G?.sourceType??"system",reason:J.assessmentBound||j?Z:s2(Q),required:Boolean(X?.required),parameters:X?.settings,assessmentBound:J.assessmentBound}}class A1{provenance;stepCounter=0;constructor(Q){this.provenance={contextId:Q,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Q,Y){let J={id:Y.id,name:Y.name??Y.id};switch(Q){case"organization":this.provenance.sources.organization={...J,pnpDefaults:Y.config};break;case"assessment":this.provenance.sources.assessment={...J,settings:Y.config};break;case"section":this.provenance.sources.section={...J,settings:Y.config};break;case"item":this.provenance.sources.item={...J,settings:Y.config};break;case"student":this.provenance.sources.student={id:Y.id,pnpProfile:Y.config};break;case"host":this.provenance.sources.host={id:Y.id,config:Y.config};break}return this}addDecision(Q){let Y={step:++this.stepCounter,precedence:Q.precedence,rule:Q.rule,featureId:Q.featureId,action:Q.action,source:{type:Q.sourceType,id:Q.sourceId,name:Q.sourceName},reason:Q.reason,value:Q.value,timestamp:new Date};this.provenance.decisionLog.push(Y);let J=this.provenance.features.get(Q.featureId);if(!J)J={featureId:Q.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Q.featureId,J);if(J.allDecisions.push(Y),Q.action==="advisory"){if(J.finalState==="not-configured")J.finalState="advisory-only"}else if(Q.action!=="skip"){if(!J.winningDecision||Y.precedence<J.winningDecision.precedence)J.winningDecision=Y,J.finalState=Y.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Q.sourceType]=(this.provenance.summary.bySource[Q.sourceType]||0)+1,this.provenance.summary.byRule[Q.rule]=(this.provenance.summary.byRule[Q.rule]||0)+1,this}reconcileFinalStates(Q){for(let Y of Q){let J=this.provenance.features.get(Y);if(!J){J={featureId:Y,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(Y,J);continue}J.finalState="enabled"}for(let Y of this.provenance.features.values()){if(Q.has(Y.featureId))continue;let J=Y.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),G=Y.allDecisions.some((X)=>X.action==="advisory");if(J)Y.finalState="blocked";else if(G)Y.finalState="advisory-only";else Y.finalState="not-configured"}return this}build(){for(let Q of this.provenance.features.values())Q.explanation=n2(Q);for(let Q of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Q.finalState==="enabled")this.provenance.summary.enabled++;else if(Q.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function n2(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let j=Q.allDecisions.find((Z)=>Z.action==="advisory");return j?`Feature "${Q.featureId}" was kept in its host-decided state; ${j.reason}`:`Feature "${Q.featureId}" carries an advisory note.`}return`Feature "${Q.featureId}" was not configured at any level.`}let Y=Q.winningDecision,J=Y.source.name||Y.source.type,G=`Feature "${Q.featureId}" is ${Q.finalState}.
|
|
215
|
+
`,document.head.appendChild(Q)}highlightTTSWord(Q,G,Y){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q.parentElement),this.clearTTSWord();let J=document.createRange();J.setStart(Q,G),J.setEnd(Q,Y),this.ttsWordHighlight.add(J)}highlightTTSWordElement(Q){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q),this.clearTTSWord(),Q.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Q)}highlightTTSSentence(Q){if(!this.ttsSentenceHighlight)return;let G=Q[0]?.startContainer,Y=G?.nodeType===Node.ELEMENT_NODE?G:G?.parentElement;this.applyAdaptiveTTSStyle(Y),this.clearTTSSentence();for(let J of Q)this.ttsSentenceHighlight.add(J);this.highlightTTSElementFallbacks(Q)}highlightTTSSentenceElements(Q){if(!this.ttsSentenceHighlight)return;this.applyAdaptiveTTSStyle(Q[0]||null),this.clearTTSSentence();for(let G of Q)G.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(G)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,u7.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-word-element",this.ttsWordElementHighlights,u7.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Q,G,Y,J){for(let X of Q){let j=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!j)continue;let Z=[],K=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,W=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let B of[K,W]){let U=B;while(U){if(U.matches?.(J))Z.push(U);U=U.parentElement}}if(j.matches?.(J))Z.push(j);Z.push(...Array.from(j.querySelectorAll(J)));for(let B of new Set(Z)){try{if(!X.intersectsNode(B)&&!B.contains(K)&&!B.contains(W))continue}catch{continue}B.setAttribute(G,"true"),Y.add(B)}}}clearTTSWord(){if(!this.ttsWordHighlight)return;this.ttsWordHighlight.clear();for(let Q of this.ttsWordElementHighlights)Q.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.ttsSentenceHighlight)return;this.ttsSentenceHighlight.clear();for(let Q of this.ttsSentenceElementHighlights)Q.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){this.clearTTSWord(),this.clearTTSSentence()}addAnnotation(Q,G=_7.YELLOW){let Y=`annotation-${this.nextAnnotationId++}`,J=Q.cloneRange(),X={id:Y,range:J,type:u.ANNOTATION,color:G,timestamp:Date.now()};this.annotations.set(Y,X);let j=this.colorHighlights.get(G);if(j)j.add(J);return Y}removeAnnotation(Q){let G=this.annotations.get(Q);if(!G){console.warn(`[HighlightCoordinator] Annotation ${Q} not found`);return}console.log(`[HighlightCoordinator] Removing annotation ${Q} (color: ${G.color})`);let Y=this.colorHighlights.get(G.color);if(Y){let J=Y.delete(G.range);console.log("[HighlightCoordinator] Highlight.delete() returned:",J)}this.annotations.delete(Q),console.log(`[HighlightCoordinator] Annotation ${Q} removed from map. Remaining:`,this.annotations.size)}clearAnnotations(){for(let Q of this.colorHighlights.values())Q.clear();this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Q){return this.annotations.get(Q)??null}changeAnnotationColor(Q,G){let Y=this.annotations.get(Q);if(!Y)return;let J=Y.color;if(J===G)return;let X=this.colorHighlights.get(J);if(X)X.delete(Y.range);Y.color=G;let j=this.colorHighlights.get(G);if(j)j.add(Y.range)}exportAnnotations(Q=document.body){return this.getAnnotations().map((G)=>({...this.rangeSerializer.serialize(G.range,Q),id:G.id,color:G.color,timestamp:G.timestamp}))}importAnnotations(Q,G=document.body){let Y=0;for(let J of Q){let X=this.rangeSerializer.deserialize(J,G);if(X)this.addAnnotation(X,J.color),Y++}return Y}highlightRange(Q,G,Y=_7.YELLOW){if(!this.supported)return;switch(G){case u.TTS_WORD:case u.TTS_SENTENCE:{let J=G===u.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(J){if(J.clear(),J.add(Q),G===u.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case u.ANNOTATION:this.addAnnotation(Q,Y);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case u.TTS_WORD:this.clearTTSWord();break;case u.TTS_SENTENCE:this.clearTTSSentence();break;case u.ANNOTATION:this.clearAnnotations();break}}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}isSupported(){return this.supported}updateTTSHighlightStyle(Q,G){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById("pie-highlight-styles"))return;let X=((j)=>{let Z=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(j);return Z?{r:parseInt(Z[1],16),g:parseInt(Z[2],16),b:parseInt(Z[3],16)}:null})(Q);if(!X)return;this.explicitTTSColorOverride={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,G))},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),typeof document<"u"){let Q=document.getElementById("pie-highlight-styles");if(Q)Q.remove()}this.themeObserver?.disconnect(),this.themeObserver=null}}function H6(Q){return(...G)=>{console.debug(`[${Q}]`,...G)}}var a=H6("ToolCoordinator"),Z7;(function(Q){Q[Q.BASE=0]="BASE",Q[Q.TOOL=1000]="TOOL",Q[Q.MODAL=2000]="MODAL",Q[Q.CONTROL=3000]="CONTROL",Q[Q.HIGHLIGHT=4000]="HIGHLIGHT"})(Z7||(Z7={}));class Y8{config;tools=new Map;layerCounters=new Map;listeners=new Set;visibilityState=new Map;constructor(Q={}){this.config=Q,this.layerCounters.set(Z7.BASE,0),this.layerCounters.set(Z7.TOOL,0),this.layerCounters.set(Z7.MODAL,0),this.layerCounters.set(Z7.CONTROL,0),this.layerCounters.set(Z7.HIGHLIGHT,0)}subscribe(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}notifyListeners(){this.listeners.forEach((Q)=>Q())}registerTool(Q,G,Y,J=Z7.MODAL){if(a("registerTool called:",{id:Q,name:G,hasElement:!!Y,layer:J}),this.tools.has(Q)){a(`Tool ${Q} is already registered`);return}let X=this.visibilityState.get(Q)??!1;if(!Y){this.tools.set(Q,{id:Q,name:G,element:null,layer:J,isVisible:X,baseZIndex:J}),a("Tool registered without element:",Q);return}let j=J+this.getNextLayerOffset(J);Y.style.zIndex=String(j),Y.style.display=X?"":"none";let Z=()=>this.bringToFront(Y);if(Y.addEventListener("mousedown",Z),this.tools.set(Q,{id:Q,name:G,element:Y,layer:J,isVisible:X,baseZIndex:j,mouseDownHandler:Z}),X)this.bringToFront(Y);a("Tool registered with element:",Q)}unregisterTool(Q){let G=this.tools.get(Q);if(!G)return;if(G.element&&G.mouseDownHandler)G.element.removeEventListener("mousedown",G.mouseDownHandler);this.tools.delete(Q)}releaseTool(Q){this.unregisterTool(Q),this.visibilityState.delete(Q)}showTool(Q){let G=this.tools.get(Q);if(!G){a(`Tool ${Q} not found`);return}if(G.element)G.element.style.display="",this.bringToFront(G.element);G.isVisible=!0,this.visibilityState.set(Q,!0),this.notifyListeners()}hideTool(Q){let G=this.tools.get(Q);if(!G){a(`Tool ${Q} not found`);return}if(G.element)G.element.style.display="none";G.isVisible=!1,this.visibilityState.set(Q,!1),this.notifyListeners()}toggleTool(Q){a("toggleTool called for:",Q);let G=this.tools.get(Q);if(!G){a(`Tool ${Q} not found. Registered tools:`,Array.from(this.tools.keys()));return}if(a("Tool found, current visibility:",G.isVisible),G.isVisible)this.hideTool(Q);else this.showTool(Q)}isToolVisible(Q){let G=this.tools.get(Q);if(G)return G.isVisible;return this.visibilityState.get(Q)??!1}bringToFront(Q){let G=Array.from(this.tools.values()).find((X)=>X.element===Q);if(!G)return;let Y=this.getMaxZIndexInLayer(G.layer),J=Math.max(Y+1,G.layer+1);Q.style.zIndex=String(J),G.baseZIndex=J}getRegisteredTools(){return Array.from(this.tools.keys())}getToolElement(Q){return this.tools.get(Q)?.element??null}getNextLayerOffset(Q){let G=this.layerCounters.get(Q)??0;return this.layerCounters.set(Q,G+1),G}getMaxZIndexInLayer(Q){let G=Q;for(let Y of this.tools.values())if(Y.layer===Q)G=Math.max(G,Y.baseZIndex);return G}resetZIndices(){for(let Q of this.tools.values())if(Q.element)Q.element.style.zIndex=String(Q.baseZIndex)}updateToolElement(Q,G){let Y=this.tools.get(Q);if(!Y){a(`Tool ${Q} not found`);return}if(Y.element&&Y.mouseDownHandler)Y.element.removeEventListener("mousedown",Y.mouseDownHandler);let J=()=>this.bringToFront(G);if(G.addEventListener("mousedown",J),Y.element=G,Y.mouseDownHandler=J,G.style.zIndex=String(Y.baseZIndex),Y.isVisible)G.style.display="";else G.style.display="none"}hideAllTools(){for(let Q of this.tools.keys())this.hideTool(Q);this.notifyListeners()}getToolState(Q){let G=this.tools.get(Q);if(!G)return;return{id:G.id,name:G.name,isVisible:G.isVisible,element:G.element??null,layer:G.layer}}getVisibleTools(){return Array.from(this.tools.values()).filter((Q)=>Q.isVisible).map((Q)=>({id:Q.id,name:Q.name,isVisible:Q.isVisible,element:Q.element??null,layer:Q.layer}))}}var L5=/^[a-z][a-z0-9+.-]*:/i,$5=new Set(["http:","https:","data:","blob:"]);function F6(Q){return Q!==void 0&&Q!==1}function w5(Q){if(typeof Q!=="string")return!1;let G=Q.trim();if(!G)return!1;if(G.startsWith("//")||!L5.test(G))return!0;let Y=G.slice(0,G.indexOf(":")+1).toLowerCase();return $5.has(Y)}function A6(Q){if(!Array.isArray(Q))return[];let G=[];for(let Y of Q){if(!Y||typeof Y!=="object")continue;let J=Y;if(!w5(J.src))continue;let X={src:J.src.trim()};if(typeof J.type==="string"&&J.type.trim())X.type=J.type.trim();if(Number.isFinite(J.width))X.width=J.width;if(Number.isFinite(J.height))X.height=J.height;if(G.some((j)=>j.src===X.src))continue;G.push(X)}return G}function N6(Q){if(!Q||typeof Q!=="object")return;let G=Q,Y=Number(G.startSeconds);if(!Number.isFinite(Y)||Y<0)return;let J=Number(G.endSeconds);if(!Number.isFinite(J)||J<=Y)return{startSeconds:Y};return{startSeconds:Y,endSeconds:J}}function M6(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}var R5=100,E5=1;function O6(Q,G,Y){if(!G)return()=>{};let{startSeconds:J,endSeconds:X}=G,j;if(J>0)if(j=()=>{if(Q.currentTime<J)Q.currentTime=J},Q.readyState>=E5)j();else Q.addEventListener("loadedmetadata",j);let Z,K;if(X!==void 0)Z=()=>{if(Q.currentTime>=X)Y()},Q.addEventListener("timeupdate",Z),K=setInterval(()=>{if(!Q.paused)Z?.()},R5);return()=>{if(j)Q.removeEventListener("loadedmetadata",j);if(Z)Q.removeEventListener("timeupdate",Z);if(K!==void 0)clearInterval(K)}}function z6(Q,G){if(!G)return Q;if(Q.includes("#"))return Q;let Y=G.endSeconds!==void 0?`,${G.endSeconds}`:"";return`${Q}#t=${G.startSeconds}${Y}`}function P6(Q){if(!Q)return null;let G=Q.payload;if(!G||typeof G!=="object")return null;let Y=G.media;if(!Y||typeof Y!=="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(F6(Y.version))return console.warn(`[spoken-audio] card's media declares version ${String(Y.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`),null;if(Y.kind!==void 0&&Y.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${Y.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let J=A6(Y.sources);if(J.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:J,fragment:N6(G.fragment),label:M6(Y.label)}}var E7=(Q,G)=>{let Y=G?.useSentenceSegmenter!==!1;try{if(!Y)throw Error("Segmenter disabled by policy");let K=globalThis.Intl?.Segmenter;if(typeof K==="function"){let W=new K(G?.locale,{granularity:"sentence"}),B=Array.from(W.segment(Q)).map((U)=>({text:U.segment,offset:U.index})).filter((U)=>U.text.trim().length>0);if(B.length>0)return B}}catch{}let J=/[^.!?]+(?:[.!?]+|$)/g,X=Q.match(J)||[Q],j=[],Z=0;for(let K of X){let W=Q.indexOf(K,Z);if(W===-1)continue;j.push({text:K,offset:W}),Z=W+K.length}return j.length>0?j:[{text:Q,offset:0}]};var L6=5000,$6=2000,w6=(Q)=>String(Q||"").trim().toLowerCase(),b5=()=>{let Q=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return w6(Q||"en-US")},C5=(Q,G)=>{if(G)return Q.find((Z)=>Z.voiceURI===G)||Q.find((Z)=>Z.name===G)||null;let Y=b5(),J=Y.split("-")[0]||"en",X=(Z)=>{let K=w6(Z.lang);return K===Y||K.startsWith(`${J}-`)},j=[(Z)=>Z.localService&&X(Z),(Z)=>Z.default&&X(Z),(Z)=>X(Z),(Z)=>Z.localService,(Z)=>Z.default];for(let Z of j){let K=Q.find(Z);if(K)return K}return Q[0]||null},T5=(Q)=>!Q.default;class b7{providerId="browser";providerName="Browser Speech Synthesis";version="1.0.0";async initialize(Q){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return new R6(Q)}supportsFeature(Q){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}}class R6{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;settlePendingVoiceWait=null;settlePendingChunk=null;onPlaybackStart=void 0;constructor(Q){this.config=Q}waitForBrowserVoices(Q,G){return new Promise((Y,J)=>{let X=speechSynthesis,j=typeof X.addEventListener==="function"&&typeof X.removeEventListener==="function",Z=j?null:X.onvoiceschanged,K=!1,W=null,B=null,U=()=>{if(W!==null)clearTimeout(W),W=null;if(j)X.removeEventListener("voiceschanged",N);else if(X.onvoiceschanged===O)X.onvoiceschanged=Z;if(B&&this.settlePendingVoiceWait===B)this.settlePendingVoiceWait=null},V=(P,$)=>{if(K)return;if(K=!0,U(),$)J($);else Y(P)},H=()=>{if(Q!==this.speakRunId){V(!1);return}if(X.getVoices().length>0)V(!0)},N=()=>H(),O=(P)=>{try{Z?.call(X,P)}finally{H()}};if(B=()=>V(!1),this.settlePendingVoiceWait=B,W=setTimeout(()=>V(!1,Error(`Configured browser voice "${G}" could not be resolved because the browser did not publish its voice inventory within ${$6/1000} seconds.`)),$6),j)X.addEventListener("voiceschanged",N);else X.onvoiceschanged=O;H()})}async resolveBrowserVoice(Q){let G=typeof this.config?.voice==="string"?this.config.voice.trim():"",Y=speechSynthesis.getVoices();if(G&&Y.length===0){if(!await this.waitForBrowserVoices(Q,G)||Q!==this.speakRunId)return{shouldContinue:!1,voice:null};Y=speechSynthesis.getVoices()}if(Q!==this.speakRunId)return{shouldContinue:!1,voice:null};let J=C5(Y,G||void 0);if(G&&!J)throw Error(`Configured browser voice "${G}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:J}}async speak(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let G=this.speakRunId,Y=await this.resolveBrowserVoice(G);if(!Y.shouldContinue)return;let J=this.splitIntoChunks(Q);for(let X of J){if(G!==this.speakRunId)break;if(!await this.speakChunk(X.text,X.offset,G,Y.voice))break}}async speakSegments(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let G=this.speakRunId,Y=await this.resolveBrowserVoice(G);if(!Y.shouldContinue)return;for(let J of Q){if(G!==this.speakRunId)break;let X=this.splitIntoChunks(J.text);for(let Z of X){if(G!==this.speakRunId)break;if(!await this.speakChunk(Z.text,J.startOffset+Z.offset,G,Y.voice))break}let j=Math.max(0,Number(J.pauseMsAfter||0));if(j>0&&G===this.speakRunId){if(!await this.waitForPause(j,G))break}}}async waitForPause(Q,G){return await new Promise((Y)=>setTimeout(Y,Q)),G===this.speakRunId}splitIntoChunks(Q){if(Q.length<=260)return[{text:Q,offset:0}];let Y=this.segmentSentences(Q),J=[],X="",j=0;for(let Z of Y){let K=Z.text.trim();if(!K)continue;let W=Z.text.search(/\S/),B=Z.offset+(W===-1?0:W);if(!X){X=K,j=B;continue}let U=`${X} ${K}`;if(U.length<=260)X=U;else J.push({text:X,offset:j}),X=K,j=B}if(X)J.push({text:X,offset:j});return J.length?J:[{text:Q,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){let Q=this.config?.providerOptions||{},G=Q.segmenter||{},J=G.mode!=="regexOnly",X=typeof G.locale==="string"&&G.locale.trim().length>0?G.locale:typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:void 0;return{useSentenceSegmenter:J,useWordSegmenter:J,locale:X}}segmentSentences(Q){let G=this.getSegmentationPolicy();return E7(Q,{locale:G.locale,useSentenceSegmenter:G.useSentenceSegmenter})}inferWordLength(Q,G){let Y=Math.max(0,Math.min(G,Math.max(0,Q.length-1)));return Q.slice(Y).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Q,G,Y,J){return new Promise((X,j)=>{if(Y!==this.speakRunId){X(!1);return}let Z=new SpeechSynthesisUtterance(Q);if(this.utterance=Z,J&&T5(J))Z.voice=J;if(this.config?.rate)Z.rate=this.config.rate;if(this.config?.pitch)Z.pitch=this.config.pitch;let K=!1,W=!1,B=null,U=null,V=()=>{if(this.utterance===Z)this.utterance=null},H=()=>{if(B!==null)clearTimeout(B),B=null},N=()=>{Z.onstart=null,Z.onend=null,Z.onerror=null,Z.onpause=null,Z.onresume=null,Z.onboundary=null},O=($,F)=>{if(W)return;if(W=!0,H(),N(),V(),U&&this.settlePendingChunk===U)this.settlePendingChunk=null;if(Y===this.speakRunId)this._isPlaying=!1,this._isPaused=!1;if(F)j(F);else X($)},P=($)=>Error($==="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 ${L6/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);U=()=>O(!1),this.settlePendingChunk=U,Z.onstart=()=>{if(Y!==this.speakRunId){O(!1);return}K=!0,H(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch($){console.error("Browser TTS playback-start callback failed",$)}},Z.onend=()=>{if(Y!==this.speakRunId){O(!1);return}if(!K){O(!1,P("ended"));return}O(!0)},Z.onerror=($)=>{if(Y!==this.speakRunId){O(!1);return}if($.error==="interrupted"||$.error==="canceled"){O(!1);return}O(!1,Error(`Speech synthesis error: ${$.error}`))},Z.onpause=()=>{if(Y!==this.speakRunId)return;this._isPaused=!0},Z.onresume=()=>{if(Y!==this.speakRunId)return;this._isPaused=!1},Z.onboundary=($)=>{if(Y!==this.speakRunId)return;if(console.log("[BrowserProvider] Boundary event:",$.name,"charIndex:",$.charIndex,"charLength:",$.charLength),$.name!=="word"||!this.onWordBoundary)return;if(this.getHighlightMode()==="sentence")return;let F=Math.max(0,Math.min($.charIndex,Math.max(0,Q.length-1))),L=Number($.charLength||0),C=this.inferWordLength(Q,F),v=Number.isFinite(L)&&L>0&&L<=80&&F+L<=Q.length?L:C,I=Q.substring(F,Math.min(Q.length,F+v)).trim(),p=G+F;console.log("[BrowserProvider] Calling onWordBoundary with word:",I,"at position:",p),this.onWordBoundary(I,p,v)},B=setTimeout(()=>{if(W||K||Y!==this.speakRunId)return;O(!1,P("timedOut")),speechSynthesis.cancel()},L6);try{speechSynthesis.speak(Z)}catch($){O(!1,$ instanceof Error?$:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPlaying&&!this._isPaused)speechSynthesis.pause()}resume(){if(this._isPlaying&&this._isPaused)speechSynthesis.resume()}stop(){let Q=this.utterance,G=this._isPlaying||Q!==null;if(this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),G)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(Q){if(!this.config)this.config={};if(Q.rate!==void 0)this.config.rate=Q.rate;if(Q.pitch!==void 0)this.config.pitch=Q.pitch;if(Q.voice!==void 0)this.config.voice=Q.voice;if(Q.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Q.providerOptions||{}}}onWordBoundary}var T=(Q)=>Q.trim().replace(/\s+/g," "),W1=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,J8=(Q)=>{if(Q.hidden)return!0;if(Q.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Q.getAttribute("aria-hidden")==="true")return!0;if(Q.hasAttribute("inert"))return!0;let G=Q.classList;if(G?.contains("sr-only")||G?.contains("pie-sr-only")||G?.contains("visually-hidden"))return!0;if(typeof window<"u"){let Y=window.getComputedStyle(Q);if(Y.display==="none"||Y.visibility==="hidden")return!0;let J=Number.parseFloat(Y.width||"0"),X=Number.parseFloat(Y.height||"0"),j=Number.isFinite(J)&&Number.isFinite(X)&&J<=1&&X<=1,Z=Y.clipPath.includes("inset(50%")||Y.clipPath.includes("inset(100%")||Y.clip.includes("rect(0px, 0px, 0px, 0px)")||Y.clip.includes("rect(0 0 0 0)");if((Y.position==="absolute"||Y.position==="fixed")&&j&&(Y.overflow==="hidden"||Z))return!0;if(Y.opacity==="0"&&j)return!0}return!1},U1=(Q,G)=>{let Y=Q.nodeType===1?Q:Q.parentElement;while(Y){if(J8(Y))return!0;if(G&&Y===G)break;Y=Y.parentElement}return!1};var C6=new Set(["computer-read-aloud","all"]),E6=new Set([...C6,"screen-reader"]),b6=new Set,S5=(Q)=>{let G=Q.getAttribute?.("data-tts-suppress");if(G===null||G===void 0)return!1;let Y=G.trim().toLowerCase();if(C6.has(Y))return!0;if(E6.has(Y))return!1;if(!b6.has(Y))b6.add(Y),console.warn(`[tts] data-tts-suppress="${G}" is not one of ${Array.from(E6).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},B1=(Q,G)=>{let Y=Q.nodeType===1?Q:Q.parentElement;while(Y){if(S5(Y))return!0;if(G&&Y===G)break;Y=Y.parentElement}return!1},V7=(Q,G)=>U1(Q,G)||B1(Q),X8=(Q,G)=>{if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u"||typeof Q.intersectsNode!=="function")return{text:Q.toString(),filtered:!1};let Y=[],J=!1,X=document.createTreeWalker(G,NodeFilter.SHOW_TEXT),j=X.nextNode();while(j){let Z=j;if(Q.intersectsNode(Z))if(V7(Z,G))J=!0;else{let K=Z.textContent||"",W=Z===Q.startContainer?Q.startOffset:0,B=Z===Q.endContainer?Q.endOffset:K.length;Y.push(K.slice(W,B))}j=X.nextNode()}return{text:Y.join(""),filtered:J}},Z8=(Q,G,Y)=>{if(!Q||!G)return!1;if(/\s/.test(Q)||/\s/.test(G))return!1;let J=Y?.boundarySpacingMode??"segmenterPreferred";if(J==="none")return!1;if(J==="segmenterPreferred")try{let Z=globalThis.Intl?.Segmenter;if(typeof Z==="function"){let K=new Z(Y?.locale,{granularity:"word"});if(Array.from(K.segment(`${Q}${G}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Q),j=/[A-Za-z0-9]/.test(G);return X&&j},C7=(Q,G)=>{let Y=new Map;if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u")return{text:"",map:Y};let J=[],X=0,j=!0,Z=!1,K=null,W=null,B=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),U=B.nextNode();while(U){let H=U;if(H.parentElement&&!V7(H,Q)){let O=H.textContent||"",P=O.match(/\S/),$=P?P[0]:null;if(!j&&!Z&&Z8(W,$,G)){if(J.push(" "),K)Y.set(X,K);X++,Z=!0}for(let F=0;F<O.length;F++){let L=O[F],C=/\s/.test(L);if(j){if(!C)j=!1,J.push(L),Y.set(X,{node:H,offset:F}),K={node:H,offset:F},X++,Z=!1,W=L}else if(C){if(!Z)J.push(" "),Y.set(X,{node:H,offset:F}),K={node:H,offset:F},X++;Z=!0}else J.push(L),Y.set(X,{node:H,offset:F}),K={node:H,offset:F},X++,Z=!1,W=L}}U=B.nextNode()}let V=J.join("").trimEnd();while(Y.has(V.length))Y.delete(V.length);return{text:V,map:Y}};var y5=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),T6=new Set(["audio","phoneme"]),y6=(Q)=>Q.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/ /g," ").replace(/&/g,"&"),D1=(Q,G,Y)=>{for(let J=0;J<G.length;J++)Q.push({char:G[J],rawOffset:Y===null?null:Y+J})},x5=(Q,G,Y)=>{let J=G.slice(Y).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!J)return 0;return D1(Q,y6(J[0]),Y),J[0].length},S6=(Q)=>{Q.push({char:" ",rawOffset:null})},f5=(Q)=>{let G=new Map,Y=[],J=!0;for(let X of Q){if(/\s/.test(X.char)){if(!J&&Y.length>0){if(Y.push(" "),X.rawOffset!==null)G.set(X.rawOffset,Y.length-1)}J=!0;continue}if(Y.push(X.char),X.rawOffset!==null)G.set(X.rawOffset,Y.length-1);J=!1}while(Y.length>0&&Y[Y.length-1]===" ")Y.pop();for(let[X,j]of G)if(j>=Y.length)G.delete(X);return{text:Y.join(""),rawToSpokenOffsetMap:G}},k5=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},I5=(Q,G)=>{let Y=new RegExp(`${G}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),J=Q.match(Y);return y6(J?.[2]??J?.[3]??"")||null},_1=(Q)=>{let G=[],Y=!1,J=!1,X=0;while(X<Q.length){let Z=Q[X];if(Z!=="<"){if(Z==="&"){let H=x5(G,Q,X);if(H>0){X+=H;continue}}D1(G,Z,X),X++;continue}let K=Q.indexOf(">",X+1);if(K<0){D1(G,Z,X),X++;continue}J=!0;let W=Q.slice(X,K+1),B=k5(W),U=/^<\s*\//.test(W),V=/\/\s*>$/.test(W);if(!U&&B==="sub"){let H=I5(W,"alias");if(!H){Y=!0,X=K+1;continue}D1(G,H,null);let N=Q.toLowerCase().indexOf("</sub>",K+1);X=N>=0?N+6:K+1;continue}if(!U&&B==="break"){S6(G),X=K+1;continue}if(!U&&T6.has(B)){if(Y=!0,V){X=K+1;continue}}if(B&&!y5.has(B)&&!T6.has(B)&&B!=="break"&&B!=="sub")Y=!0;if(!U&&(B==="p"||B==="s"))S6(G);X=K+1}let j=f5(G);return{spokenText:T(j.text),rawToSpokenOffsetMap:j.rawToSpokenOffsetMap,unsupportedSemantic:Y,hasMarkup:J}};var v5=W1(),v6=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),h5=[{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}],j8=(Q)=>{let G=[];for(let Y of Q.matchAll(v5)){let J=Y[0],X=Y.index??0;G.push({text:J,normalized:J.toLowerCase(),start:X,end:X+J.length})}return G},K8=(Q)=>v6.get(Q.normalized)||Q.normalized,m5=(Q,G)=>{let Y=[];for(let J=0;J<Q.length;J++){for(let X=0;X<G.length;X++){let j=K8(Q[J]),Z=K8(G[X]);if(j===Z)Y.push({spokenStartToken:J,spokenEndToken:J+1,visibleToken:X,score:10})}for(let X of h5){let j=Q.slice(J,J+X.phrase.length);if(j.length!==X.phrase.length)continue;if(!j.every((Z,K)=>Z.normalized===X.phrase[K]))continue;for(let Z=0;Z<G.length;Z++){if(G[Z].normalized!==X.visible)continue;Y.push({spokenStartToken:J,spokenEndToken:J+X.phrase.length,visibleToken:Z,score:X.score})}}}return Y},u5=(Q,G)=>{let Y=m5(Q,G).sort((W,B)=>Q[W.spokenStartToken].start-Q[B.spokenStartToken].start||G[W.visibleToken].start-G[B.visibleToken].start),J=Array(Y.length).fill(0),X=Array(Y.length).fill(-1);for(let W=0;W<Y.length;W++){let B=Y[W];J[W]=B.score;for(let U=0;U<W;U++){let V=Y[U];if(V.spokenEndToken<=B.spokenStartToken&&V.visibleToken<B.visibleToken){let H=B.spokenStartToken-V.spokenEndToken,N=B.visibleToken-V.visibleToken-1,O=Math.max(0,Math.abs(H-N)-2),P=J[U]+B.score-O;if(P>J[W])J[W]=P,X[W]=U}}}let j=-1;for(let W=0;W<J.length;W++)if(j<0||J[W]>J[j])j=W;if(j<0)return[];let Z=[],K=j;while(K>=0)Z.unshift(Y[K]),K=X[K];return Z.map((W)=>{let B=Q[W.spokenStartToken],U=Q[W.spokenEndToken-1],V=G[W.visibleToken];return{spokenStart:B.start,spokenEnd:U.end,visibleStart:V.start,visibleEnd:V.end,score:W.score}})},p5=(Q,G,Y)=>{if(Q.length===0)return 0;let J=Q.length/Math.max(1,Math.min(G.length,Y.length)),X=Q.reduce((j,Z)=>j+Z.score,0)/Q.length/10;return Math.min(1,J*X)},V1=(Q)=>{let G=_1(Q.speechText),Y=T(Q.visibleText),J=G.spokenText,X=j8(J),j=j8(Y),Z=G.unsupportedSemantic?[]:u5(X,j),K=p5(Z,X,j),W=J===Y&&J.length>0,B=Z.length===1&&Z[0].score===10&&X.length<=2&&j.length<=2,U=G.unsupportedSemantic?"region-fallback":W?"exact-word":Z.length>=2||B?K>=0.12?"anchor-span":"region-fallback":"region-fallback",V=G.unsupportedSemantic?"unsupported":G.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:J,visibleText:Y,playbackMode:U,boundaryOffsetMode:V,anchors:Z,confidence:K,spokenTokens:X,visibleTokens:j,rawToSpokenOffsetMap:G.rawToSpokenOffsetMap}},q8=(Q,G)=>Q.find((Y)=>Y.start<=G&&G<Y.end)||null,h6=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let G=j8(Q)[0];if(!G)return null;return v6.get(G.normalized)||G.normalized},x6=(Q,G,Y)=>{let J=h6(Y);if(!G||!J)return!1;let X=q8(Q.spokenTokens,G.start);if(!X)return!1;return K8(X)===J},f6=(Q,G)=>{let Y=Q.rawToSpokenOffsetMap.get(G);if(Y!==void 0)return Y;for(let J=G;J<Q.speechText.length;J++){let X=Q.rawToSpokenOffsetMap.get(J);if(X!==void 0)return X;if(Q.speechText[J]===">")break}return null},k6=(Q,G,Y)=>{let J=f6(Q,G);if(J===null)return null;let X=f6(Q,Math.max(G,G+Y-1)),j=q8(Q.spokenTokens,J),Z=X!==null&&X>=J?X-J+1:j?j.end-J:Y;return{start:J,length:Math.max(1,Z)}},I6=(Q,G,Y)=>{if(G<0||G>=Q.spokenText.length)return null;let J=q8(Q.spokenTokens,G);if(!J)return null;return{start:G,length:Math.min(Y,J.end-G)}},m6=(Q,G,Y=1,J)=>{if(Q.boundaryOffsetMode==="unsupported"||!Number.isFinite(G))return null;let X=Math.max(1,Number.isFinite(Y)?Y:1);if(J&&/^<[^>]+>$/.test(J.trim()))return null;if(Q.boundaryOffsetMode==="raw-ssml"){let j=k6(Q,G,X),Z=I6(Q,G,X);if(J){if(x6(Q,j,J))return j;if(x6(Q,Z,J))return Z;if(h6(J))return null}return j||Z}return I6(Q,G,X)||k6(Q,G,X)},u6=(Q,G)=>{if(Q.playbackMode==="region-fallback")return null;let Y=Q.anchors.find((j)=>j.spokenStart<=G&&G<j.spokenEnd);if(Y)return{start:Y.visibleStart,end:Y.visibleEnd};let J=null,X=null;for(let j of Q.anchors){if(j.spokenEnd<=G){J=j;continue}if(j.spokenStart>G){X=j;break}}if(J&&X)return{start:Math.min(J.visibleStart,X.visibleStart),end:Math.max(J.visibleEnd,X.visibleEnd)};return null};var g5=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"]]]),c5=new Map([["","function-application"],["","implicit-multiply"],["","invisible-separator"],["","invisible-plus"]]),p6=new Map([["2",["squared"]],["3",["cubed"]]]),l5=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),d5=(Q)=>Q.replace(/\s+/g," ").trim(),H7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),i5=(Q)=>Q.nodeType===Node.ELEMENT_NODE,T7=(Q)=>Array.from(Q.childNodes).filter(i5),W8=(Q)=>d5(Q.textContent||""),Q7=(Q,G)=>({type:"element-range",quality:G,element:Q}),s5=(Q)=>{switch(Q){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"}},n5=(Q,G)=>{if(G==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},r5=(Q,G,Y)=>{if(Y==="fraction")return["over","divided by"];if(Y==="superscript")return p6.get(Q)??[];if(Q==="|")return["absolute value"];if(G==="operator")return g5.get(Q)||[];return[]},F7=(Q)=>{let G=Q.normalized??n5(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:G,spokenAliases:r5(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||Q7(Q.sourceElement,"element-range"),optional:Q.optional}},A7=(Q,G,Y="tokens")=>{Q[Y].push(G)},g6=(Q,G,Y)=>{T7(Q).forEach((J,X)=>G7(J,G,`${Y}/${H7(J)}[${X}]`))},o5=(Q,G,Y)=>{let J=T7(Q);if(J[0])G7(J[0],G,`${Y}/numerator`);if(A7(G,F7({state:G,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:Y,target:Q7(Q,"element-range")})),J[1])G7(J[1],G,`${Y}/denominator`)},a5=(Q,G,Y)=>{let J=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";A7(G,F7({state:G,kind:"operator",role:J==="|"?"absolute-value-fence":"open-fence",text:J,sourceElement:Q,path:`${Y}/open`,target:Q7(Q,"element-range")})),g6(Q,G,Y),A7(G,F7({state:G,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${Y}/close`,target:Q7(Q,"element-range")}))},t5=(Q,G,Y)=>{let J=T7(Q);if(J[0])G7(J[0],G,`${Y}/base`);let X=J[1];if(!X)return;let j=W8(X);if(p6.has(j)){A7(G,F7({state:G,kind:"structure",role:"superscript",text:j,normalized:j,sourceElement:X,path:`${Y}/exponent`,target:Q7(Q,"element-range")}));return}G7(X,G,`${Y}/exponent`)},e5=(Q,G,Y,J)=>{A7(G,F7({state:G,kind:"structure",role:J,text:W8(Q)||J,normalized:`\x00${J}`,sourceElement:Q,path:Y,target:Q7(Q,"element-range")}))},QQ=(Q,G,Y)=>{let J=0;for(let X of T7(Q)){if(H7(X)==="mtr"||H7(X)==="mlabeledtr")J++,A7(G,F7({state:G,kind:"layout",role:"table-row",text:`row-${J}`,normalized:`row-${J}`,sourceElement:X,path:`${Y}/row[${J}]`,target:Q7(X,"region-fallback")}),"layoutTargets");G7(X,G,`${Y}/${H7(X)}[${J}]`)}},GQ=(Q,G,Y)=>{let J=W8(Q);if(!J)return;let X=s5(H7(Q)),j=X==="operator"?c5.get(J):void 0,Z=j??(X==="operator"&&(J==="("||J===")")?"grouping-fence":X);A7(G,F7({state:G,kind:X,role:Z,text:J,sourceElement:Q,path:Y,target:j&&Q.parentElement?Q7(Q.parentElement,"region-fallback"):void 0,optional:Boolean(j)||Z==="grouping-fence"}))},G7=(Q,G,Y)=>{let J=H7(Q);switch(J){case"annotation":case"annotation-xml":return;case"semantics":{let X=T7(Q).find((j)=>{let Z=H7(j);return Z!=="annotation"&&Z!=="annotation-xml"});if(X)G7(X,G,`${Y}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":GQ(Q,G,Y);return;case"mfrac":o5(Q,G,Y);return;case"msup":t5(Q,G,Y);return;case"mfenced":a5(Q,G,Y);return;case"mtable":QQ(Q,G,Y);return;case"mphantom":return;case"maction":{let X=T7(Q)[0];if(X)G7(X,G,`${Y}/action`);return}default:{let X=l5.get(J);if(X){e5(Q,G,Y,X);return}g6(Q,G,Y)}}},c6=(Q)=>{let G={tokens:[],layoutTargets:[],nextId:0};return G7(Q,G,"/math"),{tokens:G.tokens,layoutTargets:G.layoutTargets,expressionTarget:Q7(Q,"region-fallback")}};var l6=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((Y)=>Y.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var YQ=(Q)=>{let G=[],Y=new Set,J=(X)=>{let j=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(j.length===0)return;let Z=j.join(" ");if(Y.has(Z))return;Y.add(Z),G.push(j)};J(Q.normalized);for(let X of Q.spokenAliases)J(X);return G},d6=(Q,G,Y)=>{let J=0;for(let X of Y){if(X.length<=J)continue;let j=!0;for(let Z=0;Z<X.length;Z++){let K=Q[G+Z];if(!K||K.normalized.toLowerCase()!==X[Z]){j=!1;break}}if(j)J=X.length}return J},JQ=(Q,G)=>{let Y=[],J=0;for(let X of G){let j=YQ(X);if(X.optional){let Z=d6(Q,J,j);if(Z>0)Y.push({speechTokens:Q.slice(J,J+Z),math:X}),J+=Z;continue}while(J<Q.length){let Z=d6(Q,J,j);if(Z>0){Y.push({speechTokens:Q.slice(J,J+Z),math:X}),J+=Z;break}J++}}return Y},XQ=(Q,G,Y)=>{let J=Y.filter((Z)=>!Z.optional).length,X=Q.filter((Z)=>!Z.math.optional).length,j=Q.reduce((Z,K)=>Z+K.speechTokens.length,0);return J>0&&X===J&&j===G.length},ZQ=(Q)=>Q.map(({speechTokens:G,math:Y})=>({speechTokenIds:G.map((J)=>J.id),mathTokenIds:[Y.id],score:1,confidence:1,target:Y.target})),i6=(Q)=>{let G=Q.minExactWordConfidence??0.95,Y=JQ(Q.speech.tokens,Q.math.tokens),J=XQ(Y,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:J>=G?ZQ(Y):[],confidence:J,fallbackTarget:Q.math.expressionTarget}};var s6=W1(),jQ=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),n6=(Q)=>{let G=Q.toLowerCase();return jQ.get(G)||G},KQ=(Q)=>{let G=[];for(let Y of Q.matchAll(s6)){let J=Y[0],X=Y.index??0;G.push({id:`speech-token-${G.length}`,text:J,normalized:n6(J),start:X,end:X+J.length,sourceStart:X,sourceEnd:X+J.length,coordinateSystem:"normalized-speech"})}return G},N7=(Q)=>{let G=_1(Q.speechText);return{speechText:Q.speechText,spokenText:G.spokenText,tokens:KQ(G.spokenText),rawToSpokenOffsetMap:G.rawToSpokenOffsetMap,boundaryOffsetSpace:G.unsupportedSemantic?"unsupported":G.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:G.unsupportedSemantic,hasMarkup:G.hasMarkup}},D8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let G=Q.match(s6);if(!G?.[0])return null;return n6(G[0])},qQ=(Q,G)=>Q.find((Y)=>Y.start<=G&&G<Y.end)||null,WQ=(Q,G)=>{let Y=Q.rawToSpokenOffsetMap.get(G);if(Y!==void 0)return Y;for(let J=G;J<Q.speechText.length;J++){let X=Q.rawToSpokenOffsetMap.get(J);if(X!==void 0)return X;if(Q.speechText[J]===">")break}return null},U8=(Q,G,Y)=>{if(G===null)return null;let J=qQ(Q.tokens,G);if(!J)return null;return{token:J,start:G,length:Math.max(1,Math.min(Y,J.end-G)),confidence:0.75}},B8=(Q,G)=>{let Y=D8(G);return Boolean(Q&&Y&&Q.token.normalized===Y)},_8=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let G=Math.max(1,Number.isFinite(Q.length)?Q.length:1),Y=U8(Q.tokenization,WQ(Q.tokenization,Q.position),G),J=U8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,G);if(B8(Y,Q.boundaryWord))return{...Y,confidence:1};if(B8(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&D8(Q.boundaryWord))return null;return Q.tokenization.boundaryOffsetSpace==="raw-ssml"?Y||J:J||Y},r6=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let G=Math.max(1,Number.isFinite(Q.length)?Q.length:1),Y=U8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,G);if(B8(Y,Q.boundaryWord))return{...Y,confidence:1};if(Q.boundaryWord&&D8(Q.boundaryWord))return null;return Y};var S7=(Q)=>{let G=N7({speechText:Q.speechText}),Y=c6(Q.mathElement);return{speech:G,math:Y,result:i6({speech:G,math:Y})}};var o6=(Q,G)=>{let Y=r6({tokenization:Q.speech,position:G.position,length:G.length,boundaryWord:G.boundaryWord});return l6({alignment:Q.result,boundary:Y})},a6=(Q,G)=>{if(!G.boundaryWord||/^<[^>]+>$/.test(G.boundaryWord.trim()))return null;let Y=N7({speechText:G.boundaryWord}).tokens[0];if(!Y)return null;let J=Q.math.tokens.filter((X)=>{let j=Y.normalized.toLowerCase();return X.normalized.toLowerCase()===j||X.spokenAliases.some((Z)=>Z.toLowerCase()===j)});return J.length===1?J[0].target:null};var UQ=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"]),BQ=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"]),t6=(Q)=>Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),DQ=(Q)=>t6(Q).replace(/"/g,"""),_Q=(Q,G)=>{let Y=Q.toLowerCase(),J=G.trim().toLowerCase();if(Y.startsWith("on"))return!0;if(!BQ.has(Y))return!0;if(J.includes("javascript:"))return!0;if(J.includes("data:text/html"))return!0;return!1},VQ=(Q)=>{let G=Q.localName.toLowerCase();if(!UQ.has(G))return!1;let Y=Q.namespaceURI;return!Y||Y==="http://www.w3.org/1998/Math/MathML"||Y==="http://www.w3.org/1999/xhtml"},e6=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return t6(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let G=Q;if(!VQ(G))return null;let Y=G.localName.toLowerCase(),J=[];for(let Z of Array.from(G.attributes)){let K=Z.name.toLowerCase();if(_Q(K,Z.value))continue;if(K==="xmlns"&&Z.value!=="http://www.w3.org/1998/Math/MathML")return null;J.push(`${K}="${DQ(Z.value)}"`)}if(Y==="math"&&!J.some((Z)=>Z.startsWith("xmlns=")))J.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let Z of Array.from(G.childNodes)){let K=e6(Z);if(K===null)return null;X.push(K)}let j=J.length>0?` ${J.join(" ")}`:"";return`<${Y}${j}>${X.join("")}</${Y}>`},HQ=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},H1=(Q)=>{let G=String(Q||"").trim();if(!G)return null;let Y=HQ(G);if(!Y)return null;if(Y.getElementsByTagName("parsererror").length>0)return null;let J=Y.documentElement;if(!J||J.localName.toLowerCase()!=="math")return null;return e6(J)};var Q0=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),G0=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",Y0=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",J0=(Q)=>{let G=Q.tagName?.toLowerCase();return G==="annotation"||G==="annotation-xml"},FQ=(Q)=>{let G=Q.getAttribute("data-mathml");return G&&G.trim()?G:null},AQ=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},NQ=(Q)=>{if(Q.tagName.toLowerCase()==="math")return H1(Q.outerHTML);let G=FQ(Q);if(G){let Y=H1(G);if(Y)return Y}if(G0(Q)){let Y=AQ(Q);if(Y){let J=H1(Y);if(J)return J}}return null};var MQ=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),OQ=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),zQ=(Q,G)=>{let Y=Q.parentElement,J=null;while(Y&&Y!==G){let X=(Y.getAttribute("role")||"").toLowerCase(),j=Y.tagName.toUpperCase();if(MQ.has(j)||OQ.has(X)){J=Y;break}Y=Y.parentElement}return J||G},PQ=(Q)=>Boolean(typeof Q.querySelector==="function"&&Q.querySelector("math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Q.tagName?.toLowerCase()==="math"||Q.hasAttribute?.("data-mathml")||G0(Q),M7=(Q,G,Y)=>{if(/[.,;:!?]/.test(G)&&Q.chars.length>0&&Q.chars[Q.chars.length-1]===" ")Q.chars.pop(),Q.position--,Q.map.delete(Q.position);if(Q.chars.push(G),Y)Q.map.set(Q.position,Y),Q.lastMapped=Y;else if(Q.lastMapped)Q.map.set(Q.position,Q.lastMapped);Q.position++},X0=(Q,G)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let Y=Q.chars[Q.chars.length-1];return Z8(Y,G,Q.options)},Z0=(Q,G)=>{let Y=G.textContent||"",J=!1;for(let X=0;X<Y.length;X++){let j=Y[X],Z=/\s/.test(j);if(Q.inLeadingWhitespace){if(!Z)Q.inLeadingWhitespace=!1,M7(Q,j,{node:G,offset:X}),J=!0,Q.lastCharWasWhitespace=!1;continue}if(Z){if(!Q.lastCharWasWhitespace)M7(Q," ",{node:G,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!J&&X0(Q,j))M7(Q," ",{node:G,offset:X});M7(Q,j,{node:G,offset:X}),J=!0,Q.lastCharWasWhitespace=!1}},LQ=(Q,G)=>{for(let Y=0;Y<G.text.length;Y++){let J=G.text[Y],X=/\s/.test(J),j=G.map.get(Y)||null,Z=j?.node||Q.lastMapped?.node||null,K=j?.offset??Q.lastMapped?.offset??0,W=j?{node:j.node,offset:j.offset}:Z?{node:Z,offset:K}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)M7(Q," ",W);Q.lastCharWasWhitespace=!0;continue}if(Y===0&&X0(Q,J))M7(Q," ",W);if(M7(Q,J,W),Q.lastCharWasWhitespace=!1,j)Q.map.set(Q.position-1,{node:j.node,offset:j.offset}),Q.lastMapped={node:j.node,offset:j.offset};else if(Z)Q.map.set(Q.position-1,{node:Z,offset:K})}},$Q=(Q)=>{if(typeof DOMParser>"u")return"";let G=new DOMParser().parseFromString(Q,"application/xml");if(G.getElementsByTagName("parsererror").length>0)return"";let Y=[],J=(X)=>{if(X.nodeType===3){let Z=X.textContent||"";if(Z.trim())Y.push(Z);return}if(X.nodeType!==1)return;let j=X;if(J0(j))return;for(let Z of Array.from(j.childNodes))J(Z)};return J(G.documentElement),T(Y.join(" "))},wQ=(Q,G,Y)=>{let J=Q0(Y),X=(K)=>{if(V7(K,Q))return;if(K.nodeType===3){Z0(J,K);return}if(K.nodeType!==1)return;let W=K;if(Y0(W)||J0(W))return;for(let B of Array.from(W.childNodes))X(B)};X(Q),j0(J);let j=T(J.chars.join(""));if(j)return{text:j,map:J.map};let Z=$Q(G);if(!Z)return C7(Q,Y);return{text:Z,map:new Map}},j0=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},RQ=(Q,G)=>{let Y=Q0(G),J=[],X=0,j,Z=!1,K=()=>{let U=T(Y.chars.slice(X,Y.chars.length).join(""));if(U)J.push({type:"text",text:U,sourceElement:j});X=Y.chars.length,j=void 0},W=(U)=>{if(V7(U,Q))return;if(U.nodeType===Node.TEXT_NODE){let N=zQ(U,Q);if(j&&N!==j)K();j=N,Z0(Y,U);return}if(U.nodeType!==Node.ELEMENT_NODE)return;let V=U;if(Y0(V))return;let H=NQ(V);if(H){K();let N=wQ(V,H,G);LQ(Y,N);let O=T(N.text);J.push({type:"math",mathml:H,fallbackText:O,sourceElement:V}),X=Y.chars.length,Z=!0;return}for(let N of Array.from(V.childNodes))W(N)};for(let U of Array.from(Q.childNodes))W(U);j0(Y),K();let B=Y.chars.join("");while(Y.map.has(B.length))Y.map.delete(B.length);return{visibleText:B,map:Y.map,chunks:J,containsMathMarkup:Z}},O7=(Q,G)=>{if(!PQ(Q)){let{text:Y,map:J}=C7(Q,G);return{visibleText:Y,map:J,chunks:Y?[{type:"text",text:Y}]:[],containsMathMarkup:!1}}return RQ(Q,G)};var V8=null,K0=Promise.resolve(),bQ=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",CQ=async()=>{if(!V8)V8=import("speech-rule-engine").then((Q)=>{let G=Q.default||Q;if(!G||typeof G.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return G});return V8},TQ=(Q)=>Q==="en"?"clearspeak":"mathspeak",q0=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),W0=(Q)=>typeof Q==="string"&&Q.trim()?Q.trim():void 0,z7=(Q)=>{if(!q0(Q))return;let G=W0(Q.domain),Y=W0(Q.style),J=q0(Q.engineOptions)?Q.engineOptions:void 0;if(!G&&!Y&&!J)return;return{...G?{domain:G}:{},...Y?{style:Y}:{},...J?{engineOptions:J}:{}}},SQ=async(Q,G,Y,J)=>{let X=bQ(G),j=z7(J);await Q.setupEngine?.({...j?.engineOptions||{},locale:X,domain:j?.domain||TQ(X),...j?.style?{style:j.style}:{},modality:"speech",markup:Y}),await Q.engineReady?.()},yQ=async(Q)=>{let G=K0.then(Q,Q);return K0=G.then(()=>{return},()=>{return}),G},U0=async(Q,G,Y,J,X)=>yQ(async()=>{return await SQ(Q,Y,J,X),Q.toSpeech(G)}),xQ=(Q)=>Q.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),fQ=async(Q,G,Y,J)=>{try{let X=xQ(await U0(Q,G,Y,"ssml",J));return X.includes("<speak")?X:null}catch(X){return console.debug("[TTSService] Math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},F1=async(Q,G={})=>{if(!Q.some((B)=>B.type==="math"))return{speechText:T(Q.map((B)=>B.type==="text"?B.text:B.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let Y=null,J=!1,X=!1,j=G.loadSre||CQ,Z=[];for(let B of Q){if(B.type==="text"){Z.push(B.text);continue}try{if(!Y)Y=await j();let U=T(await U0(Y,B.mathml,G.language,"none",G.mathSpeech));if(U){Z.push(U),J=!0;continue}X=!0,Z.push(B.fallbackText)}catch(U){X=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),Z.push(B.fallbackText)}}let K=T(Z.join(" ")),W;if(G.produceSsml&&Y&&J&&Q.length===1&&Q[0].type==="math")W=await fQ(Y,Q[0].mathml,G.language,G.mathSpeech)??void 0;return{speechText:K,usedMathSpeech:J,usedFallback:X,ssml:W}};var kQ=(Q,G)=>F1([Q],G),IQ=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",vQ=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),hQ=new Set(["heading","listitem","option","radio"]),mQ=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let G=Q.sourceElement.tagName.toUpperCase(),Y=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return vQ.has(G)||hQ.has(Y)},H8=async(Q)=>{let G=Q.resolveMathSpeech??kQ,{visibleText:Y}=Q,J=[],X=0,j=(K)=>{let W=T(K),B=Y.indexOf(W,X),U=B>=0?B:X,V=U+W.length;return X=V,{start:U,end:V}},Z=[];for(let K=0;K<Q.chunks.length;K++){let W=Q.chunks[K];if(W.type==="text"){let N=mQ(W)?[{text:W.text,offset:0}]:E7(W.text,{locale:Q.language});for(let O of N){let P=T(O.text);if(!P)continue;let $=j(P);J.push({sourceChunkIndex:K,segment:{kind:"prose",spokenText:P,visibleText:P,visibleSpan:$}}),Z.push(P)}continue}let B=j(W.fallbackText),U=await G(W,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),V=!U.speechText,H=U.speechText||W.fallbackText;J.push({sourceChunkIndex:K,segment:{kind:"math",spokenText:H,mathml:W.mathml,fallbackText:W.fallbackText,visibleSpan:B,usedFallback:V,ssml:U.ssml}}),Z.push(H)}return{segments:J,locale:IQ(Q.language),visibleText:Y,plainSpeechText:T(Z.join(" "))}};var uQ=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",pQ="sre-v1",gQ=256,F8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(F8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([G],[Y])=>G.localeCompare(Y)).map(([G,Y])=>`${JSON.stringify(G)}:${F8(Y)}`).join(",")}}`;if(Q===null)return"null:null";if(typeof Q>"u")return"undefined:";if(typeof Q==="function")return`function:${Q.name||"anonymous"}`;if(typeof Q==="symbol")return`symbol:${String(Q)}`;if(typeof Q==="bigint")return`bigint:${Q.toString()}`;if(typeof Q==="number")return Number.isFinite(Q)?`number:${Q}`:`number:${String(Q)}`;return`${typeof Q}:${JSON.stringify(Q)}`},B0=(Q,G,Y,J)=>`${pQ}\x00${uQ(Q)}\x00${G?"ssml":"plain"}\x00${F8(Y??null)}\x00${J}`,A8=(Q={})=>{let G=Math.max(1,Q.maxEntries??gQ),Y=Q.resolve??((j,Z)=>F1([j],Z)),J=new Map,X=(j,Z)=>{J.delete(j),J.set(j,Z);while(J.size>G){let K=J.keys().next().value;if(K!==void 0)J.delete(K)}};return async(j,Z)=>{let K=z7(Z.mathSpeech),W=Z.produceSsml===!0,B=B0(Z.language,W,K,j.mathml),U=J.get(B);if(U)return J.delete(B),J.set(B,U),U;let V=await Y(j,{...Z,mathSpeech:K});if(W&&V.ssml&&G>1)X(B0(Z.language,!1,K,j.mathml),{speechText:V.speechText,usedMathSpeech:V.usedMathSpeech,usedFallback:V.usedFallback});return X(B,V),V}};var cQ=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return N7({speechText:Q}).tokens[0]?.normalized||null},lQ=(Q,G)=>{let Y=N7({speechText:Q.speechText});if(!Number.isFinite(G.position))return{boundary:null,spokenText:Y.spokenText};let J=_8({tokenization:Y,position:G.position,length:G.length,boundaryWord:G.word});return{boundary:J?{start:J.start,length:J.length}:null,spokenText:Y.spokenText}},dQ=(Q,G,Y)=>{if(!Y)return!0;return N7({speechText:Q}).tokens.find((X)=>X.start<=G&&G<X.end)?.normalized===Y},D0=(Q,G)=>{let Y=cQ(G.word);if(Q.id!==G.chunkId)return{chunkId:G.chunkId,normalizedWord:Y,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(G.providerOffsetSpace==="unknown"||Q.offsetSpace==="unsupported")return{chunkId:Q.id,normalizedWord:Y,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let J,X;if(Q.catalogAlignment)J=m6(Q.catalogAlignment,G.position,G.length,G.word),X=Q.catalogAlignment.spokenText;else{let j=lQ(Q,G);J=j.boundary,X=j.spokenText}if(!J)return{chunkId:Q.id,normalizedWord:Y,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};if(!dQ(X,J.start,Y))return{chunkId:Q.id,normalizedWord:Y,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to matching word"};return{chunkId:Q.id,normalizedWord:Y,chunkSpokenStart:J.start,chunkSpokenEnd:J.start+J.length,confidence:Y?1:0.75,reason:Q.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var P7=(Q)=>{if(Q.semanticTarget)return{activeTarget:Q.semanticTarget,regionTarget:Q.regionTarget,quality:Q.semanticTarget.quality==="exact-word"?"exact-word":Q.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Q.confidence,reason:Q.reason};if(Q.expressionTarget)return{activeTarget:Q.expressionTarget,regionTarget:Q.regionTarget,quality:"expression",confidence:Q.confidence,reason:Q.reason};return{activeTarget:null,regionTarget:Q.regionTarget,quality:"region",confidence:Q.confidence,reason:Q.reason}};var V0=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),N8="mi,mn,mo,mtext",H0="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",F0=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),A0=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},A1=(Q)=>{let G=Q;while(G){if(G.localName?.toLowerCase()==="mjx-container")return G;G=G.parentElement}return null},_0=(Q)=>{if(!Q)return!1;if(A1(Q))return!1;return!U1(Q)},N0=(Q)=>{let G=Q.getBoundingClientRect?.();return Boolean(G&&G.width>0&&G.height>0)},M8=(Q)=>{let G=Q;while(G){if(G.localName?.toLowerCase()==="math")return G;G=G.parentElement}return null},M0=(Q,G)=>{if(Q.length===0)return!1;if(Q.length!==G.length)return!1;for(let Y=0;Y<Q.length;Y+=1){let J=V0.get(Q[Y].localName.toLowerCase());if(!J)return!1;if(G[Y].localName.toLowerCase()!==J)return!1}return!0},iQ=(Q,G)=>{if(!Q)return null;if(!V0.has(Q.localName.toLowerCase()))return null;if(G.querySelector(F0))return null;let Y=M8(Q),J=G.querySelector("mjx-math");if(!Y||!J)return null;let X=Array.from(Y.querySelectorAll(N8)),j=X.indexOf(Q);if(j<0)return null;let Z=Array.from(J.querySelectorAll(H0));if(!M0(X,Z))return null;let K=Z[j];if(!K||!N0(K))return null;return K},O0=(Q)=>{let G=A1(Q);if(G){if(G.querySelector(F0))return"expression";let X=M8(Q)??Q,j=G.querySelector("mjx-math");if(!j)return"expression";let Z=Array.from(X.querySelectorAll(N8)),K=Array.from(j.querySelectorAll(H0));if(!M0(Z,K))return"expression";return K.some((W)=>N0(W))?"token":"expression"}let Y=M8(Q)??Q;return Array.from(Y.querySelectorAll(N8)).some((X)=>!U1(X))?"token":"expression"},O8=(Q)=>{let G=A0(Q),Y=A1(G);if(Y){let J=iQ(G,Y);if(J)return{type:"element",quality:"semantic-token",element:J};return{type:"element",quality:"expression",element:Y}}if(Q.type==="text-range"){if(!_0(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!_0(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},z0=O8,P0=()=>{let Q=new WeakMap;return(G)=>{let Y=A0(G),J=A1(Y);if(!Y||!J)return O8(G);if(Q.has(Y))return Q.get(Y)??null;let X=O8(G);return Q.set(Y,X),X}};var L0=(Q,G,Y,J=Q.mathAlignments,X=z0)=>{if(G.chunkSpokenStart===null||G.chunkSpokenEnd===null)return null;let j=null;for(let Z of J){let K=o6(Z.alignment,{position:G.chunkSpokenStart,length:Math.max(1,G.chunkSpokenEnd-G.chunkSpokenStart),boundaryWord:Y.word})||a6(Z.alignment,{boundaryWord:Y.word});if(!K)continue;let W=X(K);if(!W)continue;if(W.quality==="semantic-token")return W;j??=W}return j};var N1=(Q,G,Y)=>{if(!Q||typeof document>"u")return null;if(Y<=G)return null;let J=Q.get(G),X=Q.get(Math.max(G,Y-1));if(!J)return null;if(!X)X=J;try{let j=document.createRange();return j.setStart(J.node,J.offset),j.setEnd(X.node,X.offset+1),j}catch{return null}};var $0=(Q,G)=>{if(!Q.catalogAlignment||G.chunkSpokenStart===null)return null;let Y=u6(Q.catalogAlignment,G.chunkSpokenStart);if(!Y)return null;let J=N1(Q.visibleMap,Y.start,Y.end);if(!J)return null;return{type:"range",quality:Q.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:J}};var sQ=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,w0=(Q,G=Q.chunk.mathAlignments)=>{if(G.length!==1)return null;let Y=G[0]?.alignment.result.fallbackTarget;return Y?Q.renderedMathTargetResolver(Y):null},nQ=(Q,G)=>{if(!Q)return G.mathAlignments;return G.mathAlignments.filter(({element:Y})=>{try{if(Q.type==="range")return Q.range.intersectsNode(Y);if(Q.type==="element")return Q.element===Y||Q.element.contains(Y);return Q.node.parentElement?.contains(Y)||!1}catch{return!1}})},R0=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),E0=(Q)=>Q.length===1?Q[0].element:null,rQ=(Q,G)=>G.length>0&&G.every(({element:Y})=>Q.mathCapabilityByElement.get(Y)==="token"),oQ=3,aQ=(Q,G,Y)=>{if(!G||G.type!=="range")return!1;let{startContainer:J,endContainer:X}=G.range;if(J===X&&J.nodeType===oQ)return!1;return Y.some(({element:Z})=>Q.mathCapabilityByElement.get(Z)==="token"&&Z.contains(J)&&Z.contains(X))},tQ=(Q,G)=>({chunk:Q,regionTarget:sQ(Q),renderedMathTargetResolver:P0(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:Y})=>[Y,G?O0(Y):"expression"])),heldTokenByElement:new Map}),b0=(Q)=>{let G=Q.mathTokenHighlighting!==!1,Y=new Map(Q.chunks.map((J)=>[J.id,tQ(J,G)]));return{chunks:Q.chunks,resolveInitial(J){let X=Y.get(J);if(!X)return R0();let j=X.chunk.mathAlignments,Z=j.length===1?j[0].element:null,K=Z?X.mathCapabilityByElement.get(Z):null;if(K==="expression")return P7({semanticTarget:null,expressionTarget:w0(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return P7({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:K==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(J){let X=Y.get(J.chunkId);if(!X)return R0();let{chunk:j}=X,Z=D0(j,J),K=$0(j,Z),W=nQ(K,j),B=(!K||W.length>0?L0(j,Z,J,W,X.renderedMathTargetResolver):null)||null,U=G&&B&&B.quality!=="expression"?B:null,V=B&&B.quality==="expression"?B:null;if(U){let H=E0(W);if(H)X.heldTokenByElement.set(H,U);return P7({semanticTarget:U,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}if(K&&(G?!aQ(X,K,W):W.length===0))return P7({semanticTarget:K,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason});if(rQ(X,W)){let H=E0(W),N=H?X.heldTokenByElement.get(H)??null:null;return P7({semanticTarget:N,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:N?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return P7({semanticTarget:null,expressionTarget:V??w0(X,W),regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}}};var eQ=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let G=Q.mathAlignment?.speech.boundaryOffsetSpace;if(G)return G;return"plain-spoken-text"},Q9=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},C0=(Q)=>{return(Q.chunks&&Q.chunks.length?Q.chunks:[{speechText:Q.speechText||"",visibleText:Q.visibleText||Q.speechText||"",sourceElement:Q.sourceElement||Q.contentRoot,regionElement:Q.regionElement||Q.sourceElement||Q.contentRoot,regionRange:Q.regionRange,visibleMap:Q.visibleMap}]).map((Y,J)=>({id:`tts-chunk-${J}`,speechText:Y.speechText,visibleText:Y.visibleText,sourceElement:Y.sourceElement,contentRoot:Q.contentRoot,regionElement:Y.regionElement??Y.sourceElement,regionRange:Y.regionRange,visibleMap:Y.visibleMap,catalogAlignment:Y.alignment,mathAlignments:Q9(Y),offsetSpace:eQ(Y)}))};var G9=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),M1=(Q,G)=>{let Y=Q.closest(G9);if(Y&&G.contains(Y))return Y;return Q};var Y9=(Q,G,Y)=>{let J=new Map;for(let X=G;X<Y;X++){let j=Q.get(X);if(j)J.set(X-G,j)}return J},z8=async(Q)=>{let G=O7(Q.contentRoot,Q.textProcessingOptions),Y=await H8({chunks:G.chunks,visibleText:G.visibleText,language:Q.language,mathSpeech:Q.mathSpeech,produceSsml:Q.produceSsml,resolveMathSpeech:Q.resolveMathSpeech});return{plan:{items:Y.segments.map(({segment:X,sourceChunkIndex:j})=>{let Z=G.chunks[j];if(X.kind==="prose"){let W=Z?.type==="text"?Z.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:W,regionElement:M1(W,Q.contentRoot),visibleMap:Y9(G.map,X.visibleSpan.start,X.visibleSpan.end)}}}let K=Z?.type==="math"?Z.sourceElement??null:null;return{segment:X,anchor:{sourceElement:K,regionElement:K}}}),locale:Y.locale,visibleText:Y.visibleText,plainSpeechText:Y.plainSpeechText},containsMathMarkup:G.containsMathMarkup,visibleText:G.visibleText}};var J9=(Q,G)=>{let Y=V1({speechText:Q.spokenText,visibleText:Q.spokenText});return{speechText:Q.spokenText,visibleText:Q.visibleText,sourceElement:G.sourceElement,regionElement:G.regionElement,regionRange:N1(G.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:Y.playbackMode,alignment:Y,visibleMap:G.visibleMap}},T0=(Q,G)=>{let Y=G.sourceElement;return{speechText:Q.spokenText,visibleText:Q.fallbackText,sourceElement:Y,regionElement:G.regionElement,speechMatchesVisibleText:Q.spokenText===Q.fallbackText,mathAlignment:Y?S7({mathElement:Y,speechText:Q.spokenText}):void 0}},X9=(Q,G,Y)=>{let J=G.sourceElement;return{speechText:Y,visibleText:Q.fallbackText,sourceElement:J,regionElement:G.regionElement,speechMatchesVisibleText:!1,mathAlignment:J?S7({mathElement:J,speechText:Y}):void 0,plainFallback:T0(Q,G)}},P8=(Q,G={})=>Q.items.map(({segment:Y,anchor:J})=>{if(Y.kind==="prose")return J9(Y,J);if(G.format==="ssml"&&Y.ssml)return X9(Y,J,Y.ssml);return T0(Y,J)});var S0="pie-tts-control-handoff";var R;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})(R||(R={}));var y0=(Q,G)=>Q===G||Q.startContainer===G.startContainer&&Q.startOffset===G.startOffset&&Q.endContainer===G.endContainer&&Q.endOffset===G.endOffset,Z9=(Q,G)=>{if(Q===G)return!0;if(!Q||!G||Q.type!==G.type||Q.quality!==G.quality)return!1;if(Q.type==="range"&&G.type==="range")return y0(Q.range,G.range);if(Q.type==="element"&&G.type==="element")return Q.element===G.element;if(Q.type==="text-range"&&G.type==="text-range")return Q.node===G.node&&Q.startOffset===G.startOffset&&Q.endOffset===G.endOffset;return!1};class p7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=R.IDLE;ttsConfig={};currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Map;lastError=null;speakRunId=0;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];currentSeekSegmentIndex=0;activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=A8();static debugEnabled=(()=>{try{if(typeof process<"u"&&process.env?.PIE_TTS_DEBUG==="1")return!0}catch{}return globalThis.__PIE_TTS_DEBUG__===!0})();constructor(){}debugLog(Q,G){if(!p7.debugEnabled)return;if(G===void 0)console.debug(Q);else console.debug(Q,G)}clearPlaybackStartBarrier(Q=this.playbackStartBarrierCleanup){if(Q?.(),this.playbackStartBarrierCleanup===Q)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Q){if(this.playbackStartDeferredRunId!==Q||Q!==this.speakRunId)return;this.setState(R.PLAYING);let G=this.pendingPlaybackStartHighlights.splice(0);for(let Y of G)Y()}installPlaybackStartBarrier(Q,G=!1){this.clearPlaybackStartBarrier();let Y=this.provider,J=Y&&"onPlaybackStart"in Y?Y:null;if(!J&&!G)return null;let X=J?.onPlaybackStart,j=()=>{try{this.notifyPlaybackStarted(Q)}finally{X?.()}};if(J)J.onPlaybackStart=j;this.playbackStartDeferredRunId=Q;let Z=()=>{if(J?.onPlaybackStart===j)J.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Q)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=Z,Z}runWhenPlaybackStarts(Q,G){if(this.playbackStartDeferredRunId===Q){this.pendingPlaybackStartHighlights.push(G);return}G()}async emitTelemetry(Q,G){try{await this.telemetryReporter?.(Q,G)}catch(Y){console.warn("[TTSService] telemetry callback failed:",Y)}}async initialize(Q,G={}){this.currentProvider=Q,this.ttsConfig={...G};let Y=G.providerOptions&&typeof G.providerOptions==="object"?G.providerOptions:{};this.telemetryReporter=typeof Y.__pieTelemetry==="function"?Y.__pieTelemetry:null;try{this.provider=await Q.initialize(G)}catch(J){if(Q.providerId.toLowerCase()==="browser")throw J;if(!this.isBrowserSpeechFallbackAvailable())throw J;if(!await this.switchProviderToBrowser(J,{operation:"tts-initialize"}))throw J}}async updateSettings(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let G=this.provider;if(typeof G.updateSettings==="function"){let Y={...Q,...Q.providerOptions?{providerOptions:{...this.ttsConfig.providerOptions||{},...Q.providerOptions}}:{}};await G.updateSettings(Y),this.ttsConfig={...this.ttsConfig,...Y}}else console.warn("[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.")}setHighlightCoordinator(Q){this.highlightCoordinator=Q}setHighlightTargetResolverProvider(Q){return this.highlightTargetResolverProvider=Q,()=>{if(this.highlightTargetResolverProvider===Q)this.highlightTargetResolverProvider=null}}setCatalogResolver(Q){this.catalogResolver=Q}hasSpokenAlternate(Q,G="en-US"){if(!Q||!this.catalogResolver)return!1;return this.catalogResolver.getAlternative(Q,{type:"spoken",language:G,useFallback:!0,form:"content"})?.content!==void 0}getHighlightResolverRuntime(){let Q=null;try{Q=this.highlightTargetResolverProvider?.()??null}catch{Q=null}let G=Q?.context??{},Y=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...G,scopeElement:G.scopeElement??Y},resolver:Q?.resolver??null}}getNodeElement(Q){if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:Q.parentElement}isElementWithinScope(Q,G){if(!G)return!0;return Q===G||G.contains(Q)}isRangeWithinScope(Q,G){let Y=this.getNodeElement(Q.startContainer),J=this.getNodeElement(Q.endContainer);if(!Y||!J)return!1;return this.isElementWithinScope(Y,G)&&this.isElementWithinScope(J,G)}resolveWordHighlightRange(Q){let{context:G,resolver:Y}=this.getHighlightResolverRuntime(),J=G.scopeElement??this.currentContentElement;try{let X=Y?.resolveWordRange?.(Q,G);if(X&&this.isRangeWithinScope(X,J))return{range:X,remapped:!y0(Q,X)}}catch{}return{range:Q,remapped:!1}}resolveSentenceHighlightTargets(Q){let{context:G,resolver:Y}=this.getHighlightResolverRuntime(),J=G.scopeElement??this.currentContentElement;try{let X=Y?.resolveSentenceRanges?.(Q,G);if(!X)return{ranges:Q,elements:[]};let j=[],Z=[];for(let K of X){if(typeof Range<"u"&&K instanceof Range){if(!this.isRangeWithinScope(K,J))return{ranges:Q,elements:[]};j.push(K);continue}if(typeof Element<"u"&&K instanceof Element){if(!this.isElementWithinScope(K,J))return{ranges:Q,elements:[]};Z.push(K);continue}return{ranges:Q,elements:[]}}return{ranges:j,elements:Z}}catch{return{ranges:Q,elements:[]}}}createTextRange(Q,G,Y){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let J=document.createRange();if(J.setStart(Q,G),J.setEnd(Q,Y),J.startContainer!==Q||J.endContainer!==Q)return null;return J}catch{return null}}paintTTSWordRange(Q){if(!this.highlightCoordinator)return;try{if(Q.startContainer===Q.endContainer&&Q.startContainer.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(Q.startContainer,Q.startOffset,Q.endOffset);return}}catch{}this.highlightCoordinator.highlightRange(Q,u.TTS_WORD,_7.YELLOW)}paintTTSSentenceRanges(Q){if(!this.highlightCoordinator)return;let{ranges:G,elements:Y}=this.resolveSentenceHighlightTargets(Q);if(Y.length>0&&G.length===0&&this.highlightCoordinator.highlightTTSSentenceElements){this.highlightCoordinator.highlightTTSSentenceElements(Y);return}let J=[...G];for(let X of Y){let j=document.createRange();j.selectNodeContents(X),J.push(j)}this.highlightCoordinator.highlightTTSSentence(J)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}getTextProcessingOptions(Q){let Y=(this.ttsConfig.providerOptions||{}).textNormalization||{},J=Y.boundarySpacingMode,X=J==="none"||J==="alnum"||J==="segmenterPreferred"?J:void 0;return{locale:Q||(typeof Y.locale==="string"?Y.locale:void 0),boundarySpacingMode:X}}getMathSpeechOptions(){let G=(this.ttsConfig.providerOptions||{}).mathSpeech;return z7(G)}buildPositionMap(Q,G,Y){this.normalizedToDOM.clear();let{text:J,map:X}=C7(Q,this.getTextProcessingOptions(Y));if(this.normalizedToDOM=X,!p7.debugEnabled)return;this.debugLog("[TTSService] Text comparison:",{spokenLength:G.length,normalizedDomLength:J.length,match:G===J,spokenPreview:G.substring(0,150),normalizedPreview:J.substring(0,150),differAtIndex:G===J?null:(()=>{for(let j=0;j<Math.min(G.length,J.length);j++)if(G[j]!==J[j])return{index:j,spokenChar:G[j],normalizedChar:J[j],spokenContext:G.substring(Math.max(0,j-20),j+20),normalizedContext:J.substring(Math.max(0,j-20),j+20)};return null})()}),this.debugLog("[TTSService] Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:G.length,normalizedDomLength:J.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===G.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([j,{node:Z,offset:K}])=>({pos:j,offset:K,char:Z.textContent?.[K],expected:G[j]}))})}getStructuralPauseProfile(){let G=(this.ttsConfig.providerOptions||{}).structuralPauses||{},Y=G.units||{},J=(X,j)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let Z=Number(X);return Number.isFinite(Z)?Z:j}return j};return{baseMs:J(G.baseMs,280),units:{minor:J(Y.minor,0.65),section:J(Y.section,1),major:J(Y.major,1.35)},minMs:J(G.minMs,120),maxMs:J(G.maxMs,900)}}resolvePauseMsFromUnits(Q){let G=this.getStructuralPauseProfile(),Y=Math.max(0.25,Math.min(4,Number(this.ttsConfig.rate||1))),J=G.baseMs*Math.max(0,Q)/Y;return Math.max(G.minMs,Math.min(G.maxMs,Math.round(J)))}resolveHighlightMode(){let G=(this.ttsConfig.providerOptions||{}).highlightMode;if(G==="word"||G==="sentence")return G;if((this.currentProvider?.providerId||"").toLowerCase()==="browser")return"sentence";return this.currentProvider?.getCapabilities().supportsWordBoundary??!1?"word":"sentence"}hasExplicitBreakSemantics(Q){if(!Q.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Q)}isElementHidden(Q){return J8(Q)}getBoundaryStrength(Q){let G=Number(Q.getAttribute("data-tts-break-ms"));if(Number.isFinite(G)&&G>0)return"major";let Y=Q.tagName.toUpperCase();if(Y.match(/^H[1-6]$/))return"major";let J=(Q.getAttribute("role")||"").toLowerCase();if(J==="heading")return"major";if(J==="listitem"||J==="row"||J==="option"||J==="radio"||Y==="LI")return"section";if(typeof window<"u"){let X=window.getComputedStyle(Q).display;if(X==="block"||X==="list-item"||X.startsWith("table")||X==="flex"||X==="grid")return"minor"}return"minor"}getBoundaryAnchor(Q,G){let Y=Q.parentElement,J=null;while(Y&&Y!==G){if(this.isElementHidden(Y))return null;let j=Number(Y.getAttribute("data-tts-break-ms"));if(Number.isFinite(j)&&j>0)return{anchor:Y,units:j/this.getStructuralPauseProfile().baseMs};let Z=(Y.getAttribute("role")||"").toLowerCase(),K=Y.tagName.toUpperCase();if(K.match(/^H[1-6]$/)||Z==="heading"||Z==="listitem"||K==="LI"){J=Y;break}if(!J){if(typeof window<"u"){let W=window.getComputedStyle(Y).display;if(W==="block"||W==="list-item"||W.startsWith("table")||W==="flex"||W==="grid")J=Y}}Y=Y.parentElement}if(!J)return null;let X=this.getBoundaryStrength(J);return{anchor:J,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Q,G){let Y=this.collectSpeechPlanBoundaries(Q,G);return this.createSpeechPlanSegments(G,Y)}collectSpeechPlanBoundaries(Q,G){let Y=new Map,{map:J}=C7(Q,this.getTextProcessingOptions()),X=this.createNodeStartOffsets(J),j=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),Z=j.nextNode(),K=null;while(Z){let W=Z,B=W.parentElement;if(B&&!this.isElementHidden(B)&&!B1(W)){let U=this.getBoundaryAnchor(W,Q),V=X.get(W);if(U&&V!==void 0&&U.anchor!==K&&V>0)Y.set(V,Math.max(Y.get(V)||0,U.units)),K=U.anchor}Z=j.nextNode()}return Y}createNodeStartOffsets(Q){let G=new Map;for(let[Y,J]of Q.entries())if(!G.has(J.node))G.set(J.node,Y);return G}createSpeechPlanSegments(Q,G){let Y=Array.from(G.keys()).filter((W)=>W>0&&W<Q.length).sort((W,B)=>W-B),J=[],X=0;for(let W of Y){let B=Q.substring(X,W),U=B.match(/^\s*/)?.[0].length||0,V=B.match(/\s*$/)?.[0].length||0,H=X+U,N=W-V;if(N>H){let O=Q.substring(H,N);J.push({text:O,startOffset:H,pauseMsAfter:this.resolvePauseMsFromUnits(G.get(W)||0)})}X=W}let Z=Q.substring(X).match(/^\s*/)?.[0].length||0,K=X+Z;if(K<Q.length)J.push({text:Q.substring(K).trimEnd(),startOffset:K,pauseMsAfter:0});return J.filter((W)=>W.text.trim().length>0)}segmentSentences(Q){let G=this.ttsConfig.providerOptions?.locale||void 0;return E7(Q,{locale:G})}createSeekSegmentsFromText(Q){return this.segmentSentences(Q).map((G)=>{let Y=G.text.match(/^\s*/)?.[0].length||0;return{text:G.text.trim(),startOffset:G.offset+Y,pauseMsAfter:0}}).filter((G)=>G.text.length>0)}splitSegmentsAtBoundaries(Q,G,Y){if(Q.length===0||G.length===0)return Q;let J=Array.from(new Set(G)).filter((j)=>Number.isFinite(j)&&j>0).sort((j,Z)=>j-Z);if(J.length===0)return Q;let X=[];for(let j of Q){let Z=j.startOffset,K=j.startOffset+j.text.length,W=J.filter((U)=>U>Z&&U<K);if(W.length===0){X.push(j);continue}let B=Z;for(let U of[...W,K]){let V=Y.substring(B,U),H=V.match(/^\s*/)?.[0].length||0,N=V.match(/\s*$/)?.[0].length||0,O=B+H,P=U-N;if(P>O)X.push({text:Y.substring(O,P),startOffset:O,pauseMsAfter:0});B=U}}return X}createSentenceHighlightSegments(Q){let G=this.createSeekSegmentsFromText(Q.contentToSpeak);if(!Q.shouldUsePlan||Q.playbackSegments.length===0)return G;let Y=Q.playbackSegments.map((J)=>J.startOffset).filter((J)=>J>0);return this.splitSegmentsAtBoundaries(G,Y,Q.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Q){let G=0;return Q.map((Y)=>{let J=Y.plainFallback?.speechText||(this.hasExplicitBreakSemantics(Y.speechText)?Y.visibleText:Y.speechText)||Y.visibleText,X=T(J)||Y.visibleText||"",j={text:X,startOffset:G,pauseMsAfter:0};return G+=Math.max(1,X.length+1),j})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let Q=0;for(let G=0;G<this.seekSegments.length;G++)if(this.seekSegments[G].startOffset<=this.currentBoundaryOffset)Q=G;else break;return Q}async speakWithPlan(Q,G,Y){if(!this.provider||Q.length===0)return;let J=Y?.highlightMode==="sentence",X=this.provider;if(!J&&typeof X.speakSegments==="function"){this.currentBoundaryOffset=0;let j=this.provider.onWordBoundary;this.provider.onWordBoundary=(Z,K,W)=>{if(j?.(Z,K,W),Number.isFinite(K))this.currentBoundaryOffset=K,this.currentSeekSegmentIndex=this.getCurrentSeekSegmentIndex()};try{await X.speakSegments(Q)}finally{if(G===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=j}return}this.configureWordBoundaryHighlighting({highlightMode:Y?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let j of Q){if(G!==this.speakRunId)return;let Z=this.seekSegments.findIndex((W)=>W.startOffset===j.startOffset);if(Z>=0)this.currentSeekSegmentIndex=Z;if(this.currentBoundaryOffset=j.startOffset,J)this.runWhenPlaybackStarts(G,()=>{this.highlightSentenceSegment(j.startOffset,j.text)});await this.provider.speak(j.text);let K=j.pauseMsAfter??0;if(K>0)await new Promise((W)=>setTimeout(W,K))}}highlightSentenceSegment(Q,G){if(!this.highlightCoordinator||typeof document>"u")return;let Y=G.trimEnd().length;if(Y<=0)return;let J=this.normalizedToDOM.get(Q),X=this.normalizedToDOM.get(Q+Y-1);if(!J||!X)return;let j=document.createRange();j.setStart(J.node,J.offset),j.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([j]),this.activeSentenceStartOffset=Q}getSegmentIndexForOffset(Q,G){if(Q.length===0)return-1;let Y=-1;for(let J=0;J<Q.length;J++)if(Q[J].startOffset<=G)Y=J;else break;return Y}highlightSentenceForOffset(Q){let G=this.sentenceHighlightSegments;if(!this.highlightCoordinator||G.length===0)return;let Y=this.getSegmentIndexForOffset(G,Q);if(Y<0)return;let J=G[Y];if(!J)return;if(this.activeSentenceStartOffset===J.startOffset)return;this.highlightSentenceSegment(J.startOffset,J.text)}findHighlightRange(Q,G){let Y=this.normalizedToDOM.get(Q);if(!Y)return console.warn(`[TTSService] No mapping found for start position ${Q}`,{totalMappings:this.normalizedToDOM.size,nearbyMappings:Array.from(this.normalizedToDOM.entries()).filter(([j])=>Math.abs(j-Q)<5).map(([j,{offset:Z,node:K}])=>({pos:j,offset:Z,char:K.textContent?.[Z]}))}),null;let J=Q+G-1,X=this.normalizedToDOM.get(J);if(!X)return console.warn(`[TTSService] No mapping found for end position ${J}`,{startChar:Q,length:G,totalMappings:this.normalizedToDOM.size}),null;if(Y.node!==X.node)return console.warn("[TTSService] Word spans multiple nodes, highlighting in first node only"),{node:Y.node,start:Y.offset,end:(Y.node.textContent||"").length};return{node:Y.node,start:Y.offset,end:X.offset+1}}async speak(Q,G){if(!this.provider)throw Error("TTS service not initialized");let Y=++this.speakRunId;this.clearPlaybackStartBarrier();let J=null;try{if(await this.applyLanguageSettings(G),Y!==this.speakRunId)return;let X=await this.resolveSpeechContent(Q,G);if(Y!==this.speakRunId)return;let{contentToSpeak:j,speechText:Z,highlightText:K,normalizedText:W,usedCatalogSpoken:B,speechSource:U,speechMatchesVisibleText:V,speechChunks:H}=X;this.logResolvedSpeechContent({contentToSpeak:j,speechSource:U,catalogId:G?.catalogId}),this.initializeSpeakTracking(K,G);let N=G?.highlightModeOverride||(V?this.resolveHighlightMode():"sentence");this.activeHighlightMode=N,this.activeWordBoundaryOffset=G?.wordBoundaryOffset||0;let O=this.hasExplicitBreakSemantics(j),P=!!this.currentContentElement&&!B&&!O&&V;if(this.playbackChunks=H?.length?H:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):O||!V?[]:P&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,W):this.createSeekSegmentsFromText(K),this.sentenceHighlightSegments=O?[]:this.createSentenceHighlightSegments({contentToSpeak:K,shouldUsePlan:P,playbackSegments:this.seekSegments}),this.setState(R.LOADING),J=this.installPlaybackStartBarrier(Y,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:K,options:G,highlightMode:N,shouldUsePlan:P,runId:Y}),V)this.configureWordBoundaryHighlighting({highlightMode:N,wordBoundaryOffset:G?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(!J)this.setState(R.PLAYING);if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:P,runId:Y,highlightMode:N,contentToSpeak:Z,speechChunks:H}),Y!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(X){let j=X;if(console.error("TTS error:",j),this.lastError=j instanceof Error?j.message:String(j),Y!==this.speakRunId)return;throw this.setState(R.ERROR),this.clearHighlightsAndTracking(),j}finally{this.clearPlaybackStartBarrier(J)}}async switchProviderToBrowser(Q,G){if(!this.currentProvider)return!1;let Y=new b7,J=this.currentProvider.providerId,X={};if(this.ttsConfig.rate!==void 0)X.rate=this.ttsConfig.rate;if(this.ttsConfig.pitch!==void 0)X.pitch=this.ttsConfig.pitch;if(this.ttsConfig.mathTokenHighlighting!==void 0)X.mathTokenHighlighting=this.ttsConfig.mathTokenHighlighting;let j=G?.operation||"tts-initialize",Z=G?.contentToSpeak??"",K=Z.replace(/\s+/g," ").trim().slice(0,120),W=Z.length>0?{textLength:Z.length,textPreview:K.length<Z.length?`${K}…`:K}:{};try{return this.provider?.stop(),this.currentProvider.destroy(),this.currentProvider=Y,this.provider=await Y.initialize(X),this.ttsConfig=X,await this.emitTelemetry("pie-tool-runtime-fallback",{toolId:"textToSpeech",operation:j,fromProvider:J,toProvider:Y.providerId,reason:Q instanceof Error?Q.message:String(Q),...W}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:J,reason:Q,...W}),!0}catch(B){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:j,fromProvider:J,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:B instanceof Error?B.message:String(B)}),console.error("[TTSService] Failed to switch to browser fallback provider",B),!1}}isBrowserSpeechFallbackAvailable(){if(typeof window>"u")return!1;if(!("speechSynthesis"in window))return!1;return typeof globalThis.SpeechSynthesisUtterance==="function"}async applyLanguageSettings(Q){if(!Q?.language||!this.provider)return;let G=this.ttsConfig.providerOptions||{},Y=G.textNormalization||{},J=G.segmenter||{},X={...G,locale:Q.language,textNormalization:{...Y,locale:Q.language},segmenter:{...J,locale:Q.language}};if(this.ttsConfig={...this.ttsConfig,providerOptions:X},"updateSettings"in this.provider&&typeof this.provider.updateSettings==="function")await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Q,G){let Y=T(Q);if(G?.ignoreCatalogs)return{contentToSpeak:Y,speechText:Y,visibleText:Y,highlightText:Y,usedCatalogSpoken:!1,speechSource:"dom-or-input",normalizedText:Y,containsMathMarkup:!1,speechMatchesVisibleText:!0};if(G?.catalogId&&this.catalogResolver){let j=this.catalogResolver.getAlternative(G.catalogId,{type:"spoken",language:G.language||"en-US",useFallback:!0,context:G.catalogContext,form:"content"}),Z=j?.content;if(j&&Z!==void 0){let K=G?.contentElement?O7(G.contentElement,this.getTextProcessingOptions(G.language)).visibleText||Y:Y,W=T(Z);return this.debugLog(`[TTSService] Using catalog content for "${G.catalogId}" (${j.language})`),{contentToSpeak:Z,speechText:Z,visibleText:K,highlightText:K,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:K,containsMathMarkup:!1,speechMatchesVisibleText:W===K}}this.debugLog(`[TTSService] No catalog found for "${G.catalogId}", falling back to generated TTS`)}let J=G?.contentElement?this.resolveCatalogComposedSpeechContent(G.contentElement,Y,G):null;if(J)return J;return{...G?.contentElement?await this.resolveGeneratedSpeechContent(G.contentElement,Y,G.language):{contentToSpeak:Y,speechText:Y,visibleText:Y,highlightText:Y,normalizedText:Y,containsMathMarkup:!1,speechMatchesVisibleText:!0},usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Q,G,Y){if(!this.catalogResolver)return null;let J=this.collectCatalogSpeechChunks(Q,Y);if(!J.some((Z)=>Z.sourceElement))return null;let X=T(J.map((Z)=>Z.speechText).join(" ")),j=O7(Q,this.getTextProcessingOptions(Y.language)).visibleText||G;return{contentToSpeak:X,speechText:X,visibleText:j,highlightText:j,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:j,containsMathMarkup:!1,speechMatchesVisibleText:J.every((Z)=>Z.speechMatchesVisibleText),speechChunks:J}}collectCatalogSpeechChunks(Q,G){let Y=[],J="",X=()=>{let B=T(J);if(J="",!B)return;Y.push({speechText:B,visibleText:B,sourceElement:null,speechMatchesVisibleText:!0})},j=(B)=>{let U=B.getAttribute("data-catalog-idref");if(!U)return null;let V={type:"spoken",language:G.language||"en-US",useFallback:!0,context:G.catalogContext},H=this.catalogResolver.getAlternative(U,{...V,form:"payload"}),N=H?.payload?P6({payload:H.payload})??void 0:void 0,P=this.catalogResolver.getAlternative(U,{...V,form:"content"})?.content;if(N===void 0&&P===void 0)return null;return{script:P,audio:N}},Z=(B,U)=>{let V=K(B);if(V.length!==1)return null;let H=V[0],N=O7(H,this.getTextProcessingOptions(G.language)).visibleText||T(H.textContent||""),O=(P)=>T(P).replace(/\s+/g,"");return O(N)===O(U)?H:null},K=(B)=>{let U=Array.from(B.querySelectorAll("math"));if(B.localName?.toLowerCase()==="math")return[B,...U];return U},W=(B)=>{if(V7(B,Q))return;if(B.nodeType===Node.TEXT_NODE){J+=` ${B.textContent||""}`;return}if(B.nodeType!==Node.ELEMENT_NODE)return;let U=B,V=j(U);if(V){X();let H=O7(U,this.getTextProcessingOptions(G.language)),N=H.visibleText||T(U.textContent||""),O=M1(U,Q),P=V.script!==void 0?(()=>{let $=V.script,F=V1({speechText:$,visibleText:N}),L=Z(U,N),C=L?S7({mathElement:L,speechText:$}):void 0,v=C?void 0:K(U).map((I)=>({element:I,alignment:S7({mathElement:I,speechText:$})}));return{speechText:$,visibleText:N,sourceElement:U,regionElement:O,speechMatchesVisibleText:T($)===N,playbackMode:F.playbackMode,alignment:F,mathAlignment:C,mathAlignments:v,visibleMap:H.map}})():null;if(V.audio){Y.push(P?{...P,audio:V.audio,plainFallback:P}:{speechText:N,visibleText:N,sourceElement:U,regionElement:O,speechMatchesVisibleText:!1,visibleMap:H.map,audio:V.audio});return}if(P)Y.push(P);return}for(let H of Array.from(U.childNodes))W(H)};return W(Q),X(),Y}resolveGeneratedPlaybackFormat(){let Q=this.currentProvider;if(!Q)return"plain";if(Q.providerId?.toLowerCase()==="browser")return"plain";return Q.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Q,G,Y){let J=this.resolveGeneratedPlaybackFormat(),{plan:X,containsMathMarkup:j,visibleText:Z}=await z8({contentRoot:Q,language:Y,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(Y),produceSsml:J==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),K=Z||G;if(!j)return{contentToSpeak:K,speechText:K,visibleText:K,highlightText:K,normalizedText:K,containsMathMarkup:!1,speechMatchesVisibleText:!0};let W=P8(X,{format:J}),B=X.plainSpeechText;return{contentToSpeak:B,speechText:B,visibleText:K,highlightText:K,normalizedText:K,containsMathMarkup:!0,speechMatchesVisibleText:B===K,speechChunks:W}}logResolvedSpeechContent(Q){let G=Q.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);this.debugLog("[TTSService] Speak resolved content",{source:Q.speechSource,catalogId:Q.catalogId||null,length:Q.contentToSpeak.length,preview:G})}initializeSpeakTracking(Q,G){this.currentText=Q,this.currentContentElement=G?.contentElement||null,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Q){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Q.contentToSpeak,Q.options?.language),Q.highlightMode==="sentence"&&Q.shouldUsePlan)return;let G=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Q.runId,()=>{if(G)this.highlightSentenceSegment(G.startOffset,G.text),this.debugLog("[TTSService] Applied initial sentence highlighting");else try{let Y=document.createRange();Y.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([Y])}catch{}})}configureWordBoundaryHighlighting(Q){if(!this.provider||Q.highlightMode!=="word"||!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(G,Y,J)=>{let X=J||G.length,j=Y+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(j);let Z=this.findHighlightRange(j,X);if(Z&&this.highlightCoordinator){let K=Z.node.textContent?.substring(Z.start,Z.end)||"";this.debugLog(`[TTSService] Highlighting "${K}" (word: "${G}") at position ${j}`);let W=this.createTextRange(Z.node,Z.start,Z.end);if(W)this.paintTTSWordRange(this.resolveWordHighlightRange(W).range);else this.highlightCoordinator.highlightTTSWord(Z.node,Z.start,Z.end)}else console.warn(`[TTSService] Could not find highlight range for position ${j}, length ${X}`)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Q){let G=Q.regionElement||Q.sourceElement;if(!G&&!Q.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Q.regionRange){this.highlightCoordinator.clearHighlights?.(u.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!G)return;let Y=document.createRange();Y.selectNodeContents(G),this.highlightCoordinator.clearHighlights?.(u.TTS_WORD),this.paintTTSSentenceRanges([Y])}catch{}}highlightCatalogActiveRange(Q){if(!this.highlightCoordinator)return;this.paintTTSWordRange(this.resolveWordHighlightRange(Q).range)}highlightRenderableRegionTarget(Q){if(!this.highlightCoordinator||!Q||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&Z9(this.lastRenderedRegionTarget,Q))return;try{let G=document.createRange();if(Q.type==="element")G.selectNodeContents(Q.element);else if(Q.type==="range"){this.paintTTSSentenceRanges([Q.range]),this.lastRenderedRegionTarget=Q;return}else G.setStart(Q.node,Q.startOffset),G.setEnd(Q.node,Q.endOffset);this.paintTTSSentenceRanges([G]),this.lastRenderedRegionTarget=Q}catch{}}highlightRenderableActiveTarget(Q){if(!this.highlightCoordinator||typeof document>"u")return;if(!Q){this.highlightCoordinator.clearHighlights(u.TTS_WORD);return}if(Q.type==="text-range"){let X=this.createTextRange(Q.node,Q.startOffset,Q.endOffset);if(X)this.paintTTSWordRange(this.resolveWordHighlightRange(X).range);else this.highlightCoordinator.highlightTTSWord(Q.node,Q.startOffset,Q.endOffset);return}if(Q.type==="range"){this.highlightCatalogActiveRange(Q.range);return}let G=document.createRange();G.selectNodeContents(Q.element);let Y=this.resolveWordHighlightRange(G);if(Y.remapped){this.paintTTSWordRange(Y.range);return}let J=Q.element.childNodes.length===1?Q.element.firstChild:null;if(Q.quality==="semantic-token"&&J?.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(J,0,J.textContent?.length||0);return}this.highlightCoordinator.highlightTTSWordElement?.(Q.element)}renderHighlightDecision(Q){this.highlightRenderableRegionTarget(Q.regionTarget),this.highlightRenderableActiveTarget(Q.activeTarget)}async speakCatalogChunk(Q,G){try{await this.speakCatalogChunkOnce(Q,G)}catch(Y){if(Q.plainFallback&&G===this.speakRunId){if(this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:Y instanceof Error?Y.message:String(Y)}),this.playbackStartDeferredRunId===G&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.setState(R.PLAYING);await this.speakCatalogChunkOnce(Q.plainFallback,G);return}throw Y}}async playRecordedAudio(Q,G){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let Y=Q.sources[0],J=document.createElement("audio");J.preload="auto",J.src=z6(Y.src,Q.fragment),J.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,j)=>{let Z,K=!1,W=!1,B=()=>{if(W||K)return;K=!0,G?.()},U=()=>{if(J.removeEventListener("ended",V),J.removeEventListener("error",H),J.removeEventListener("playing",B),Z?.(),this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null},V=()=>{if(W)return;W=!0,U(),X()},H=()=>{if(W)return;W=!0,U(),j(Error(`[tts] recorded audio failed to play: ${Y.src}`))};this.activeRecordedAudio={element:J,cancel:()=>{if(W)return;W=!0,U(),J.pause(),X()}},J.addEventListener("ended",V),J.addEventListener("error",H),J.addEventListener("playing",B),Z=O6(J,Q.fragment,V),Promise.resolve(J.play()).then(B).catch(H)}).finally(()=>{if(this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null;J.pause(),J.removeAttribute("src")})}cancelRecordedAudio(){let Q=this.activeRecordedAudio;if(!Q)return;this.activeRecordedAudio=null,Q.cancel()}async speakCatalogChunkOnce(Q,G){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Q.audio){this.runWhenPlaybackStarts(G,()=>{this.highlightCatalogRegion(Q)}),await this.playRecordedAudio(Q.audio,()=>{this.notifyPlaybackStarted(G)});return}let Y=Q.regionElement||Q.sourceElement||this.currentContentElement,J=Y?C0({contentRoot:Y,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,j=J?b0({chunks:[J],mathTokenHighlighting:X}):null;if(this.runWhenPlaybackStarts(G,()=>{if(j&&J&&Q.mathAlignment)this.renderHighlightDecision(j.resolveInitial(J.id));else this.highlightCatalogRegion(Q)}),!(Q.sourceElement&&(Q.mathAlignment&&Q.mathAlignment.speech.tokens.length>0||Q.mathAlignments&&Q.mathAlignments.length>0||Q.alignment&&Q.visibleMap&&(Q.playbackMode==="exact-word"||Q.playbackMode==="anchor-span")))){let U=this.provider,V=U.onWordBoundary;U.onWordBoundary=void 0;try{await U.speak(Q.speechText)}finally{if(this.provider===U&&G===this.speakRunId&&U.onWordBoundary===void 0)U.onWordBoundary=V}return}let K=this.provider,W=K.onWordBoundary,B=(U,V,H)=>{if(G!==this.speakRunId)return;if(j&&J){let N=J.offsetSpace==="unsupported"?"unknown":J.offsetSpace;this.renderHighlightDecision(j.resolveBoundary({chunkId:J.id,word:U,position:V,length:H,providerOffsetSpace:N}));return}};K.onWordBoundary=B;try{await K.speak(Q.speechText)}finally{if(this.provider===K&&G===this.speakRunId&&K.onWordBoundary===B)K.onWordBoundary=W}}async executeSpeakPlayback(Q){if(Q.speechChunks?.length&&this.provider){for(let G=0;G<Q.speechChunks.length;G++){if(Q.runId!==this.speakRunId)return;this.currentSeekSegmentIndex=G;let Y=this.seekSegments[G];if(Y)this.currentBoundaryOffset=Y.startOffset;let J=Q.speechChunks[G];await this.speakCatalogChunk(J,Q.runId)}return}if(Q.shouldUsePlan&&this.currentContentElement){let G=this.seekSegments;if(G.length>0)await this.speakWithPlan(G,Q.runId,{highlightMode:Q.highlightMode});else if(this.provider)await this.provider.speak(Q.contentToSpeak);return}if(this.provider)await this.provider.speak(Q.contentToSpeak)}clearHighlightsAndTracking(){if(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.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}async speakRange(Q,G){if(!this.provider)throw Error("TTS service not initialized");if(B1(Q.commonAncestorContainer)){console.warn("[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.");return}let J=G?.contentRoot||null;if(!J){let U=Q.commonAncestorContainer;J=U.nodeType===Node.ELEMENT_NODE?U:U.parentElement}if(!J)return;let X=X8(Q,J),j=X.text.trim();if(!j){if(X.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return}let Z=document.createRange();Z.selectNodeContents(J),Z.setEnd(Q.startContainer,Q.startOffset);let K=X8(Z,J).text,W=T(K),B=W.length+(/\s$/.test(K)&&W?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:j,textBeforeRange:K.substring(0,100),offset:B,rootTag:J.tagName}),await this.speak(j,{contentElement:J,ignoreCatalogs:!0,wordBoundaryOffset:B})}pause(){if(!this.provider)return;if(this.state===R.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(R.PAUSED)}resume(){if(!this.provider)return;if(this.state===R.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState(R.PLAYING)}}normalizePlaybackRate(Q){if(!Number.isFinite(Q))return 1;return Math.max(0.25,Math.min(4,Q))}async restartFromSeekIndex(Q){if(!this.provider||this.seekSegments.length===0)return;let G=Math.max(0,Math.min(this.seekSegments.length-1,Q)),Y=this.playbackChunks.length?this.playbackChunks.slice(G):null;this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=G;let J=++this.speakRunId,X=this.seekSegments.slice(G);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.setState(R.LOADING);let j=this.installPlaybackStartBarrier(J,!!Y?.[0]?.audio);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}),Y)for(let Z=0;Z<Y.length;Z++){if(J!==this.speakRunId)return;let K=G+Z;this.currentSeekSegmentIndex=K;let W=this.seekSegments[K];if(W)this.currentBoundaryOffset=W.startOffset;await this.speakCatalogChunk(Y[Z],J)}else await this.speakWithPlan(X,J,{highlightMode:this.activeHighlightMode});if(J!==this.speakRunId)return;this.setState(R.IDLE),this.clearHighlightsAndTracking()}catch(Z){if(J!==this.speakRunId)return;throw this.lastError=Z instanceof Error?Z.message:String(Z),this.setState(R.ERROR),this.clearHighlightsAndTracking(),Z}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let G=this.normalizePlaybackRate(Q),Y=this.pendingPlaybackRateRequest;if(Y?.rate===G){await Y.promise;return}let J=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let K=this.speakRunId;if(J!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:K};let W=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(G===W)return{didUpdate:!1,playbackRunId:K};return await this.updateSettings({rate:G}),{didUpdate:!0,playbackRunId:K}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let j=X.then(async(K)=>{if(J!==this.playbackRateRequestId||K.playbackRunId!==this.speakRunId)return;let W=this.activePlaybackRate!==null&&this.activePlaybackRate!==G;if(!K.didUpdate&&!W)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())}),Z;Z=j.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===Z)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:G,promise:Z},await Z}async seekBy(Q){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 G=Number.isFinite(Q)?Math.trunc(Q):0;if(G===0)return;let Y=this.getCurrentSeekSegmentIndex(),J=Math.max(0,Math.min(this.seekSegments.length-1,Y+G));if(J===Y)return;await this.restartFromSeekIndex(J)}async seekForward(Q=1){let G=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(G)}async seekBackward(Q=1){let G=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(-G)}stop(){if(!this.provider)return;if(this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.setState(R.IDLE),this.currentText=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.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null,this.activePlaybackRate=null}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(S0,{detail:Q}))}isPlaying(){return this.state===R.PLAYING}isPaused(){return this.state===R.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(Q,G){if(!this.listeners.has(Q))this.listeners.set(Q,new Set);this.listeners.get(Q).add(G)}offStateChange(Q,G){let Y=this.listeners.get(Q);if(Y){if(Y.delete(G),Y.size===0)this.listeners.delete(Q)}}setState(Q){if(this.state===Q)return;let G=this.state;this.state=Q;for(let Y of this.listeners.values())for(let J of Y)J(Q);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",providerId:"tts",previousState:G,state:Q}),Q===R.PLAYING){let Y=G===R.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(Y,{toolId:"textToSpeech",providerId:"tts",previousState:G,state:Q});return}if(Q===R.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:G,state:Q});return}if(Q===R.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:G,state:Q,message:this.lastError||void 0});return}if(Q===R.IDLE&&(G===R.PLAYING||G===R.PAUSED||G===R.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:G,state:Q})}}var j9=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),x0=(Q)=>Q&&typeof Q==="object"?Q:{},K9=(Q)=>Q==="polly"||Q==="google"||Q==="server",l=(Q,G)=>Q===void 0?G:Q,q9=(Q,G="left-aligned")=>typeof Q==="string"&&j9.has(Q)?Q:G,ZG=Object.freeze([0.8,1.25]),jG=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 KG=Object.freeze([0.8,1,1.25]);var W9=(Q)=>{let G={...Q,layoutMode:q9(Q.layoutMode)},Y=Q.backend||"browser";if(!K9(Y))return G;let J={...G,apiEndpoint:l(G.apiEndpoint,"/api/tts"),transportMode:l(G.transportMode,"pie"),endpointValidationMode:l(G.endpointValidationMode,"voices"),validateEndpoint:l(G.validateEndpoint,!0),includeAuthOnAssetFetch:l(G.includeAuthOnAssetFetch,!1),rate:l(G.rate,1),language:l(G.language,"en-US")};if(Y==="polly")return{...J,defaultVoice:l(J.defaultVoice,"Joanna"),engine:l(J.engine,"neural"),format:l(J.format,"mp3"),speechMarksMode:l(J.speechMarksMode,"word+sentence")};if(Y==="google")return{...J,defaultVoice:l(J.defaultVoice,"en-US-Wavenet-A")};return J},f0=(Q)=>{let G=x0(Q),Y=x0(G.settings);return W9({...G,...Y})},L8=(Q)=>Q.backend||"browser",U9=(Q,G)=>{if(G==="polly"||G==="google")return G;if(G==="server")return Q.serverProvider||Q.provider;return Q.serverProvider||Q.provider},B9=(Q,G)=>Q.transportMode||(G==="custom"?"custom":"pie"),k0=(Q)=>{let G=L8(Q),Y=U9(Q,G),J=B9(Q,Y),X=z7(Q.mathSpeech);return{voice:Q.defaultVoice,rate:Q.rate,pitch:Q.pitch,providerOptions:{...Q.language?{locale:Q.language}:{},...G==="polly"&&Q.engine?{engine:Q.engine}:{},...G==="polly"&&typeof Q.sampleRate==="number"?{sampleRate:Q.sampleRate}:{},...G==="polly"&&Q.format?{format:Q.format}:{},...G==="polly"?{speechMarkTypes:Q.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...J==="custom"&&typeof Q.cache==="boolean"?{cache:Q.cache}:{},...J==="custom"&&Q.speedRate?{speedRate:Q.speedRate}:{},...J==="custom"&&Q.lang_id?{lang_id:Q.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Q.apiEndpoint,provider:Y,language:Q.language,transportMode:J,endpointMode:Q.endpointMode,endpointValidationMode:Q.endpointValidationMode,includeAuthOnAssetFetch:Q.includeAuthOnAssetFetch,validateEndpoint:Q.validateEndpoint,...typeof Q.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Q.mathTokenHighlighting}:{}}};class O1{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Q,G,Y){try{await Q.onTelemetry?.(G,Y)}catch(J){console.warn("[ToolProviderRegistry] Telemetry callback failed:",J)}}register(Q,G){if(this.providers.has(Q)){console.warn(`[ToolProviderRegistry] Provider "${Q}" already registered, skipping`);return}if(this.providers.set(Q,G.provider),this.configs.set(Q,G),this.initialized.set(Q,!1),console.log(`[ToolProviderRegistry] Registered provider "${Q}" (${G.provider.providerName})`),G.lazy===!1)this.initialize(Q).catch((Y)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Q}":`,Y)})}async initialize(Q){if(this.initialized.get(Q))return;let G=this.initializationPromises.get(Q);if(G)return G;let Y=this._doInitialize(Q);this.initializationPromises.set(Q,Y);try{await Y}finally{this.initializationPromises.delete(Q)}}async _doInitialize(Q){let G=this.providers.get(Q),Y=this.configs.get(Q);if(!G||!Y)throw Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);let J={...Y.config},X=(Z)=>{if(!Z||typeof Z!=="object")return"unknown";let K=Z;return(typeof K.backend==="string"?K.backend:typeof K.provider==="string"?K.provider:typeof K.serverProvider==="string"?K.serverProvider:typeof K.providerId==="string"?K.providerId:"")||"unknown"},j=Date.now();if(await this.emitTelemetry(Y,"pie-tool-init-start",{toolId:Q,providerId:Q,backend:X(J),operation:"provider-initialize"}),G.requiresAuth&&Y.authFetcher){let Z=Date.now();await this.emitTelemetry(Y,"pie-tool-backend-call-start",{toolId:Q,providerId:Q,backend:X(J),operation:"auth-fetch"}),console.log(`[ToolProviderRegistry] Fetching auth for "${Q}"...`);try{let K=await Y.authFetcher();J={...J,...K},await this.emitTelemetry(Y,"pie-tool-backend-call-success",{toolId:Q,providerId:Q,backend:X(J),operation:"auth-fetch",duration:Date.now()-Z})}catch(K){throw await this.emitTelemetry(Y,"pie-tool-backend-call-error",{toolId:Q,providerId:Q,backend:X(J),operation:"auth-fetch",duration:Date.now()-Z,errorType:"ProviderAuthFetchError",message:K instanceof Error?K.message:String(K)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Q}":`,K),Error(`Failed to fetch auth credentials for provider "${Q}"`)}}try{await G.initialize(J),this.initialized.set(Q,!0),await this.emitTelemetry(Y,"pie-tool-init-success",{toolId:Q,providerId:Q,backend:X(J),operation:"provider-initialize",duration:Date.now()-j}),console.log(`[ToolProviderRegistry] Provider "${Q}" initialized`)}catch(Z){throw await this.emitTelemetry(Y,"pie-tool-init-error",{toolId:Q,providerId:Q,backend:X(J),operation:"provider-initialize",duration:Date.now()-j,errorType:"ProviderInitializationError",message:Z instanceof Error?Z.message:String(Z)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Q}":`,Z),Z}}async getProvider(Q,G=!0){console.log("[ToolProviderRegistry] getProvider called",{providerId:Q,autoInitialize:G,isRegistered:this.providers.has(Q),isInitialized:this.initialized.get(Q),allProviderIds:Array.from(this.providers.keys())});let Y=this.providers.get(Q);if(!Y)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Q,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);if(G&&!this.initialized.get(Q))console.log("[ToolProviderRegistry] Auto-initializing provider:",Q),await this.initialize(Q);return console.log("[ToolProviderRegistry] Returning provider:",{providerId:Q,providerName:Y.providerName,isReady:Y.isReady()}),Y}getProvidersByCategory(Q){return Array.from(this.providers.entries()).filter(([G,Y])=>Y.category===Q).map(([G])=>G)}getProviderIds(){return Array.from(this.providers.keys())}has(Q){return this.providers.has(Q)}isInitialized(Q){return this.initialized.get(Q)===!0}isInitializing(Q){return this.initializationPromises.has(Q)}async unregister(Q){let G=this.providers.get(Q);if(G){let Y=this.initializationPromises.get(Q);if(Y)try{await Y}catch{}G.destroy(),this.providers.delete(Q),this.configs.delete(Q),this.initialized.delete(Q),this.initializationPromises.delete(Q),console.log(`[ToolProviderRegistry] Unregistered provider "${Q}"`)}}async destroy(){let Q=Array.from(this.providers.keys());await Promise.all(Q.map((G)=>this.unregister(G))),console.log("[ToolProviderRegistry] Registry destroyed")}}class $8{targets=new Set;changeListeners=new Set;registerTarget(Q){return this.targets.add(Q),this.notifyChange(),()=>{if(!this.targets.delete(Q))return;this.notifyChange()}}canRequest(Q,G){return this.findTarget(Q,G)!==null}request(Q){let G=this.findTarget(Q.toolId,Q.level);if(!G)return!1;try{G.open(Q.toolId,Q.params)}catch(Y){return console.error(`[ToolRequestRegistry] Target failed to open "${Q.toolId}":`,Y),!1}return!0}onTargetsChange(Q){return this.changeListeners.add(Q),()=>{this.changeListeners.delete(Q)}}findTarget(Q,G){let Y=this.findTargetAtLevel(Q,G??"section");if(Y||G!==void 0)return Y;for(let J of this.targets){if(J.level==="section")continue;if(this.hostsTool(J,Q))return J}return null}findTargetAtLevel(Q,G){for(let Y of this.targets){if(Y.level!==G)continue;if(this.hostsTool(Y,Q))return Y}return null}hostsTool(Q,G){try{return Q.hostsTool(G)===!0}catch(Y){return console.warn(`[ToolRequestRegistry] Target at level "${Q.level}" failed the host check for "${G}":`,Y),!1}}notifyChange(){for(let Q of this.changeListeners)try{Q()}catch(G){console.warn("[ToolRequestRegistry] Target change listener threw:",G)}}}var D9=(Q)=>`No assessment is bound, so no policy source could grant "${Q}"`;function w8(Q,G,Y,J){return{featureId:Q,granted:!1,action:"block",rule:G,precedence:0,sourceType:"host",reason:G==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${Y.join(", ")})`,required:!1,assessmentBound:J.assessmentBound}}function I0(Q,G,Y){let J=G.decisions[0],X=Array.from(G.perToolFlags.values())[0],j=J?.action==="enable",Z=J?.reason??`Feature "${Q}" not configured`;return{featureId:Q,granted:j,action:J?.action??"skip",rule:J?.rule??"pnp-support",precedence:J?.precedence??6,sourceType:J?.sourceType??"system",reason:Y.assessmentBound||j?Z:D9(Q),required:Boolean(X?.required),parameters:X?.settings,assessmentBound:Y.assessmentBound}}class z1{provenance;stepCounter=0;constructor(Q){this.provenance={contextId:Q,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Q,G){let Y={id:G.id,name:G.name??G.id};switch(Q){case"organization":this.provenance.sources.organization={...Y,pnpDefaults:G.config};break;case"assessment":this.provenance.sources.assessment={...Y,settings:G.config};break;case"section":this.provenance.sources.section={...Y,settings:G.config};break;case"item":this.provenance.sources.item={...Y,settings:G.config};break;case"student":this.provenance.sources.student={id:G.id,pnpProfile:G.config};break;case"host":this.provenance.sources.host={id:G.id,config:G.config};break}return this}addDecision(Q){let G={step:++this.stepCounter,precedence:Q.precedence,rule:Q.rule,featureId:Q.featureId,action:Q.action,source:{type:Q.sourceType,id:Q.sourceId,name:Q.sourceName},reason:Q.reason,value:Q.value,timestamp:new Date};this.provenance.decisionLog.push(G);let Y=this.provenance.features.get(Q.featureId);if(!Y)Y={featureId:Q.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Q.featureId,Y);if(Y.allDecisions.push(G),Q.action==="advisory"){if(Y.finalState==="not-configured")Y.finalState="advisory-only"}else if(Q.action!=="skip"){if(!Y.winningDecision||G.precedence<Y.winningDecision.precedence)Y.winningDecision=G,Y.finalState=G.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Q.sourceType]=(this.provenance.summary.bySource[Q.sourceType]||0)+1,this.provenance.summary.byRule[Q.rule]=(this.provenance.summary.byRule[Q.rule]||0)+1,this}reconcileFinalStates(Q){for(let G of Q){let Y=this.provenance.features.get(G);if(!Y){Y={featureId:G,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(G,Y);continue}Y.finalState="enabled"}for(let G of this.provenance.features.values()){if(Q.has(G.featureId))continue;let Y=G.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),J=G.allDecisions.some((X)=>X.action==="advisory");if(Y)G.finalState="blocked";else if(J)G.finalState="advisory-only";else G.finalState="not-configured"}return this}build(){for(let Q of this.provenance.features.values())Q.explanation=_9(Q);for(let Q of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Q.finalState==="enabled")this.provenance.summary.enabled++;else if(Q.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function _9(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let j=Q.allDecisions.find((Z)=>Z.action==="advisory");return j?`Feature "${Q.featureId}" was kept in its host-decided state; ${j.reason}`:`Feature "${Q.featureId}" carries an advisory note.`}return`Feature "${Q.featureId}" was not configured at any level.`}let G=Q.winningDecision,Y=G.source.name||G.source.type,J=`Feature "${Q.featureId}" is ${Q.finalState}.
|
|
216
216
|
|
|
217
|
-
`;
|
|
218
|
-
`,
|
|
219
|
-
`,
|
|
220
|
-
`;let X=Q.allDecisions.filter((j)=>j.step!==
|
|
217
|
+
`;J+=`**Primary Reason** (${G.rule}):
|
|
218
|
+
`,J+=`${G.reason}
|
|
219
|
+
`,J+=`Source: ${Y} (${G.source.type})
|
|
220
|
+
`;let X=Q.allDecisions.filter((j)=>j.step!==G.step&&j.action!=="skip"&&j.action!=="advisory"&&j.precedence>G.precedence);if(X.length>0){J+=`
|
|
221
221
|
**Overridden Rules**:
|
|
222
|
-
`;for(let j of X)
|
|
223
|
-
`}return G}function z8(Q){let{request:Y,tools:J,pnpPolicy:G,customSources:X,contextId:j}=Q,Z=new A1(j);Z.addSource("host",{id:Y.scope.scopeId,name:`${Y.level}:${Y.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let q=M1(J.placement[Y.level]),K=M1(J.policy.allowed),B=new Set(M1(J.policy.blocked)),U=[];for(let F of q)U.push(F),Z.addDecision({precedence:0,rule:"placement-membership",featureId:F,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Y.level}`});if(U=U.filter((F)=>{if(J.providers?.[F]?.enabled===!1)return Z.addDecision({precedence:0,rule:"provider-disabled",featureId:F,action:"block",sourceType:"host",reason:`tools.providers.${F}.enabled === false`,value:!1}),!1;return!0}),K.length>0){let F=new Set(K);U=U.filter(($)=>{if(!F.has($))return Z.addDecision({precedence:0,rule:"host-allowlist",featureId:$,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:K}),!1;return!0})}U=U.filter((F)=>{if(B.has(F))return Z.addDecision({precedence:0,rule:"host-blocked",featureId:F,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let H=[],_=new Map;for(let F of U)_.set(F,["placement"]);let A=new Set(U),M=null;if(G.enforcement==="on"&&G.source&&(G.assessment||G.currentItemRef)){if(M=G.source.apply({assessment:G.assessment,currentItemRef:G.currentItemRef}),M.sources.assessment)Z.addSource("assessment",M.sources.assessment);if(M.sources.student)Z.addSource("student",M.sources.student);if(M.sources.item)Z.addSource("item",M.sources.item);for(let F of M.decisions)Z.addDecision({precedence:F.precedence,rule:F.rule,featureId:F.featureId,action:F.action,sourceType:F.sourceType,reason:F.reason,value:F.value});U=U.filter((F)=>{return!M.blockedToolIds.has(F)});for(let F of Array.from(_.keys()))if(M.blockedToolIds.has(F))_.delete(F);for(let F of M.mandatedToolIds){if(!!A.has(F))continue;let v=M.perToolFlags.get(F)?.rule??"required-tool",k=r2(F,{placement:q,allowed:K,blocked:B,providers:J.providers}),p={rule:v,hostRule:k.hostRule,hostValue:k.hostValue};H.push({code:"tool-policy.requiredToolBlocked",level:Y.level,toolId:F,message:`Profile policy mandates "${F}" (${v}) but host policy removed it from level "${Y.level}" via ${k.hostRule}.`,details:p}),Z.addDecision({precedence:0,rule:"required-tool-blocked",featureId:F,action:"advisory",sourceType:"host",reason:`Host removed required tool "${F}" via ${k.hostRule}`,value:p})}for(let F of U){let $=M.perToolFlags.get(F);if($){let b=_.get(F)??[];b.push(`pnp.${$.rule}`),_.set(F,b)}}}for(let F=0;F<X.length;F++){let $=X[F],b=U.slice(),v=$.refine({request:Y,candidates:b}),k=new Set(v.refinedCandidates);for(let w of v.refinedCandidates)if(!b.includes(w))H.push({code:"tool-policy.placementMissing",level:Y.level,toolId:w,message:`Custom source "${$.id}" tried to add tool "${w}" that was not in candidates; ignored.`,source:`custom.${$.id}`}),k.delete(w);U=b.filter((w)=>k.has(w));let p=new Set;if(v.decisions){for(let w of v.decisions)if(Z.addDecision({precedence:w.precedence??100+F,rule:w.rule,featureId:w.featureId,action:w.action,sourceType:w.sourceType,reason:w.reason,value:w.value}),w.action==="block")p.add(w.featureId)}for(let w of b){if(k.has(w))continue;if(p.has(w))continue;Z.addDecision({precedence:100+F,rule:"custom-source",featureId:w,action:"block",sourceType:"custom",reason:`Custom policy source "${$.id}" removed tool "${w}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:$.id}})}for(let w of U){let l=_.get(w)??["placement"];l.push(`custom.${$.id}`),_.set(w,l)}for(let w of b)if(!k.has(w))_.delete(w)}let O=new Set(U),L=U.map((F)=>{let $=M?.perToolFlags.get(F);return{toolId:F,required:$?.required??!1,alwaysAvailable:$?.alwaysAvailable??!1,settings:$?.settings,sources:_.get(F)??["placement"]}});return Z.reconcileFinalStates(O),{visibleTools:L,diagnostics:H,provenance:Z.build()}}function r2(Q,Y){if(!Y.placement.includes(Q))return{hostRule:"placement-missing",hostValue:Y.placement};if(Y.providers?.[Q]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Y.allowed.length>0&&!Y.allowed.includes(Q))return{hostRule:"host-allowlist",hostValue:Y.allowed};if(Y.blocked.has(Q))return{hostRule:"host-blocked",hostValue:Array.from(Y.blocked)};return{hostRule:"placement-missing",hostValue:Y.placement}}function b6(Q){if(!Q)return!1;let Y=Q.personalNeedsProfile;if(Y){if(Array.isArray(Y.supports)&&Y.supports.length>0)return!0;if(Array.isArray(Y.prohibitedSupports)&&Y.prohibitedSupports.length>0)return!0;if(Array.isArray(Y.activateAtInit)&&Y.activateAtInit.length>0)return!0}let J=Q.settings;if(J){let G=J.districtPolicy;if(G){if(Array.isArray(G.blockedTools)&&G.blockedTools.length>0)return!0;if(Array.isArray(G.requiredTools)&&G.requiredTools.length>0)return!0;if(G.policies&&typeof G.policies==="object"&&Object.keys(G.policies).length>0)return!0}let X=J.testAdministration;if(X&&typeof X==="object")for(let j of Object.keys(X)){let Z=X[j];if(Z===void 0||Z===null)continue;if(Array.isArray(Z)&&Z.length===0)continue;if(typeof Z==="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0)continue;return!0}}return!1}function S6(Q){let Y=Q?.settings;if(!Y)return!1;if(Array.isArray(Y.requiredTools)&&Y.requiredTools.length>0)return!0;if(Array.isArray(Y.restrictedTools)&&Y.restrictedTools.length>0)return!0;if(Y.toolParameters&&typeof Y.toolParameters==="object"&&Object.keys(Y.toolParameters).length>0)return!0;return!1}function u7(Q){if(b6(Q.assessment))return"on";if(S6(Q.currentItemRef))return"on";return"off"}class N1{id="pnp";toolRegistry;constructor(Q){this.toolRegistry=Q}apply(Q){let{ctx:Y,result:J}=this.prepare(Q),{pnp:G,districtPolicy:X,itemSettings:j}=Y,Z=new Set;G?.supports?.forEach((q)=>Z.add(q)),G?.prohibitedSupports?.forEach((q)=>Z.add(q)),X?.blockedTools?.forEach((q)=>Z.add(q)),X?.requiredTools?.forEach((q)=>Z.add(q)),j?.requiredTools?.forEach((q)=>Z.add(q)),j?.restrictedTools?.forEach((q)=>Z.add(q));for(let q of Z)this.resolveSupport(q,Y,J);return J}resolveFeature(Q,Y){let{ctx:J,result:G}=this.prepare(Y);return this.resolveSupport(Q,J,G),G}prepare(Q){let{assessment:Y,currentItemRef:J}=Q,G=Y?.personalNeedsProfile,X=Y?.settings,j=J?.settings,Z={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)Z.sources.assessment={id:Y?.id||"unknown",name:Y?.name||Y?.id||"Assessment",config:X};if(G)Z.sources.student={id:"student",name:"Student PNP Profile",config:G};if(J&&j)Z.sources.item={id:J.identifier,name:J.identifier,config:j};return{ctx:{pnp:G,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:j,toolConfigs:X?.toolConfigs},result:Z}}resolveSupport(Q,Y,J){if(Y.districtPolicy?.blockedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:1,rule:"district-block",featureId:X,action:"block",sourceType:"assessment",reason:`District policy blocks "${Q}" for all assessments`,value:Y.districtPolicy.blockedTools});return}if(Y.testAdmin?.toolOverrides?.[Q]===!1){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:X,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Q}" for this session`,value:Y.testAdmin.toolOverrides});return}if(Y.itemSettings?.restrictedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:3,rule:"item-restriction",featureId:X,action:"block",sourceType:"item",reason:`Item restricts "${Q}" (e.g., mental math question blocks calculator)`,value:Y.itemSettings.restrictedTools});return}if(Y.itemSettings?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"item-requirement",sourceType:"item"}),J.decisions.push({precedence:4,rule:"item-requirement",featureId:X,action:"enable",sourceType:"item",reason:`Item requires "${Q}" for this question`,value:Y.itemSettings.requiredTools});return}if(Y.districtPolicy?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"district-requirement",sourceType:"assessment"}),J.decisions.push({precedence:5,rule:"district-requirement",featureId:X,action:"enable",sourceType:"assessment",reason:`District policy requires "${Q}" for all assessments`,value:Y.districtPolicy.requiredTools});return}if(Y.pnp?.prohibitedSupports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:6,rule:"pnp-prohibited",featureId:X,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Q}"`,value:Y.pnp.prohibitedSupports});return}if(Y.pnp?.supports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.perToolFlags.set(X,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(Q,Y),rule:"pnp-support",sourceType:"student"}),J.decisions.push({precedence:6,rule:"pnp-support",featureId:X,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Q}"`,value:Y.pnp.supports});return}let G=this.mapSupportToToolId(Q);J.decisions.push({precedence:6,rule:"pnp-support",featureId:G,action:"skip",sourceType:"system",reason:`Feature "${Q}" not configured at any level`,value:{supportId:Q}})}mapSupportToToolId(Q){let Y=this.toolRegistry.getToolsByPNPSupport(Q);if(Y.size===0)return Q;return Array.from(Y)[0]}resolveToolSettings(Q,Y){return Y.itemSettings?.toolParameters?.[Q]??Y.toolConfigs?.[Q]}}var T6=$7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class z1{toolRegistry;contextId;pnpPolicySource;customSources;listeners=new Set;tools;assessment;currentItemRef;pnpEnforcement;disposed=!1;constructor(Q){this.toolRegistry=Q.toolRegistry,this.contextId=Q.contextId??"tool-policy",this.pnpPolicySource=new N1(this.toolRegistry),this.customSources=Q.customSources?[...Q.customSources]:[];let Y=Q.inputs??{};this.tools=Y.tools??T6,this.assessment=Y.assessment??null,this.currentItemRef=Y.currentItemRef??null,this.pnpEnforcement=Y.pnpEnforcement??u7({assessment:this.assessment,currentItemRef:this.currentItemRef})}decide(Q){this.assertNotDisposed();let Y=Q.scope.scopeId?`${this.contextId}:${Q.level}:${Q.scope.scopeId}`:`${this.contextId}:${Q.level}`;return z8({request:Q,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0,enforcement:this.pnpEnforcement},customSources:this.customSources,contextId:Y})}decideFeature(Q){return this.assertNotDisposed(),E6(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}),{assessmentBound:this.assessment!==null})}getVisibleToolIds(Q,Y){return this.decide({level:Q,scope:{level:Q,scopeId:Y}}).visibleTools.map((J)=>J.toolId)}updateInputs(Q){this.assertNotDisposed();let Y=!1,J=!1;if("tools"in Q){let G=Q.tools??T6;if(!Object.is(this.tools,G))this.tools=G,Y=!0}if("assessment"in Q){let G=Q.assessment??null;if(!Object.is(this.assessment,G))this.assessment=G,Y=!0}if("currentItemRef"in Q){let G=Q.currentItemRef??null;if(!Object.is(this.currentItemRef,G))this.currentItemRef=G,Y=!0}if("pnpEnforcement"in Q&&Q.pnpEnforcement){if(this.pnpEnforcement!==Q.pnpEnforcement)this.pnpEnforcement=Q.pnpEnforcement,J=!0}if(Y||J)this.emit({reason:J&&!Y?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Q){return this.assertNotDisposed(),this.customSources.push(Q),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Y=this.customSources.indexOf(Q);if(Y!==-1){if(this.customSources.splice(Y,1),!this.disposed)this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}}onPolicyChange(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,currentItemRef:this.currentItemRef,pnpEnforcement:this.pnpEnforcement})}emit(Q){for(let Y of Array.from(this.listeners))try{Y(Q)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}var o2=Symbol("@pie-players/tool-policy-engine");var O1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),a2=(Q,Y,J)=>{let G={...Y,...J};if(Q==="textToSpeech"&&O1(Y.settings)&&O1(J.settings)){if(G.settings={...Y.settings,...J.settings},O1(Y.settings.mathSpeech)&&O1(J.settings.mathSpeech))G.settings.mathSpeech={...Y.settings.mathSpeech,...J.settings.mathSpeech}}return G},t2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],e2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error"];class P1{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;ttsInitialized=!1;ttsInitPromise;ttsReconfigurePromise;stateLoaded=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;toolRegistry;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitPromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;policyEngine;pnpEnforcementOverride=null;boundAssessment=null;boundCurrentItemRef=null;reportedUnboundFeaturePolicy=!1;static resolveConfig(Q){let Y=u1(Q.toolConfigStrictness),J=Q.toolRegistry??new O8,G=Q.deferToolConfigValidation===!0?$7(Q.tools):G7(Q.tools,{strictness:Y,source:"ToolkitCoordinator.init",toolRegistry:J}).config;return{...Q,toolConfigStrictness:Y,toolRegistry:J,tools:{...G,providers:{...{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}},...G.providers}},accessibility:{language:"en-US",...Q.accessibility??{},catalogs:Q.accessibility?.catalogs??[]}}}constructor(Q){if(!Q.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");let Y=P1.resolveConfig(Q);if(this.assessmentId=Y.assessmentId,this.config=Y,this.toolRegistry=Y.toolRegistry??new O8,this.installToolContextResolvers(Y.toolContextResolvers),this.hooks=Y.hooks??{},this.lazyInit=Q.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=Q.frameworkErrorBus??new v7,this.ownsFrameworkErrorBus=!Q.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new t1,this.highlightCoordinator=new h7,this.elementToolStateStore=new o1,this.catalogResolver=new r1(Y.accessibility?.catalogs||[],Y.accessibility?.language||"en-US"),this.toolProviderRegistry=new F1,this._registerToolProviders(),this.ttsService=new m7,this.setupStatePersistenceHooks(),this.policyEngine=new z1({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,currentItemRef:null,pnpEnforcement:this.resolveEffectivePnpEnforcement()}}),!this.lazyInit)this.waitUntilReady().catch((J)=>{console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready"})})}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorBus.subscribeFrameworkErrors((Q)=>{let Y=this.hooks.onFrameworkError;if(!Y)return;try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Q,Y){try{await this.hooks.onTelemetry?.(Q,Y)}catch(G){console.warn("[ToolkitCoordinator] telemetry hook failed:",G)}let J=Y?{...Y}:void 0;for(let G of this.telemetryListeners)try{G({eventName:Q,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Q){for(let Y of this.sectionControllerLifecycleListeners)try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Q,Y){let J=r8({error:Q,context:Y});this.frameworkErrorBus.reportFrameworkError(J)}subscribeFrameworkErrors(Q){return this.frameworkErrorBus.subscribeFrameworkErrors(Q)}reportFrameworkError(Q){this.frameworkErrorBus.reportFrameworkError(Q)}getSectionControllerMapKey(Q){return`${Q.assessmentId}::${Q.sectionId}::${Q.attemptId||""}`}createDefaultSectionPersistence(){let Q=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Y=(J)=>{let{assessmentId:G,sectionId:X,attemptId:j}=J.key;return`pie:section-controller:v1:${G}:${X}:${j||"default"}`};return{async loadSession(J){if(!Q)return null;let G=Q.getItem(Y(J));if(!G)return null;try{return JSON.parse(G)}catch{return null}},async saveSession(J,G){if(!Q)return;Q.setItem(Y(J),JSON.stringify(G))},async clearSession(J){if(!Q)return;Q.removeItem(Y(J))}}}async resolveSectionPersistence(Q){let Y=this.getSectionControllerMapKey(Q.key),J=this.sectionPersistenceStrategies.get(Y);if(J)return J;let G={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Q,G)??await G.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Y,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Q)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Q)).catch((Y)=>{this.handleError(Y,{phase:"state-save"})})})}async ensureStateLoaded(){if(this.stateLoaded)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Q=this.hooks.loadToolState;if(!Q)return;try{let Y=await Q();if(Y&&typeof Y==="object")this.elementToolStateStore.loadState(Y);this.stateLoaded=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Y)})}catch(Y){this.handleError(Y,{phase:"state-load"})}})().finally(()=>{this.stateLoadPromise=void 0}),this.stateLoadPromise}_registerToolProviders(){let Q=this.getProviderDescriptorTools();for(let Y of Q)this.registerProviderFromTool(Y)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Q)=>!!Q.provider)}async registerProviderFromTool(Q){let Y=Q.provider;if(!Y)return;let J=this.getToolConfig(Q.toolId)||void 0;if(J?.enabled===!1)return;let G=Y.getProviderId?.(J)??J?.provider?.id??Q.toolId;if(this.toolProviderRegistry.has(G))return;let X=Y.createProvider(J),j=Y.getInitConfig?.(J)??J?.provider?.init??{},Z=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:G,initConfig:j}),q=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:G}),K=Y.getAuthFetcher?.(J)??J?.provider?.runtime?.authFetcher;await this.registerProvider(G,{provider:X,config:Z,lazy:Y.lazy??!0,authFetcher:K,onTelemetry:q})}createToolTelemetryForwarder(Q){return async(Y,J)=>{await this.emitTelemetry(Y,{...J||{},toolId:Q.toolId,providerId:Q.providerId})}}addToolTelemetryReporter(Q){let Y=Q.initConfig&&typeof Q.initConfig==="object"?{...Q.initConfig}:{},J=typeof Y.onTelemetry==="function"?Y.onTelemetry:null,G=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:Q.providerId});return Y.onTelemetry=async(X,j)=>{if(J)await J(X,j);await G(X,j)},Y}async registerProvider(Q,Y){try{this.toolProviderRegistry.register(Q,Y);let J={providerId:Q,providerName:Y.provider.providerName};await this.hooks.onProviderRegistered?.(Q,J),await this.emitTelemetry("pie-toolkit-provider-registered",{providerId:Q,providerName:Y.provider.providerName})}catch(J){console.warn(`[ToolkitCoordinator] Failed to register provider "${Q}":`,J),this.handleError(J,{phase:"provider-register",providerId:Q})}}async ensureProviderReady(Q){let Y=this.providerInitPromises.get(Q);if(Y)return Y;let J=(async()=>{let G=await this.toolProviderRegistry.getProvider(Q,!1),X={providerId:Q,providerName:G.providerName};try{return await this.hooks.onProviderInitStart?.(Q,X),await this.toolProviderRegistry.initialize(Q),await this.hooks.onProviderReady?.(Q,X),await this.emitTelemetry("pie-toolkit-provider-ready",{providerId:Q}),G}catch(j){let Z=j instanceof Error?j:Error(String(j));throw this.handleError(Z,{phase:"provider-init",providerId:Q}),Z}})().finally(()=>{this.providerInitPromises.delete(Q)});return this.providerInitPromises.set(Q,J),J}setHooks(Q){if(Object.assign(this.hooks,Q),this.setupStatePersistenceHooks(),Q.onCoordinatorReady&&this.isReady())Promise.resolve(Q.onCoordinatorReady(this)).catch((Y)=>{this.handleError(Y,{phase:"coordinator-ready"})})}subscribeTelemetry(Q){return this.telemetryListeners.add(Q),()=>{this.telemetryListeners.delete(Q)}}getSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(Y))}subscribeSectionEvents(Q){if(this.activeCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Y=this.activeSubscriptions.get(Q.listener);if(Y)Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null;let J={listener:Q.listener,eventTypes:Q.eventTypes,itemIds:Q.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Q.listener,J);let G=this.sectionControllers.get(this.activeCohortMapKey);if(G)this.bindSubscriptionToController(J,G);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Q.listener)===J)this.activeSubscriptions.delete(Q.listener)}}bindSubscriptionToController(Q,Y){Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J=Y.subscribe;if(typeof J!=="function")return;let G=this.buildSectionEventPredicate(Q);Q.unsubscribeCurrent=J.call(Y,(Z)=>{if(!G(Z))return;this.deliverSectionEventSafely(Q.listener,Z)});let X=this.buildContentLoadedReplayEvents(Y);for(let Z of X)if(G(Z))this.deliverSectionEventSafely(Q.listener,Z);let j=this.buildLoadingCompleteReplayEvent(Y);if(j&&G(j))this.deliverSectionEventSafely(Q.listener,j)}deliverSectionEventSafely(Q,Y){try{Q(Y)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Q){if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=Q;let Y=this.sectionControllers.get(Q);if(!Y)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Y)}setActiveCohortIfLatestRequest(Q){if(this.latestRequestedActiveCohortMapKey!==Q)return;this.setActiveCohort(Q)}suspendActiveCohortIfSuperseded(Q){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}clearActiveCohortIfMatches(Q){if(this.activeCohortMapKey!==Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}buildSectionEventPredicate(Q){let Y=Q.eventTypes?new Set(Q.eventTypes):null,J=Q.itemIds?new Set(Q.itemIds):null;return(G)=>{if(Y||J){let X=G?.type||null;if(Y&&(!X||!Y.has(X)))return!1;if(J){if(!Array.from(this.collectEventItemIds(G)).some((Z)=>J.has(Z)))return!1}}return!0}}collectEventItemIds(Q){let Y=new Set;if("itemId"in Q&&typeof Q.itemId==="string")Y.add(Q.itemId);if("canonicalItemId"in Q&&typeof Q.canonicalItemId==="string")Y.add(Q.canonicalItemId);if("currentItemId"in Q&&typeof Q.currentItemId==="string")Y.add(Q.currentItemId);if("previousItemId"in Q&&typeof Q.previousItemId==="string")Y.add(Q.previousItemId);return Y}buildContentLoadedReplayEvents(Q){let Y=Q.getRuntimeState?.(),J=Y?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let G=typeof Y?.currentItemIndex==="number"&&Number.isFinite(Y.currentItemIndex)?Y.currentItemIndex:0,X=Date.now(),j=[];for(let Z of J){if(!Z)continue;let q=Z.itemId,K=typeof Z.canonicalItemId==="string"&&Z.canonicalItemId?Z.canonicalItemId:q;if(typeof q!=="string"||!q)continue;j.push({type:"content-loaded",contentKind:Z.contentKind??"unknown",itemId:q,canonicalItemId:K,currentItemIndex:G,timestamp:X})}return j}buildLoadingCompleteReplayEvent(Q){let Y=Q.getRuntimeState?.();if(Y?.loadingComplete!==!0)return null;let J=typeof Y.totalRegistered==="number"&&Number.isFinite(Y.totalRegistered)?Math.max(0,Y.totalRegistered):0,G=typeof Y.totalLoaded==="number"&&Number.isFinite(Y.totalLoaded)?Math.max(0,Y.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:G,currentItemIndex:Y.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||t2,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||e2,listener:Q.listener})}onSectionControllerLifecycle(Q){return this.sectionControllerLifecycleListeners.add(Q),()=>{this.sectionControllerLifecycleListeners.delete(Q)}}async getOrCreateSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let G=await this.resolveExistingSectionController({mapKey:J,key:Y,input:Q.input,updateExisting:Q.updateExisting});if(G)return G;let X=this.sectionControllerInitPromises.get(J);if(X)return X;let j=this.initializeNewSectionController({args:Q,key:Y,mapKey:J}).catch((Z)=>{throw this.handleSectionControllerInitError(Z,Q),Z}).finally(()=>{this.sectionControllerInitPromises.delete(J)});return this.sectionControllerInitPromises.set(J,j),j}async resolveExistingSectionController(Q){let Y=this.sectionControllers.get(Q.mapKey);if(!Y)return;if(this.sectionControllerKeys.set(Q.mapKey,Q.key),Q.updateExisting!==!1)await Y.updateInput?.(Q.input);return this.setActiveCohortIfLatestRequest(Q.mapKey),Y}createSectionControllerContext(Q){return{key:Q.key,coordinator:this,input:Q.input}}async initializeNewSectionController(Q){let Y=this.createSectionControllerContext({key:Q.key,input:Q.args.input}),J=await this.resolveSectionPersistence(Y),G={createDefaultController:Q.args.createDefaultController},X=await this.hooks.createSectionController?.(Y,G)??await G.createDefaultController();return await X.configureSessionPersistence?.({strategy:J,context:Y}),await X.initialize?.(Q.args.input),await X.hydrate?.(),await this.finalizeSectionControllerReady({mapKey:Q.mapKey,key:Q.key,context:Y,controller:X}),X}async finalizeSectionControllerReady(Q){this.sectionControllers.set(Q.mapKey,Q.controller),this.sectionControllerKeys.set(Q.mapKey,Q.key),this.setActiveCohortIfLatestRequest(Q.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Q.key,controller:Q.controller}),await this.hooks.onSectionControllerReady?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}handleSectionControllerInitError(Q,Y){this.handleError(Q,{phase:"section-controller-init",details:{sectionId:Y.sectionId,attemptId:Y.attemptId}})}async disposeSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y),G=this.sectionControllers.get(J);if(!G)return;this.clearActiveCohortIfMatches(J);let X=this.createSectionControllerContext({key:Y,input:void 0});try{await this.runSectionControllerDisposePipeline({key:Y,context:X,controller:G,persistBeforeDispose:Q.persistBeforeDispose})}catch(j){this.handleError(j,{phase:"section-controller-dispose",details:{sectionId:Q.sectionId,attemptId:Q.attemptId}})}finally{await this.finalizeSectionControllerDispose({mapKey:J,key:Y,context:X,clearPersistence:Q.clearPersistence})}}async runSectionControllerDisposePipeline(Q){if(Q.persistBeforeDispose!==!1)await Q.controller.persist?.();await Q.controller.dispose?.(),await this.hooks.onSectionControllerDispose?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}async finalizeSectionControllerDispose(Q){if(this.sectionControllers.delete(Q.mapKey),this.sectionControllerKeys.delete(Q.mapKey),this.emitSectionControllerLifecycle({type:"disposed",key:Q.key}),Q.clearPersistence)await this.sectionPersistenceStrategies.get(Q.mapKey)?.clearSession?.(Q.context);this.sectionPersistenceStrategies.delete(Q.mapKey)}async ensureTTSReady(Q){if(await this.waitForPendingTTSReconfigure(),this.ttsInitialized)return;if(this.ttsInitPromise)return this.ttsInitPromise;return this.ttsInitPromise=this._initializeTTS(Q).finally(()=>{this.ttsInitPromise=void 0}),this.ttsInitPromise}async waitForPendingTTSReconfigure(){let Q=this.ttsReconfigurePromise;while(Q)await Q,Q=this.ttsReconfigurePromise}async _initializeTTS(Q){if(this.ttsInitialized)return;let Y=this.resolveTTSToolConfig(Q),J=w6(Y),G=N8(J),X=R6(J);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:G}}),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:G}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:G}),this.toolProviderRegistry.has("tts"))try{let q=await(await this.ensureProviderReady("tts")).createInstance();await this.initializeTTSService(q,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"registry"}),console.log("[ToolkitCoordinator] TTS initialized via ToolProviderRegistry");return}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,errorType:"TTSRegistryInitError",message:q.message,recovered:!0}),await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,fromProvider:"registry",toProvider:"browser",reason:q.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",q)}let j=new R7;try{await this.initializeTTSService(j,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"browser-fallback"})}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));throw this.handleError(q,{phase:"tts-init"}),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:q.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:G,errorType:"TTSInitError",message:q.message}),q}}resolveTTSToolConfig(Q){return Q||this.getTTSConfigFromProviders()||{}}async initializeTTSService(Q,Y){let J={...Y.providerOptions||{},__pieTelemetry:async(X,j)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...j||{}})}},G={...Y,providerOptions:J};await this.ttsService.initialize(Q,G),await this.ensureBrowserVoicesReady(Q),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,await this.hooks.onTTSReady?.()}async ensureBrowserVoicesReady(Q,Y=1200){if(Q.providerId!=="browser")return;if(typeof window>"u")return;if(!("speechSynthesis"in window))return;let J=window.speechSynthesis;if(J.getVoices().length>0)return;await new Promise((j)=>{let Z=!1,q=typeof J.addEventListener==="function"&&typeof J.removeEventListener==="function",K=!q&&"onvoiceschanged"in J,B=K?J.onvoiceschanged:null,U=!1,H=()=>{if(Z)return;if(Z=!0,window.clearTimeout(A),q)J.removeEventListener("voiceschanged",_);else if(U&&J.onvoiceschanged===_)J.onvoiceschanged=B;j()},_=(M)=>{if(!q&&typeof B==="function"&&M)B.call(J,M);H()},A=window.setTimeout(H,Y);if(q)J.addEventListener("voiceschanged",_,{once:!0});else if(K)J.onvoiceschanged=_,U=!0});let X=J.getVoices();await this.emitTelemetry("pie-toolkit-tts-browser-voices-ready",{voiceCount:X.length,timedOut:X.length===0})}getServiceBundle(){return{ttsService:this.ttsService,toolCoordinator:this.toolCoordinator,highlightCoordinator:this.highlightCoordinator,elementToolStateStore:this.elementToolStateStore,catalogResolver:this.catalogResolver,toolProviderRegistry:this.toolProviderRegistry}}async getToolProvider(Q){return this.ensureProviderReady(Q)}async waitUntilReady(){if(this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded();let Q=this.getTTSConfigFromProviders();if(Q?.enabled!==!1)await this.ensureTTSReady(Q);if(!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return this.getInitStatus().coordinator}getInitStatus(){let Q={};for(let J of this.toolProviderRegistry.getProviderIds())Q[J]=this.toolProviderRegistry.isInitialized(J);let Y=this.getTTSConfigFromProviders();return{tts:this.ttsInitialized,stateLoaded:this.stateLoaded||!this.hooks.loadToolState,coordinator:(this.stateLoaded||!this.hooks.loadToolState)&&(this.ttsInitialized||Y?.enabled===!1),providers:Q}}getTTSConfigFromProviders(){return(this.config.tools?.providers||{}).textToSpeech}assertCanonicalToolId(Q){if(typeof Q!=="string"||Q.trim().length===0)throw Error("Tool id must be a non-empty string.");if(Q==="tts")throw Error('Tool id "tts" is no longer supported. Use "textToSpeech".');if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Q))throw Error(`Unknown tool id "${Q}".`)}installToolContextResolvers(Q){if(!Q)return;for(let[Y,J]of Object.entries(Q)){if(J==null)continue;if(this.assertCanonicalToolId(Y),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Y}": expected a function.`);this.toolContextResolvers.set(Y,J)}}setToolContextResolvers(Q){this.toolContextResolvers.clear(),this.installToolContextResolvers(Q??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Q of this.toolContextResolverChangeListeners)try{Q()}catch(Y){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Y)}}isToolEnabled(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]?.enabled!==!1}getToolConfig(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]||null}updateToolConfig(Q,Y){this.assertCanonicalToolId(Q);let J=this.getToolConfig(Q)||{};if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}).config;if(!this.config.tools.providers)this.config.tools.providers={};let G={...this.config.tools.providers||{},[Q]:a2(Q,J,Y)},X=G7({...this.config.tools,providers:G},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X.config,this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Q}),this._applyToolConfigChange(Q,Y)}updateToolPlacement(Q,Y){this.updateToolsPlacement({[Q]:[...Y]})}updateToolsPlacement(Q){if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}).config;let Y=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Q.section??Y.section??[]],item:[...Q.item??Y.item??[]],passage:[...Q.passage??Y.passage??[]]},G=G7({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});G.config.placement=J,this.config.tools=G.config,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(Q){return this.policyEngine.decide(Q)}decideFeaturePolicy(Q){let Y=this.policyEngine.decideFeature(Q);if(!Y.assessmentBound&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Q}" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`);return Y}onPolicyChange(Q){return this.policyEngine.onPolicyChange(Q)}onCatalogsChange(Q){return this.catalogResolver.onCatalogsChange(Q)}updateAssessment(Q){this.boundAssessment=Q,this.policyEngine.updateInputs({assessment:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}updateCurrentItemRef(Q){this.boundCurrentItemRef=Q,this.policyEngine.updateInputs({currentItemRef:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}setPnpEnforcement(Q){this.pnpEnforcementOverride=Q,this.policyEngine.updateInputs({pnpEnforcement:this.resolveEffectivePnpEnforcement()})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Q){return this.policyEngine.registerPolicySource(Q)}registerToolContextResolver(Q,Y){if(this.assertCanonicalToolId(Q),typeof Y!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);return this.toolContextResolvers.set(Q,Y),this.notifyToolContextResolverChange(),()=>{if(this.toolContextResolvers.get(Q)!==Y)return;this.toolContextResolvers.delete(Q),this.notifyToolContextResolverChange()}}hasToolContextResolver(Q){return this.assertCanonicalToolId(Q),this.toolContextResolvers.has(Q)}resolveToolContext(Q){this.assertCanonicalToolId(Q.toolId);let Y=this.toolContextResolvers.get(Q.toolId);if(!Y)return null;let J;try{J=Y(Q)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Q.toolId}" threw:`,X),{toolId:Q.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Q.toolId,visible:!0,params:{}};let G=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Q.toolId,visible:J.visible!==!1,params:G,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Q){return this.toolContextResolverChangeListeners.add(Q),()=>{this.toolContextResolverChangeListeners.delete(Q)}}resolveEffectivePnpEnforcement(){if(this.pnpEnforcementOverride!==null)return this.pnpEnforcementOverride;return u7({assessment:this.boundAssessment,currentItemRef:this.boundCurrentItemRef})}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Q,Y){switch(Q){case"textToSpeech":{let J=this._reconfigureTTSProvider();this.ttsReconfigurePromise=J,J.finally(()=>{if(this.ttsReconfigurePromise===J)this.ttsReconfigurePromise=void 0}),J.then(async()=>{let G=this.getTTSConfigFromProviders();if(!this.lazyInit&&G?.enabled!==!1)await this.ensureTTSReady(G)});break}case"answerEliminator":break}}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsInitPromise=void 0;try{this.ttsService.stop()}catch{}if(this.toolProviderRegistry.has("tts"))await this.toolProviderRegistry.unregister("tts");let Q=this.getProviderDescriptorTools().find((Y)=>Y.toolId==="textToSpeech");if(!Q)return;await this.registerProviderFromTool(Q)}}var C6="pie-register",y6="pie-unregister",x6="pie-item-session-changed";var f6="pie-content-loaded",k6="pie-item-player-error";var Q5={bubbles:!0,composed:!0,cancelable:!1};function Y5(Q,Y,J={}){return new CustomEvent(Q,{detail:Y,...Q5,...J})}function P8(Q,Y,J,G={}){return Q.dispatchEvent(Y5(Y,J,G))}function T7(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function L8(Q,Y){if(Q===Y)return!0;if(!Q||!Y)return!1;return Q.sectionId===Y.sectionId&&Q.attemptId===Y.attemptId}function J5(Q){if(Q.runtimeError)return"error";if(Q.allLoadingComplete)return"ready";if(Q.interactionReady)return"interaction-ready";if(Q.sectionReady)return"loading";return"bootstrapping"}function I6(Q){let Y=Q.signals.sectionReady&&Q.signals.allLoadingComplete,J=Q.mode==="strict"?Y:Q.signals.interactionReady;return{phase:J5({...Q.signals,allLoadingComplete:Y,interactionReady:J}),interactionReady:J,allLoadingComplete:Y,reason:Q.reason}}function v6(Q){switch(Q){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function L1(Q,Y,J,G="entered"){let X=v6(Y);if(!X)return;Q.push({kind:"stage-change",stage:X,status:G,cohort:J})}function h6(Q){let Y={...T7(),phase:"booting-section",cohort:Q.cohort,effectiveRuntime:Q.effectiveRuntime,effectiveToolsConfig:Q.effectiveToolsConfig,itemCount:Q.itemCount},J=[];return L1(J,"booting-section",Q.cohort),{state:Y,outputs:J}}function G5(Q,Y){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let J=I6({mode:Y.mode,signals:Y.signals}),G=[],X=Q.phase,j=Q.loadingCompleteEmitted;if(X==="engine-ready"&&J.interactionReady)X="interactive",L1(G,X,Q.cohort);if(J.allLoadingComplete&&Q.cohort&&!j)j=!0,G.push({kind:"loading-complete",cohort:Q.cohort,itemCount:Y.itemCount,loadedCount:Y.loadedCount});return{state:{...Q,phase:X,readinessSignals:Y.signals,loadedCount:Y.loadedCount,itemCount:Y.itemCount,loadingCompleteEmitted:j},outputs:G}}function p7(Q,Y){switch(Y.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if(L8(Q.cohort,Y.cohort))return p7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});return p7(Q,{kind:"cohort-change",cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}return h6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}case"update-runtime":{if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};return{state:{...Q,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig},outputs:[]}}case"cohort-change":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(L8(Q.cohort,Y.cohort))return p7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});let J=[];if(Q.phase!=="idle")J.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:Q.cohort});let G=h6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount});return{state:G.state,outputs:[...J,...G.outputs]}}case"section-controller-resolved":{if(Q.phase!=="booting-section")return{state:{...Q,controllerResolved:!0},outputs:[]};let J=[];return L1(J,"engine-ready",Q.cohort),{state:{...Q,phase:"engine-ready",controllerResolved:!0},outputs:J}}case"update-readiness-signals":return G5(Q,{signals:Y.signals,mode:Y.mode,loadedCount:Y.loadedCount,itemCount:Y.itemCount});case"framework-error":return{state:{...Q,lastFrameworkError:Y.error,readinessSignals:{...Q.readinessSignals,runtimeError:Y.error.recoverable===!0?Q.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:Y.error}]};case"dispose":{if(Q.phase==="disposed")return{state:Q,outputs:[]};let J=[];if(Q.phase!=="idle")L1(J,"disposed",Q.cohort);return{state:{...Q,phase:"disposed"},outputs:J}}default:{let J=Y;return{state:Q,outputs:[]}}}}class $8{state=T7();listeners=new Set;getState(){return this.state}dispatch(Q){let Y=p7(this.state,Q);if(this.state=Y.state,Y.outputs.length>0)this.fanOut(Y.outputs);return Y.outputs}subscribe(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}disposeListeners(){this.listeners.clear()}fanOut(Q){let Y=Array.from(this.listeners),J=Object.freeze(Q.slice());for(let G of Y)try{G(J)}catch(X){console.warn("[SectionEngineCore] listener failed:",X)}}}function m6(Q){let{coordinator:Y,dispatchCoreInput:J}=Q,G=0,X=null,j=null,Z=!1,q=Y.subscribeFrameworkErrors((H)=>{try{J({kind:"framework-error",error:H})}catch(_){console.warn("[CoordinatorBridge] framework-error dispatch failed:",_)}});function K(){if(!j)return;try{j()}catch(H){console.warn("[CoordinatorBridge] controller unsubscribe failed:",H)}j=null}async function B(H){if(Z)return;G+=1;let _=G;X=H.cohort;let A=await Y.getOrCreateSectionController({sectionId:H.cohort.sectionId,attemptId:H.cohort.attemptId||void 0,input:{section:H.section,sectionId:H.cohort.sectionId,assessmentId:H.assessmentId,view:H.view},updateExisting:!0,createDefaultController:H.createDefaultController});if(_!==G||Z)return;K(),H.onControllerResolved?.(A);let M=A.getCompositionModel;if(H.onCompositionChanged?.(M?.()),typeof A.subscribe==="function")j=A.subscribe((O)=>{if(_!==G||Z)return;H.onCompositionChanged?.(M?.())});J({kind:"section-controller-resolved"})}async function U(){if(Z)return;Z=!0,G+=1,K();try{q()}catch(_){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",_)}let H=X;if(X=null,H)try{await Y.disposeSectionController({sectionId:H.sectionId,attemptId:H.attemptId||void 0})}catch(_){console.warn("[CoordinatorBridge] section-controller dispose failed:",_)}}return{resolveSectionController:B,dispose:U}}function u6(Q){let{runtimeId:Y,sourceCe:J}=Q,G=Q.host,X=Q.now??(()=>new Date().toISOString());function j(U){let H={stage:U.stage,status:U.status,runtimeId:Y,sectionId:U.cohort?.sectionId,attemptId:U.cohort?.attemptId?U.cohort.attemptId:void 0,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-stage-change",{detail:H}))}function Z(U){let H={runtimeId:Y,sectionId:U.cohort.sectionId,attemptId:U.cohort.attemptId?U.cohort.attemptId:void 0,itemCount:U.itemCount,loadedCount:U.loadedCount,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:H}))}function q(U){G.dispatchEvent(new CustomEvent("framework-error",{detail:U.error}))}function K(U){switch(U.kind){case"stage-change":j(U);return;case"loading-complete":Z(U);return;case"framework-error":q(U);return;default:{let H=U;return}}}function B(U){G=U}return{dispatch:K,setHost:B}}function p6(Q){let{bus:Y}=Q;function J(G){switch(G.kind){case"framework-error":Y.reportFrameworkError(G.error);return;case"stage-change":case"loading-complete":return;default:{let X=G;return}}}return{dispatch:J}}function g6(Q={}){let Y=Q.hook;function J(X){if(!Y)return;try{Y(X)}catch(j){console.warn("[InstrumentationBridge] hook failed:",j)}}function G(X){Y=X}return{dispatch:J,setHook:G}}function c6(){let Q=new Set;function Y(j){if(j.length===0)return;let Z=Array.from(Q),q=Object.freeze(j.slice());for(let K of Z)try{K(q)}catch(B){console.warn("[SubscriberFanout] listener failed:",B)}}function J(j){Q.add(j);let Z=!0;return()=>{if(!Z)return;Z=!1,Q.delete(j)}}function G(){Q.clear()}function X(){return Q.size}return{emit:Y,subscribe:J,dispose:G,getListenerCount:X}}class w8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new $8,this.domEventBridge=u6({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=p6({bus:Q.frameworkErrorBus}),this.instrumentationBridge=g6({hook:Q.instrumentationHook}),this.subscriberFanout=c6(),this.coordinatorBridge=Q.coordinator?m6({coordinator:Q.coordinator,dispatchCoreInput:(Y)=>this.dispatchInput(Y)}):null,this.unsubscribeCore=this.core.subscribe((Y)=>{this.routeOutputs(Y)})}getState(){return this.core.getState()}dispatchInput(Q){if(this.disposed)return[];return this.core.dispatch(Q)}subscribe(Q){return this.subscriberFanout.subscribe(Q)}setHost(Q){this.domEventBridge.setHost(Q)}setInstrumentationHook(Q){this.instrumentationBridge.setHook(Q)}resolveSectionController(Q){if(!this.coordinatorBridge)throw Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(Q)}async dispose(){if(this.disposed)return;if(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge)await this.coordinatorBridge.dispose()}routeOutputs(Q){for(let Y of Q)this.routeOne(Y);this.subscriberFanout.emit(Q)}routeOne(Q){switch(Q.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(Q);break;case"framework-error":this.domEventBridge.dispatch(Q),this.frameworkErrorBridge.dispatch(Q);break;default:{let Y=Q;return}}this.instrumentationBridge.dispatch(Q)}}var X5={mode:"gather",role:"student"};function $1(Q,Y){return Q!==void 0?Q:Y}function Z5(Q){let Y=Q.runtime??{};if(Y.onFrameworkError!==void 0)return Y.onFrameworkError;return Q.onFrameworkError}function j5(Q){let Y=Q.runtime?.tools||{},J=Y.placement||{};return{...Y,placement:{...J}}}function q5(Q){let Y=Q.runtime||{},J=Y.player?{...Y.player}:null;return{...Y,assessmentId:$1(Y.assessmentId,Q.assessmentId),playerType:Y.playerType??"iife",player:J,lazyInit:Y.lazyInit??!0,accessibility:Y.accessibility??null,coordinator:Y.coordinator??null,createSectionController:Y.createSectionController,isolation:Y.isolation??"inherit",env:Y.env??X5,toolConfigStrictness:$1(Y.toolConfigStrictness,Q.toolConfigStrictness)??"error",onFrameworkError:Z5({runtime:Q.runtime,onFrameworkError:Q.onFrameworkError}),onStageChange:$1(Y.onStageChange,Q.onStageChange),onLoadingComplete:$1(Y.onLoadingComplete,Q.onLoadingComplete),tools:Q.effectiveToolsConfig}}function l6(Q,Y){let J=Q.assessmentId??"section-demo-direct",G=j5({runtime:Q.runtime}),X=q5({assessmentId:J,runtime:Q.runtime,effectiveToolsConfig:G,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),j=Y.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:G,effectiveRuntime:X,playerRuntime:j}}function K5(Q,Y){if(Q===Y)return 0;let J=Q.compareDocumentPosition(Y);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class R8{shellsByElement=new Map;register(Q){let Y=this.shellsByElement.get(Q.element),J={...Q,sortKey:Date.now()};if(Y&&Y.kind===J.kind&&Y.itemId===J.itemId&&Y.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Q.element,J),!0}unregister(Q){return this.shellsByElement.delete(Q)}getOrderedShells(Q){let Y=Array.from(this.shellsByElement.values()).filter((J)=>!Q||J.kind===Q);return Y.sort((J,G)=>K5(J.element,G.element)),Y}getCanonicalIdMap(){let Q={};for(let Y of this.getOrderedShells("item")){if(!Y.itemId)continue;Q[Y.itemId]=Y.canonicalItemId||Y.itemId}return Q}clear(){this.shellsByElement.clear()}}function w1(Q="runtime"){return`${Q}-${Math.random().toString(16).slice(2)}-${Date.now()}`}class E8{registry=new R8;runtimeId=w1("section-engine");adapter=null;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;loadedRenderableKeys=new Set;attachHost(Q){if(this.adapter){if(this.adapter.setHost(Q.host),Q.instrumentationHook!==void 0)this.adapter.setInstrumentationHook(Q.instrumentationHook);return}this.adapter=new w8({host:Q.host,runtimeId:this.runtimeId,sourceCe:Q.sourceCe,frameworkErrorBus:Q.frameworkErrorBus,coordinator:Q.coordinator,instrumentationHook:Q.instrumentationHook,now:Q.now})}dispatchInput(Q){return this.adapter?.dispatchInput(Q)??[]}subscribe(Q){return this.adapter?.subscribe(Q)??W5}getState(){return this.adapter?.getState()??T7()}getEffectiveRuntime(Q,Y){return l6(Q,Y).effectiveRuntime}setInstrumentationHook(Q){this.adapter?.setInstrumentationHook(Q)}getRuntimeId(){return this.runtimeId}async initialize(Q){this.activeInitToken+=1;let Y=this.activeInitToken;this.coordinator=Q.coordinator,this.sectionId=Q.sectionId,this.attemptId=Q.attemptId;let J=await Q.coordinator.getOrCreateSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId,input:{section:Q.section,sectionId:Q.sectionId,assessmentId:Q.assessmentId,view:Q.view},updateExisting:!0,createDefaultController:Q.createDefaultController});if(Y!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.replayRegisteredShellsIntoController(J),Q.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.(()=>{Q.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Q){if(!Q.handleContentRegistered)return;let Y=this.registry.getOrderedShells();if(Y.length===0)return;for(let G of Y){let X=G.canonicalItemId||G.itemId;Q.handleContentRegistered({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind})}let J=Date.now();for(let G of Y){let X=G.canonicalItemId||G.itemId,j=this.getLoadedKey(X,G.contentKind);if(this.loadedRenderableKeys.has(j))Q.handleContentLoaded?.({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind,timestamp:J})}}getLoadedKey(Q,Y){return`${Y??""}:${Q}`}register(Q){return this.registry.register(Q)}unregister(Q){return this.registry.unregister(Q)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Q){return this.registry.getCanonicalIdMap()[Q]||this.controller?.getCanonicalItemId?.(Q)||Q}handleContentRegistered(Q){this.controller?.handleContentRegistered?.({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId,contentKind:Q.contentKind||Q.kind})}handleContentUnregistered(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentUnregistered?.({itemId:Q.itemId,canonicalItemId:Y,contentKind:Q.contentKind||Q.kind})}handleContentLoaded(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentLoaded?.(Q)}handleItemPlayerError(Q){this.controller?.handleItemPlayerError?.(Q)}reportSectionError(Q){this.controller?.reportSectionError?.(Q)}updateItemSession(Q,Y){let J=this.getCanonicalItemId(Q);return this.controller?.updateItemSession?.(J,Y)??null}navigateToItem(Q){return this.controller?.navigateToItem?.(Q)??null}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId)await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId});if(this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){let Q=this.adapter;this.adapter=null,await Q.dispose()}}}var W5=()=>{};import{ContextConsumer as U5,createContext as B5}from"@pie-players/pie-context";var d6=B5(Symbol.for("pie.sectionRuntimeEngineHostContext"));function i6(Q,Y){let J=!1,G=new U5(Q,{context:d6,subscribe:!0,onValue:(K)=>{J=!0,Y(K)}});G.connect();let X=(K)=>{if(K.context!==d6)return;G.requestValue()};Q.addEventListener("context-provider",X);let j=0,Z=200,q=globalThis.setInterval(()=>{if(J||j>=Z){globalThis.clearInterval(q);return}j+=1,G.requestValue()},50);return()=>{globalThis.clearInterval(q),Q.removeEventListener("context-provider",X),G.disconnect()}}var D5=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function s6(Q,Y){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(Y);let J=Q.getOnStageChange();if(J)try{J(Y)}catch(G){(Q.logHandlerError??D5)(G)}return!0}function g7(Q,Y){if(typeof Q==="function")return Q;if(Q===null)return null;return typeof Y==="function"?Y:null}function n6(Q={}){let Y=Q.frameDeadlineMs??100,J=!1,G=null,X=null,j=null,Z=null,q=null;function K(){if(J=!1,X!==null)Z?.(X),X=null;if(j!==null)q?.(j),j=null;Z=null,q=null}function B(_){if(!J)return;if(_==="frame")X=null;if(_==="timer")j=null;let A=G;G=null,K(),A?.()}function U(_){if(G=_,J)return;J=!0;let A=globalThis,M=g7(Q.requestFrame,A.requestAnimationFrame);Z=g7(Q.cancelFrame,A.cancelAnimationFrame);let O=g7(Q.setTimer,A.setTimeout);if(q=g7(Q.clearTimer,A.clearTimeout),M){let F=M(()=>B("frame"));if(!J)return;if(X=F,O){let $=O(()=>B("timer"),Y);if(J)j=$}return}let L=g7(Q.queueMicrotaskFn,A.queueMicrotask);if(L){L(()=>B("microtask"));return}if(O){let F=O(()=>B("timer"),0);if(J)j=F;return}B("microtask")}function H(){if(!J)return;G=null,K()}return{schedule:U,cancel:H,isPending:()=>J}}function r6(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function o6(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function a6(Q){let{state:Y,itemId:J,payload:G}=Q;if(H5(G)){let Z=_5(G);if(Y.lastMetadataSignatureByItemId.get(J)===Z)return!1;Y.lastMetadataSignatureByItemId.set(J,Z)}let X=V5(G);if(Y.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Y.lastSessionEventSignatureByItemId.set(J,X),!0}function V5(Q){let Y={...Q};delete Y.timestamp,delete Y.sourceRuntimeId;try{return JSON.stringify(Y)}catch{return String(Y.itemId||"")}}function H5(Q){return Q.intent==="metadata-only"}function _5(Q){try{return JSON.stringify({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,intent:Q.intent,complete:Q.complete??null,component:Q.component??null})}catch{return String(Q.itemId||"")}}var F5=(Q,Y)=>{if(customElements.get(Q))return;try{customElements.define(Q,Y)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Q))throw J}},L5=C8('<div class="pie-assessment-toolkit-error svelte-vpe4u2" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-vpe4u2"> </div> <div class="pie-assessment-toolkit-error-message svelte-vpe4u2"> </div> <pre class="pie-assessment-toolkit-error-details svelte-vpe4u2"> </pre></div>'),$5=C8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),w5={hash:"svelte-vpe4u2",code:`.pie-assessment-toolkit-anchor.svelte-vpe4u2 {display:none;}.pie-assessment-toolkit-error.svelte-vpe4u2 {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-vpe4u2 {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-vpe4u2 {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-vpe4u2 {margin:0;white-space:pre-wrap;word-break:break-word;}`};function D0(Q,Y){Q0(Y,!0),j0(Q,w5);let J=w1("toolkit"),G=new E8,X=h(null),j=new v7,Z={mode:"gather",role:"student"},q={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},K=y(Y,"assessmentId",7,""),B=y(Y,"section",7,null),U=y(Y,"sectionId",7,""),H=y(Y,"attemptId",7,""),_=y(Y,"env",23,()=>({})),A=y(Y,"ndsIcons",7,!1),M=y(Y,"lazyInit",7,!0),O=y(Y,"toolConfigStrictness",7,"error"),L=y(Y,"tools",23,()=>({})),F=y(Y,"toolContextResolvers",7,null),$=y(Y,"enabledTools",7,""),b=y(Y,"toolRegistry",7,null),v=y(Y,"accessibility",23,()=>({})),k=y(Y,"player",7,null),p=y(Y,"playerType",7,""),w=y(Y,"coordinator",7,null),l=y(Y,"createSectionController",7,null),Z7=y(Y,"onFrameworkError",7,null),j7=y(Y,"errorRenderer",7,null),P7=y(Y,"onStageChange",7,null),q7=y(Y,"assessment",7,null),d7=y(Y,"currentItemRef",7,null),i7=y(Y,"pnpEnforcement",7,null),K7=y(Y,"isolation",7,"inherit"),C7=h(null),d=h(null),Y7=h(null),y8=null,y7=null,x7=null,s7=null,f7=null,n7=null,r7=h(0),S1=h(null),o7=h(null),n=h(null),T1=h("Unable to initialize assessment toolkit."),C1=h(b8([])),x8="",y1="",f8=h(""),k8=null,I8=n6(),W7=[],a7=new Map,x1=new WeakMap,v8=r6(),i=N5({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:J,sectionId:u(()=>U()||void 0),attemptId:u(()=>H()||void 0),emit:(W)=>{s6({isSuppressed:()=>V(X)!==null,dispatchDomEvent:(D)=>U7("pie-stage-change",D),getOnStageChange:()=>P7()},W)}}),h8=h(b8(u(()=>`${U()}|${H()}`))),t7=h(!1),a=h(!1),f1=h(!1),k1=h(!1);function V0(){if(!V(C7))return null;let W=V(C7).getRootNode();if(W&&"host"in W)return W.host;return V(C7).parentElement}let x=s(()=>V0());function U7(W,D){if(!V(x)){W7=[...W7,{name:W,detail:D}];return}P8(V(x),W,D)}T(()=>{if(!V(x))return;if(W7.length===0)return;let W=W7;W7=[],queueMicrotask(()=>{let D=V(x);if(!D){W7=[...W,...W7];return}for(let N of W)P8(D,N.name,N.detail)})});function H0(W){if(!j7())return{title:"Unable to initialize assessment toolkit.",details:W.details.length>0?W.details:[W.message]};try{let D=j7()(W)||{};return{title:typeof D.title==="string"&&D.title.trim().length>0?D.title:"Unable to initialize assessment toolkit.",details:Array.isArray(D.details)&&D.details.length>0?D.details.map((N)=>String(N)):W.details.length>0?W.details:[W.message]}}catch(D){let N=D instanceof Error&&D.message.trim().length>0?D.message:String(D||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...W.details,`Error renderer failed: ${N}`]}}}function e7(W){let D=G1({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable});return j.reportFrameworkError(D),D}function _0(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function m8(W){if(!Z7())return;try{Z7()(W),x8=`${W.kind}|${W.source}|${W.message}`}catch(D){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,D)}}T(()=>{let W=j.subscribeFrameworkErrors((D)=>{if(console.error(o8(D),D.cause),_0(D.kind)){let N=H0(D);R(n,D,!0),R(T1,N.title,!0),R(C1,N.details,!0)}U7("framework-error",D),m8(D)});return()=>{W()}}),T(()=>{if(!V(n))return;let W=`${V(n).kind}|${V(n).source}|${V(n).message}`;if(x8===W)return;m8(V(n))});function F0(W){let D=5381;for(let N=0;N<W.length;N+=1)D=(D<<5)+D^W.charCodeAt(N);return(D>>>0).toString(36)}function B7(W){return W&&typeof W==="object"?W:{}}function A0(W){let D=B7(W.section),N=typeof D.identifier==="string"?D.identifier:"",P=typeof W.sectionId==="string"?W.sectionId:"";return N||P}function M0(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function N0(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((N,P)=>{let z=B7(N),I=B7(z.entity),r=typeof I.id==="string"&&I.id||`renderable-${P}`,J1=B7(I.config),m1=typeof I.version==="string"&&I.version||(typeof I.version==="number"?String(I.version):"")||(typeof J1.version==="string"?J1.version:"");return{id:r,version:m1}})}function z0(W){let D=B7(W.itemSessionsByItemId);return Object.keys(D).sort((N,P)=>N.localeCompare(P)).map((N)=>{let P=B7(D[N]),z=typeof P.id==="string"?P.id:"",I=Array.isArray(P.data)?P.data:[],r="";try{r=F0(JSON.stringify(I))}catch{r=String(I.length)}return{itemId:N,sessionId:z,payloadSignature:r}})}function O0(W){let D=B7(W),N=N0(D).map((z)=>`${z.id}:${z.version}`).join("|"),P=z0(D).map((z)=>`${z.itemId}:${z.sessionId}:${z.payloadSignature}`).join("|");return{sectionId:A0(D),currentItemIndex:M0(D),renderableSignature:N,itemSessionSignature:P}}function P0(W){let D=O0(W);return`${D.sectionId}|${D.currentItemIndex}|${D.renderableSignature}|${D.itemSessionSignature}`}function u8(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function L0(W,D){let N=W?.type,P=u8(N)?N:u8(D)?D:W?.tagName?"custom":"iife",z=W?.tagName?.trim();if(P==="custom"&&!z)return{type:"iife",tagName:q.iife,version:void 0,source:void 0,isDefault:!0};return{type:P,tagName:z||q[P],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!D}}function p8(W){let D=W||{},N=typeof D.mode==="string"&&D.mode.trim()?D.mode.trim():Z.mode,P=typeof D.role==="string"&&D.role.trim()?D.role.trim():Z.role;return{mode:N,role:P}}function $0(W){let D=p8(W);if(D.mode==="author")return"author";if(D.role==="instructor")return"scorer";return"candidate"}async function w0(){if(l())return l()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function g8(){let W=L()||{},D=B0($());if(D.length===0)return W;let N=W.placement||{},P=Array.isArray(N.section)?N.section:null;if(P&&P.length>0)return W;return{...W,placement:{...N,section:D}}}function R0(){return G7(g8(),{strictness:O(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:b()}).config}function E0(){let W="",D="";try{W=JSON.stringify(g8())}catch{W="[unserializable-tools]"}try{D=JSON.stringify(Object.entries(F()??{}).map(([N,P])=>[N,typeof P]))}catch{D="[unserializable-resolvers]"}return[K()||"",String(O()||"error"),W,D].join("|")}function c8(W){return W==="on"||W==="off"?W:null}function b0(W,D){let N=c8(W);if(N)return N;if(D&&typeof D==="object"){let z=D.pnpEnforcement;return c8(typeof z==="string"?z:null)}return null}function S0(W){let D=K()||B()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new P1({assessmentId:D,lazyInit:M(),toolConfigStrictness:O(),deferToolConfigValidation:!0,tools:W,toolRegistry:b(),toolContextResolvers:F(),accessibility:v(),frameworkErrorBus:j})}let f=s(()=>{if(K7()!=="force"&&V(Y7)?.coordinator)return V(Y7).coordinator;return w()||V(d)});T(()=>{V(x),w(),K7(),V(Y7),F(),u(()=>{if(!V(x))return;if(w()){if(V(d))R(d,null);y7=null;return}if(K7()!=="force"&&V(Y7)?.coordinator){if(V(d))R(d,null);y7=null;return}if(V(d)&&y7!==F()){try{V(d).setToolContextResolvers(F()),y7=F()}catch(W){R(o7,W,!0),e7({kind:"coordinator-init",phase:"coordinator-ready",error:W})}return}if(!V(d)){let W=E0();if(y1===W)return;try{let D=R0();R(d,S0(D),!0),y7=F(),y1="",R(n,null),R(T1,"Unable to initialize assessment toolkit."),R(C1,[],!0)}catch(D){R(o7,D,!0),R(d,null),y1=W,e7({kind:"coordinator-init",source:"pie-assessment-toolkit",error:D})}}})});let J7=s(()=>K()||V(f)?.assessmentId||""),t=s(()=>U()||B()?.identifier||`section-${V(J7)||"default"}`),I1=s(()=>p8(_())),T0=s(()=>$0(V(I1))),L7=s(()=>L0(k(),p())),k7=s(()=>z5({player:V(L7),component:"pie-assessment-toolkit"})),Q1=s(()=>{if(!V(f))return null;let W=V(f).getServiceBundle();return{toolkitCoordinator:V(f),toolCoordinator:V(f).toolCoordinator,ttsService:W.ttsService,highlightCoordinator:W.highlightCoordinator,catalogResolver:W.catalogResolver,elementToolStateStore:W.elementToolStateStore,assessmentId:V(J7),sectionId:V(t),itemPlayer:V(L7),ndsIcons:A()===!0,reportSessionChanged:(D,N)=>{let P=G.updateItemSession(D,N);i8({itemId:D,result:P,fallbackSession:N})}}}),Y1=s(()=>{if(!V(f))return null;return{runtimeId:J,coordinator:V(f)}});function C0(W){let D=P0(W);if(D===V(f8))return;R(f8,D,!0),R(r7,V(r7)+1),R(S1,W,!0),U7("composition-changed",{composition:V(S1),version:V(r7)})}function v1(W){k8=W??G.getCompositionModel(),I8.schedule(()=>{C0(k8)})}function h1(W){if(!W)return;let D=x1.get(W);if(!D)return;for(let N of D)N();x1.delete(W)}function l8(){for(let W of a7.values())h1(W.element)}function d8(W){if(h1(W.element),!V(f))return;let D=V(f).getServiceBundle().catalogResolver;x1.set(W.element,[D.registerOwner({owner:{kind:W.kind,itemId:W.itemId,canonicalItemId:W.canonicalItemId,assessmentId:V(J7),sectionId:V(t)},entity:W.item})])}function y0(){l8();for(let W of a7.values())d8(W)}function i8(W){let N={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:J};if(!a6({state:v8,itemId:W.itemId,payload:N}))return;U7("session-changed",N)}function x0(W){if(!(W instanceof HTMLElement))return!1;return A5(W,T8)?.runtimeId===J}function I7(W){return W.detail??null}function f0(W,D){for(let N of D)W.addEventListener(N.name,N.handler);return()=>{for(let N of D)W.removeEventListener(N.name,N.handler)}}T(()=>{if(!V(x))return;if(K7()==="force"){R(Y7,null);return}return U0(V(x),(W)=>{if(W.runtimeId===J)return;R(Y7,W,!0)})}),T(()=>{let W=V(x);return u(()=>{if(!W){R(X,null);return}let D=i6(W,(N)=>{if(N.engine===V(X))return;R(X,N.engine,!0)});return()=>{D(),R(X,null)}})}),T(()=>{let W=K7()!=="force"&&V(Y7)?V(Y7).runtimeId:null,D=W?"inherited":"owned";if(D!==y8)y8=D,U7(D==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:J,parentRuntimeId:W})}),T(()=>{let W=V(t),D=H()||"";o6(v8)}),T(()=>{if(!V(x)||!V(Y1))return;return f7=new t6(V(x),{context:T8,initialValue:V(Y1)}),f7.connect(),n7=new e6(V(x)),n7.attach(),()=>{n7?.detach(),n7=null,f7?.disconnect(),f7=null}}),T(()=>{if(!V(Y1))return;f7?.setValue(V(Y1))}),T(()=>{if(!V(x))return;V(x).setAttribute("data-item-player-type",V(L7).type),V(x).setAttribute("data-item-player-tag",V(L7).tagName),V(x).setAttribute("data-env-mode",String(V(I1)?.mode||"")),V(x).setAttribute("data-env-role",String(V(I1)?.role||""))}),T(()=>{if(!V(x)||!V(Q1))return;return x7=new t6(V(x),{context:W0,initialValue:V(Q1)}),x7.connect(),s7=new e6(V(x)),s7.attach(),()=>{s7?.detach(),s7=null,x7?.disconnect(),x7=null}}),T(()=>{if(V(Q1))x7?.setValue(V(Q1))}),T(()=>{return V(f),V(J7),V(t),y0(),()=>{l8()}}),T(()=>{if(!V(x))return;return M5({host:V(x),instrumentationProvider:V(k7),component:"pie-assessment-toolkit",eventMap:O5,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0}})}),T(()=>{q7(),d7(),i7(),L();let W=V(f);if(!W)return;if(W!==V(d))return;u(()=>{W.setPnpEnforcement(b0(i7(),L())),W.updateAssessment(q7()),W.updateCurrentItemRef(d7())})}),T(()=>{if(!V(f))return;return V(f).subscribeTelemetry(({eventName:W,payload:D})=>{if(!P5(V(k7)))return;if(!V(k7).isReady())return;let N=W,P=new Date().toISOString(),z={...D||{},instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:P};V(k7).trackEvent(N,z);let I=D&&typeof D.errorType==="string"?D.errorType:void 0;if(!W.endsWith("-error")&&!I)return;let r=D&&typeof D.message==="string"?D.message:`Toolkit telemetry error: ${W}`;V(k7).trackError(Error(r),{component:"pie-assessment-toolkit",errorType:I||"ToolkitTelemetryError",...z})})}),T(()=>{if(!B()||!V(f))return;let W=!1;return G.initialize({coordinator:V(f),section:B(),sectionId:V(t),assessmentId:V(J7),attemptId:H()||void 0,view:V(T0),createDefaultController:w0,onCompositionChanged:(D)=>{if(W)return;v1(D)}}).then(()=>{if(W)return;U7("toolkit-ready",{runtimeId:J,assessmentId:V(J7),sectionId:V(t),itemPlayer:V(L7),coordinator:V(f)}),U7("section-ready",{sectionId:V(t)}),u(()=>{R(k1,!0)})}).catch((D)=>{u(()=>{if(!V(a))R(a,!0),i.enter("engine-ready","skipped");i.enter("interactive","failed")}),R(o7,D,!0),G.reportSectionError({source:"section-runtime",error:D,timestamp:Date.now()}),e7({kind:"runtime-init",source:"pie-assessment-toolkit",error:D})}),()=>{W=!0}}),T(()=>{if(!V(x))return;let W=V(x),D=(P)=>x0(P.target);return f0(W,[{name:C6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.element||!z?.itemId)return;let I=G.register(z);if(a7.set(z.element,z),d8(z),G.handleContentRegistered(z),I)v1()}},{name:y6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;let I=z?.element?G.unregister(z.element):!1;if(h1(z.element),z.element)a7.delete(z.element);if(G.handleContentUnregistered(z),I)v1()}},{name:x6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;let I=G.updateItemSession(z.itemId,z.session);i8({itemId:z.itemId,canonicalItemId:G.getCanonicalItemId(z.itemId),result:I,fallbackSession:z.session})}},{name:f6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;G.handleContentLoaded({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,detail:z.detail,timestamp:Date.now()})}},{name:k6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;G.handleItemPlayerError({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,error:z.error,timestamp:Date.now()})}}])});async function k0(){if(!V(f))throw Error("Coordinator not initialized");await V(f).waitUntilReady()}function I0(){if(!V(f))throw Error("Coordinator not initialized");return V(f).getServiceBundle()}function v0(W){if(!V(f))throw Error("Coordinator not initialized");V(f).setHooks(W)}function h0(W){return G.navigateToItem(W)}function m0(){return G.getCompositionModel()}function u0(){return V(L7)}async function p0(){await G.persist()}async function g0(){await G.hydrate()}T(()=>{return()=>{u(()=>{if(i.getCurrent()!==null)i.enter("disposed")})}}),T(()=>{let W=`${U()}|${H()}`;u(()=>{if(W===V(h8))return;if(i.getCurrent()!==null)i.enter("disposed");i.reset({sectionId:U()||void 0,attemptId:H()||void 0}),R(h8,W),R(t7,!1),R(a,!1),R(f1,!1),R(k1,!1)})}),T(()=>{let W=V(a)&&V(k1);u(()=>{if(!W)return;if(V(f1))return;R(f1,!0),i.enter("interactive")})}),T(()=>{let W=V(r7)>0||V(S1)!==null;u(()=>{if(!V(t7)&&W)R(t7,!0),i.enter("composed")})}),T(()=>{if(!V(f))return;if(!V(t7))return;if(V(a))return;let W=V(f),D=!1;return W.waitUntilReady().then(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready")})}).catch(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready","failed")})}),()=>{D=!0}}),T(()=>{return()=>{I8.cancel(),G.dispose().catch((W)=>{R(o7,W,!0),e7({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).finally(()=>{j.dispose()})}});var c0={waitUntilReady:k0,getServiceBundle:I0,setHooks:v0,navigateToItem:h0,getCompositionModel:m0,getItemPlayerConfig:u0,persist:p0,hydrate:g0,get assessmentId(){return K()},set assessmentId(W){K(W),C()},get section(){return B()},set section(W){B(W),C()},get sectionId(){return U()},set sectionId(W){U(W),C()},get attemptId(){return H()},set attemptId(W){H(W),C()},get env(){return _()},set env(W){_(W),C()},get ndsIcons(){return A()},set ndsIcons(W){A(W),C()},get lazyInit(){return M()},set lazyInit(W){M(W),C()},get toolConfigStrictness(){return O()},set toolConfigStrictness(W){O(W),C()},get tools(){return L()},set tools(W){L(W),C()},get toolContextResolvers(){return F()},set toolContextResolvers(W){F(W),C()},get enabledTools(){return $()},set enabledTools(W){$(W),C()},get toolRegistry(){return b()},set toolRegistry(W){b(W),C()},get accessibility(){return v()},set accessibility(W){v(W),C()},get player(){return k()},set player(W){k(W),C()},get playerType(){return p()},set playerType(W){p(W),C()},get coordinator(){return w()},set coordinator(W){w(W),C()},get createSectionController(){return l()},set createSectionController(W){l(W),C()},get onFrameworkError(){return Z7()},set onFrameworkError(W){Z7(W),C()},get errorRenderer(){return j7()},set errorRenderer(W){j7(W),C()},get onStageChange(){return P7()},set onStageChange(W){P7(W),C()},get assessment(){return q7()},set assessment(W){q7(W),C()},get currentItemRef(){return d7()},set currentItemRef(W){d7(W),C()},get pnpEnforcement(){return i7()},set pnpEnforcement(W){i7(W),C()},get isolation(){return K7()},set isolation(W){K7(W),C()}},s8=$5(),n8=S8(s8);q0(n8,(W)=>R(C7,W),()=>V(C7));var l0=R1(n8,2);{var d0=(W)=>{var D=L5(),N=l7(D),P=l7(N,!0);c7(N);var z=R1(N,2),I=l7(z,!0);c7(z);var r=R1(z,2),J1=l7(r,!0);c7(r),c7(D),J0((m1)=>{b1(P,V(T1)),b1(I,V(n).message),b1(J1,m1)},[()=>V(C1).join(`
|
|
225
|
-
`)]),
|
|
222
|
+
`;for(let j of X)J+=`- ${j.rule}: ${j.reason}
|
|
223
|
+
`}return J}function R8(Q){let{request:G,tools:Y,pnpPolicy:J,customSources:X,contextId:j}=Q,Z=new z1(j);Z.addSource("host",{id:G.scope.scopeId,name:`${G.level}:${G.scope.scopeId}`,config:{placement:Y.placement,policy:Y.policy}});let K=L7(Y.placement[G.level]),W=L7(Y.policy.allowed),B=new Set(L7(Y.policy.blocked)),U=[];for(let F of K)U.push(F),Z.addDecision({precedence:0,rule:"placement-membership",featureId:F,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${G.level}`});if(U=U.filter((F)=>{if(Y.providers?.[F]?.enabled===!1)return Z.addDecision({precedence:0,rule:"provider-disabled",featureId:F,action:"block",sourceType:"host",reason:`tools.providers.${F}.enabled === false`,value:!1}),!1;return!0}),W.length>0){let F=new Set(W);U=U.filter((L)=>{if(!F.has(L))return Z.addDecision({precedence:0,rule:"host-allowlist",featureId:L,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:W}),!1;return!0})}U=U.filter((F)=>{if(B.has(F))return Z.addDecision({precedence:0,rule:"host-blocked",featureId:F,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:Y.policy.blocked}),!1;return!0});let V=[],H=new Map;for(let F of U)H.set(F,["placement"]);let N=new Set(U),O=null;if(J.enforcement==="on"&&J.source&&(J.assessment||J.currentItemRef)){if(O=J.source.apply({assessment:J.assessment,currentItemRef:J.currentItemRef}),O.sources.assessment)Z.addSource("assessment",O.sources.assessment);if(O.sources.student)Z.addSource("student",O.sources.student);if(O.sources.item)Z.addSource("item",O.sources.item);for(let F of O.decisions)Z.addDecision({precedence:F.precedence,rule:F.rule,featureId:F.featureId,action:F.action,sourceType:F.sourceType,reason:F.reason,value:F.value});U=U.filter((F)=>{return!O.blockedToolIds.has(F)});for(let F of Array.from(H.keys()))if(O.blockedToolIds.has(F))H.delete(F);for(let F of O.mandatedToolIds){if(!!N.has(F))continue;let v=O.perToolFlags.get(F)?.rule??"required-tool",I=V9(F,{placement:K,allowed:W,blocked:B,providers:Y.providers}),p={rule:v,hostRule:I.hostRule,hostValue:I.hostValue};V.push({code:"tool-policy.requiredToolBlocked",level:G.level,toolId:F,message:`Profile policy mandates "${F}" (${v}) but host policy removed it from level "${G.level}" via ${I.hostRule}.`,details:p}),Z.addDecision({precedence:0,rule:"required-tool-blocked",featureId:F,action:"advisory",sourceType:"host",reason:`Host removed required tool "${F}" via ${I.hostRule}`,value:p})}for(let F of U){let L=O.perToolFlags.get(F);if(L){let C=H.get(F)??[];C.push(`pnp.${L.rule}`),H.set(F,C)}}}for(let F=0;F<X.length;F++){let L=X[F],C=U.slice(),v=L.refine({request:G,candidates:C}),I=new Set(v.refinedCandidates);for(let E of v.refinedCandidates)if(!C.includes(E))V.push({code:"tool-policy.placementMissing",level:G.level,toolId:E,message:`Custom source "${L.id}" tried to add tool "${E}" that was not in candidates; ignored.`,source:`custom.${L.id}`}),I.delete(E);U=C.filter((E)=>I.has(E));let p=new Set;if(v.decisions){for(let E of v.decisions)if(Z.addDecision({precedence:E.precedence??100+F,rule:E.rule,featureId:E.featureId,action:E.action,sourceType:E.sourceType,reason:E.reason,value:E.value}),E.action==="block")p.add(E.featureId)}for(let E of C){if(I.has(E))continue;if(p.has(E))continue;Z.addDecision({precedence:100+F,rule:"custom-source",featureId:E,action:"block",sourceType:"custom",reason:`Custom policy source "${L.id}" removed tool "${E}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:L.id}})}for(let E of U){let g=H.get(E)??["placement"];g.push(`custom.${L.id}`),H.set(E,g)}for(let E of C)if(!I.has(E))H.delete(E)}let P=new Set(U),$=U.map((F)=>{let L=O?.perToolFlags.get(F);return{toolId:F,required:L?.required??!1,alwaysAvailable:L?.alwaysAvailable??!1,settings:L?.settings,sources:H.get(F)??["placement"]}});return Z.reconcileFinalStates(P),{visibleTools:$,diagnostics:V,provenance:Z.build()}}function V9(Q,G){if(!G.placement.includes(Q))return{hostRule:"placement-missing",hostValue:G.placement};if(G.providers?.[Q]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(G.allowed.length>0&&!G.allowed.includes(Q))return{hostRule:"host-allowlist",hostValue:G.allowed};if(G.blocked.has(Q))return{hostRule:"host-blocked",hostValue:Array.from(G.blocked)};return{hostRule:"placement-missing",hostValue:G.placement}}function v0(Q){if(!Q)return!1;let G=Q.personalNeedsProfile;if(G){if(Array.isArray(G.supports)&&G.supports.length>0)return!0;if(Array.isArray(G.prohibitedSupports)&&G.prohibitedSupports.length>0)return!0;if(Array.isArray(G.activateAtInit)&&G.activateAtInit.length>0)return!0}let Y=Q.settings;if(Y){let J=Y.districtPolicy;if(J){if(Array.isArray(J.blockedTools)&&J.blockedTools.length>0)return!0;if(Array.isArray(J.requiredTools)&&J.requiredTools.length>0)return!0;if(J.policies&&typeof J.policies==="object"&&Object.keys(J.policies).length>0)return!0}let X=Y.testAdministration;if(X&&typeof X==="object")for(let j of Object.keys(X)){let Z=X[j];if(Z===void 0||Z===null)continue;if(Array.isArray(Z)&&Z.length===0)continue;if(typeof Z==="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0)continue;return!0}}return!1}function h0(Q){let G=Q?.settings;if(!G)return!1;if(Array.isArray(G.requiredTools)&&G.requiredTools.length>0)return!0;if(Array.isArray(G.restrictedTools)&&G.restrictedTools.length>0)return!0;if(G.toolParameters&&typeof G.toolParameters==="object"&&Object.keys(G.toolParameters).length>0)return!0;return!1}function g7(Q){if(v0(Q.assessment))return"on";if(h0(Q.currentItemRef))return"on";return"off"}class P1{id="pnp";toolRegistry;constructor(Q){this.toolRegistry=Q}apply(Q){let{ctx:G,result:Y}=this.prepare(Q),{pnp:J,districtPolicy:X,itemSettings:j}=G,Z=new Set;J?.supports?.forEach((K)=>Z.add(K)),J?.prohibitedSupports?.forEach((K)=>Z.add(K)),X?.blockedTools?.forEach((K)=>Z.add(K)),X?.requiredTools?.forEach((K)=>Z.add(K)),j?.requiredTools?.forEach((K)=>Z.add(K)),j?.restrictedTools?.forEach((K)=>Z.add(K));for(let K of Z)this.resolveSupport(K,G,Y);return Y}resolveFeature(Q,G){let{ctx:Y,result:J}=this.prepare(G);return this.resolveSupport(Q,Y,J),J}prepare(Q){let{assessment:G,currentItemRef:Y}=Q,J=G?.personalNeedsProfile,X=G?.settings,j=Y?.settings,Z={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)Z.sources.assessment={id:G?.id||"unknown",name:G?.name||G?.id||"Assessment",config:X};if(J)Z.sources.student={id:"student",name:"Student PNP Profile",config:J};if(Y&&j)Z.sources.item={id:Y.identifier,name:Y.identifier,config:j};return{ctx:{pnp:J,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:j,toolConfigs:X?.toolConfigs},result:Z}}resolveSupport(Q,G,Y){if(G.districtPolicy?.blockedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.blockedToolIds.add(X),Y.decisions.push({precedence:1,rule:"district-block",featureId:X,action:"block",sourceType:"assessment",reason:`District policy blocks "${Q}" for all assessments`,value:G.districtPolicy.blockedTools});return}if(G.testAdmin?.toolOverrides?.[Q]===!1){let X=this.mapSupportToToolId(Q);Y.blockedToolIds.add(X),Y.decisions.push({precedence:2,rule:"test-admin-override",featureId:X,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Q}" for this session`,value:G.testAdmin.toolOverrides});return}if(G.itemSettings?.restrictedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.blockedToolIds.add(X),Y.decisions.push({precedence:3,rule:"item-restriction",featureId:X,action:"block",sourceType:"item",reason:`Item restricts "${Q}" (e.g., mental math question blocks calculator)`,value:G.itemSettings.restrictedTools});return}if(G.itemSettings?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.mandatedToolIds.add(X),Y.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,G),rule:"item-requirement",sourceType:"item"}),Y.decisions.push({precedence:4,rule:"item-requirement",featureId:X,action:"enable",sourceType:"item",reason:`Item requires "${Q}" for this question`,value:G.itemSettings.requiredTools});return}if(G.districtPolicy?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.mandatedToolIds.add(X),Y.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,G),rule:"district-requirement",sourceType:"assessment"}),Y.decisions.push({precedence:5,rule:"district-requirement",featureId:X,action:"enable",sourceType:"assessment",reason:`District policy requires "${Q}" for all assessments`,value:G.districtPolicy.requiredTools});return}if(G.pnp?.prohibitedSupports?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.blockedToolIds.add(X),Y.decisions.push({precedence:6,rule:"pnp-prohibited",featureId:X,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Q}"`,value:G.pnp.prohibitedSupports});return}if(G.pnp?.supports?.includes(Q)){let X=this.mapSupportToToolId(Q);Y.perToolFlags.set(X,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(Q,G),rule:"pnp-support",sourceType:"student"}),Y.decisions.push({precedence:6,rule:"pnp-support",featureId:X,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Q}"`,value:G.pnp.supports});return}let J=this.mapSupportToToolId(Q);Y.decisions.push({precedence:6,rule:"pnp-support",featureId:J,action:"skip",sourceType:"system",reason:`Feature "${Q}" not configured at any level`,value:{supportId:Q}})}mapSupportToToolId(Q){let G=this.toolRegistry.getToolsByPNPSupport(Q);if(G.size===0)return Q;return Array.from(G)[0]}resolveToolSettings(Q,G){return G.itemSettings?.toolParameters?.[Q]??G.toolConfigs?.[Q]}}var m0=R7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class L1{toolRegistry;contextId;pnpPolicySource;customSources;listeners=new Set;tools;assessment;currentItemRef;pnpEnforcement;disposed=!1;constructor(Q){this.toolRegistry=Q.toolRegistry,this.contextId=Q.contextId??"tool-policy",this.pnpPolicySource=new P1(this.toolRegistry),this.customSources=Q.customSources?[...Q.customSources]:[];let G=Q.inputs??{};this.tools=G.tools??m0,this.assessment=G.assessment??null,this.currentItemRef=G.currentItemRef??null,this.pnpEnforcement=G.pnpEnforcement??g7({assessment:this.assessment,currentItemRef:this.currentItemRef})}decide(Q){this.assertNotDisposed();let G=Q.scope.scopeId?`${this.contextId}:${Q.level}:${Q.scope.scopeId}`:`${this.contextId}:${Q.level}`;return R8({request:Q,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0,enforcement:this.pnpEnforcement},customSources:this.customSources,contextId:G})}decideFeature(Q){this.assertNotDisposed();let G=this.hostFeatureGate(Q);if(G)return G;return I0(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}),{assessmentBound:this.assessment!==null})}hostFeatureGate(Q){let G={assessmentBound:this.assessment!==null},Y=L7(this.tools.policy.blocked);if(Y.includes(Q))return w8(Q,"host-blocked",Y,G);let J=L7(this.tools.policy.allowed);if(J.length>0&&!J.includes(Q))return w8(Q,"host-allowlist",J,G);return null}getVisibleToolIds(Q,G){return this.decide({level:Q,scope:{level:Q,scopeId:G}}).visibleTools.map((Y)=>Y.toolId)}updateInputs(Q){this.assertNotDisposed();let G=!1,Y=!1;if("tools"in Q){let J=Q.tools??m0;if(!Object.is(this.tools,J))this.tools=J,G=!0}if("assessment"in Q){let J=Q.assessment??null;if(!Object.is(this.assessment,J))this.assessment=J,G=!0}if("currentItemRef"in Q){let J=Q.currentItemRef??null;if(!Object.is(this.currentItemRef,J))this.currentItemRef=J,G=!0}if("pnpEnforcement"in Q&&Q.pnpEnforcement){if(this.pnpEnforcement!==Q.pnpEnforcement)this.pnpEnforcement=Q.pnpEnforcement,Y=!0}if(G||Y)this.emit({reason:Y&&!G?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Q){return this.assertNotDisposed(),this.customSources.push(Q),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let G=this.customSources.indexOf(Q);if(G!==-1){if(this.customSources.splice(G,1),!this.disposed)this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}}onPolicyChange(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,currentItemRef:this.currentItemRef,pnpEnforcement:this.pnpEnforcement})}emit(Q){for(let G of Array.from(this.listeners))try{G(Q)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}var H9=Symbol("@pie-players/tool-policy-engine");var $1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),F9=(Q,G,Y)=>{let J={...G,...Y};if(Q==="textToSpeech"&&$1(G.settings)&&$1(Y.settings)){if(J.settings={...G.settings,...Y.settings},$1(G.settings.mathSpeech)&&$1(Y.settings.mathSpeech))J.settings.mathSpeech={...G.settings.mathSpeech,...Y.settings.mathSpeech}}return J},A9=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],N9=["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 w1{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;ttsInitialized=!1;ttsInitPromise;ttsReconfigurePromise;stateLoaded=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;toolRegistry;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;toolRequests=new $8;sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitPromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;policyEngine;pnpEnforcementOverride=null;boundAssessment=null;boundCurrentItemRef=null;reportedUnboundFeaturePolicy=!1;static resolveConfig(Q){let G=l1(Q.toolConfigStrictness),Y=Q.toolRegistry??new E8,J=Q.deferToolConfigValidation===!0?R7(Q.tools):X7(Q.tools,{strictness:G,source:"ToolkitCoordinator.init",toolRegistry:Y}).config;return{...Q,toolConfigStrictness:G,toolRegistry:Y,tools:{...J,providers:{...{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}},...J.providers}},accessibility:{language:"en-US",...Q.accessibility??{},catalogs:Q.accessibility?.catalogs??[]}}}constructor(Q){if(!Q.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");let G=w1.resolveConfig(Q);if(this.assessmentId=G.assessmentId,this.config=G,this.toolRegistry=G.toolRegistry??new E8,this.installToolContextResolvers(G.toolContextResolvers),this.hooks=G.hooks??{},this.lazyInit=Q.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=Q.frameworkErrorBus??new m7,this.ownsFrameworkErrorBus=!Q.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new Y8,this.highlightCoordinator=new u7,this.elementToolStateStore=new Q8,this.catalogResolver=new e1(G.accessibility?.catalogs||[],G.accessibility?.language||"en-US"),this.toolProviderRegistry=new O1,this._registerToolProviders(),this.ttsService=new p7,this.setupStatePersistenceHooks(),this.policyEngine=new L1({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,currentItemRef:null,pnpEnforcement:this.resolveEffectivePnpEnforcement()}}),!this.lazyInit)this.waitUntilReady().catch((Y)=>{console.error("[ToolkitCoordinator] Failed eager initialization:",Y),this.handleError(Y,{phase:"coordinator-ready"})})}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorBus.subscribeFrameworkErrors((Q)=>{let G=this.hooks.onFrameworkError;if(!G)return;try{G(Q)}catch(Y){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",Y)}})}async emitTelemetry(Q,G){try{await this.hooks.onTelemetry?.(Q,G)}catch(J){console.warn("[ToolkitCoordinator] telemetry hook failed:",J)}let Y=G?{...G}:void 0;for(let J of this.telemetryListeners)try{J({eventName:Q,payload:Y?{...Y}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Q){for(let G of this.sectionControllerLifecycleListeners)try{G(Q)}catch(Y){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",Y)}}handleError(Q,G){let Y=G6({error:Q,context:G});this.frameworkErrorBus.reportFrameworkError(Y)}subscribeFrameworkErrors(Q){return this.frameworkErrorBus.subscribeFrameworkErrors(Q)}reportFrameworkError(Q){this.frameworkErrorBus.reportFrameworkError(Q)}getSectionControllerMapKey(Q){return`${Q.assessmentId}::${Q.sectionId}::${Q.attemptId||""}`}createDefaultSectionPersistence(){let Q=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),G=(Y)=>{let{assessmentId:J,sectionId:X,attemptId:j}=Y.key;return`pie:section-controller:v1:${J}:${X}:${j||"default"}`};return{async loadSession(Y){if(!Q)return null;let J=Q.getItem(G(Y));if(!J)return null;try{return JSON.parse(J)}catch{return null}},async saveSession(Y,J){if(!Q)return;Q.setItem(G(Y),JSON.stringify(J))},async clearSession(Y){if(!Q)return;Q.removeItem(G(Y))}}}async resolveSectionPersistence(Q){let G=this.getSectionControllerMapKey(Q.key),Y=this.sectionPersistenceStrategies.get(G);if(Y)return Y;let J={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Q,J)??await J.createDefaultPersistence();return this.sectionPersistenceStrategies.set(G,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Q)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Q)).catch((G)=>{this.handleError(G,{phase:"state-save"})})})}async ensureStateLoaded(){if(this.stateLoaded)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Q=this.hooks.loadToolState;if(!Q)return;try{let G=await Q();if(G&&typeof G==="object")this.elementToolStateStore.loadState(G);this.stateLoaded=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(G)})}catch(G){this.handleError(G,{phase:"state-load"})}})().finally(()=>{this.stateLoadPromise=void 0}),this.stateLoadPromise}_registerToolProviders(){let Q=this.getProviderDescriptorTools();for(let G of Q)this.registerProviderFromTool(G)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Q)=>!!Q.provider)}async registerProviderFromTool(Q){let G=Q.provider;if(!G)return;let Y=this.getToolConfig(Q.toolId)||void 0;if(Y?.enabled===!1)return;let J=G.getProviderId?.(Y)??Y?.provider?.id??Q.toolId;if(this.toolProviderRegistry.has(J))return;let X=G.createProvider(Y),j=G.getInitConfig?.(Y)??Y?.provider?.init??{},Z=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:J,initConfig:j}),K=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:J}),W=G.getAuthFetcher?.(Y)??Y?.provider?.runtime?.authFetcher;await this.registerProvider(J,{provider:X,config:Z,lazy:G.lazy??!0,authFetcher:W,onTelemetry:K})}createToolTelemetryForwarder(Q){return async(G,Y)=>{await this.emitTelemetry(G,{...Y||{},toolId:Q.toolId,providerId:Q.providerId})}}addToolTelemetryReporter(Q){let G=Q.initConfig&&typeof Q.initConfig==="object"?{...Q.initConfig}:{},Y=typeof G.onTelemetry==="function"?G.onTelemetry:null,J=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:Q.providerId});return G.onTelemetry=async(X,j)=>{if(Y)await Y(X,j);await J(X,j)},G}async registerProvider(Q,G){try{this.toolProviderRegistry.register(Q,G);let Y={providerId:Q,providerName:G.provider.providerName};await this.hooks.onProviderRegistered?.(Q,Y),await this.emitTelemetry("pie-toolkit-provider-registered",{providerId:Q,providerName:G.provider.providerName})}catch(Y){console.warn(`[ToolkitCoordinator] Failed to register provider "${Q}":`,Y),this.handleError(Y,{phase:"provider-register",providerId:Q})}}async ensureProviderReady(Q){let G=this.providerInitPromises.get(Q);if(G)return G;let Y=(async()=>{let J=await this.toolProviderRegistry.getProvider(Q,!1),X={providerId:Q,providerName:J.providerName};try{return await this.hooks.onProviderInitStart?.(Q,X),await this.toolProviderRegistry.initialize(Q),await this.hooks.onProviderReady?.(Q,X),await this.emitTelemetry("pie-toolkit-provider-ready",{providerId:Q}),J}catch(j){let Z=j instanceof Error?j:Error(String(j));throw this.handleError(Z,{phase:"provider-init",providerId:Q}),Z}})().finally(()=>{this.providerInitPromises.delete(Q)});return this.providerInitPromises.set(Q,Y),Y}setHooks(Q){if(Object.assign(this.hooks,Q),this.setupStatePersistenceHooks(),Q.onCoordinatorReady&&this.isReady())Promise.resolve(Q.onCoordinatorReady(this)).catch((G)=>{this.handleError(G,{phase:"coordinator-ready"})})}subscribeTelemetry(Q){return this.telemetryListeners.add(Q),()=>{this.telemetryListeners.delete(Q)}}getSectionController(Q){let G={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(G))}subscribeSectionEvents(Q){if(this.activeCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let G=this.activeSubscriptions.get(Q.listener);if(G)G.unsubscribeCurrent?.(),G.unsubscribeCurrent=null;let Y={listener:Q.listener,eventTypes:Q.eventTypes,itemIds:Q.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Q.listener,Y);let J=this.sectionControllers.get(this.activeCohortMapKey);if(J)this.bindSubscriptionToController(Y,J);let X=!1;return()=>{if(X)return;if(X=!0,Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null,this.activeSubscriptions.get(Q.listener)===Y)this.activeSubscriptions.delete(Q.listener)}}bindSubscriptionToController(Q,G){Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let Y=G.subscribe;if(typeof Y!=="function")return;let J=this.buildSectionEventPredicate(Q);Q.unsubscribeCurrent=Y.call(G,(Z)=>{if(!J(Z))return;this.deliverSectionEventSafely(Q.listener,Z)});let X=this.buildContentLoadedReplayEvents(G);for(let Z of X)if(J(Z))this.deliverSectionEventSafely(Q.listener,Z);let j=this.buildLoadingCompleteReplayEvent(G);if(j&&J(j))this.deliverSectionEventSafely(Q.listener,j)}deliverSectionEventSafely(Q,G){try{Q(G)}catch(Y){console.warn("[ToolkitCoordinator] section-event listener failed:",Y)}}setActiveCohort(Q){if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=Q;let G=this.sectionControllers.get(Q);if(!G)return;for(let Y of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(Y,G)}setActiveCohortIfLatestRequest(Q){if(this.latestRequestedActiveCohortMapKey!==Q)return;this.setActiveCohort(Q)}suspendActiveCohortIfSuperseded(Q){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=null;for(let G of Array.from(this.activeSubscriptions.values()))G.unsubscribeCurrent?.(),G.unsubscribeCurrent=null}clearActiveCohortIfMatches(Q){if(this.activeCohortMapKey!==Q)return;this.activeCohortMapKey=null;for(let G of Array.from(this.activeSubscriptions.values()))G.unsubscribeCurrent?.(),G.unsubscribeCurrent=null}buildSectionEventPredicate(Q){let G=Q.eventTypes?new Set(Q.eventTypes):null,Y=Q.itemIds?new Set(Q.itemIds):null;return(J)=>{if(G||Y){let X=J?.type||null;if(G&&(!X||!G.has(X)))return!1;if(Y){if(!Array.from(this.collectEventItemIds(J)).some((Z)=>Y.has(Z)))return!1}}return!0}}collectEventItemIds(Q){let G=new Set;if("itemId"in Q&&typeof Q.itemId==="string")G.add(Q.itemId);if("canonicalItemId"in Q&&typeof Q.canonicalItemId==="string")G.add(Q.canonicalItemId);if("currentItemId"in Q&&typeof Q.currentItemId==="string")G.add(Q.currentItemId);if("previousItemId"in Q&&typeof Q.previousItemId==="string")G.add(Q.previousItemId);return G}buildContentLoadedReplayEvents(Q){let G=Q.getRuntimeState?.(),Y=G?.loadedRenderables;if(!Array.isArray(Y)||Y.length===0)return[];let J=typeof G?.currentItemIndex==="number"&&Number.isFinite(G.currentItemIndex)?G.currentItemIndex:0,X=Date.now(),j=[];for(let Z of Y){if(!Z)continue;let K=Z.itemId,W=typeof Z.canonicalItemId==="string"&&Z.canonicalItemId?Z.canonicalItemId:K;if(typeof K!=="string"||!K)continue;j.push({type:"content-loaded",contentKind:Z.contentKind??"unknown",itemId:K,canonicalItemId:W,currentItemIndex:J,timestamp:X})}return j}buildLoadingCompleteReplayEvent(Q){let G=Q.getRuntimeState?.();if(G?.loadingComplete!==!0)return null;let Y=typeof G.totalRegistered==="number"&&Number.isFinite(G.totalRegistered)?Math.max(0,G.totalRegistered):0,J=typeof G.totalLoaded==="number"&&Number.isFinite(G.totalLoaded)?Math.max(0,G.totalLoaded):Y;return{type:"section-loading-complete",totalRegistered:Y,totalLoaded:J,currentItemIndex:G.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||A9,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||N9,listener:Q.listener})}onSectionControllerLifecycle(Q){return this.sectionControllerLifecycleListeners.add(Q),()=>{this.sectionControllerLifecycleListeners.delete(Q)}}async getOrCreateSectionController(Q){let G={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},Y=this.getSectionControllerMapKey(G);this.latestRequestedActiveCohortMapKey=Y,this.suspendActiveCohortIfSuperseded(Y);let J=await this.resolveExistingSectionController({mapKey:Y,key:G,input:Q.input,updateExisting:Q.updateExisting});if(J)return J;let X=this.sectionControllerInitPromises.get(Y);if(X)return X;let j=this.initializeNewSectionController({args:Q,key:G,mapKey:Y}).catch((Z)=>{throw this.handleSectionControllerInitError(Z,Q),Z}).finally(()=>{this.sectionControllerInitPromises.delete(Y)});return this.sectionControllerInitPromises.set(Y,j),j}async resolveExistingSectionController(Q){let G=this.sectionControllers.get(Q.mapKey);if(!G)return;if(this.sectionControllerKeys.set(Q.mapKey,Q.key),Q.updateExisting!==!1)await G.updateInput?.(Q.input);return this.setActiveCohortIfLatestRequest(Q.mapKey),G}createSectionControllerContext(Q){return{key:Q.key,coordinator:this,input:Q.input}}async initializeNewSectionController(Q){let G=this.createSectionControllerContext({key:Q.key,input:Q.args.input}),Y=await this.resolveSectionPersistence(G),J={createDefaultController:Q.args.createDefaultController},X=await this.hooks.createSectionController?.(G,J)??await J.createDefaultController();return await X.configureSessionPersistence?.({strategy:Y,context:G}),await X.initialize?.(Q.args.input),await X.hydrate?.(),await this.finalizeSectionControllerReady({mapKey:Q.mapKey,key:Q.key,context:G,controller:X}),X}async finalizeSectionControllerReady(Q){this.sectionControllers.set(Q.mapKey,Q.controller),this.sectionControllerKeys.set(Q.mapKey,Q.key),this.setActiveCohortIfLatestRequest(Q.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Q.key,controller:Q.controller}),await this.hooks.onSectionControllerReady?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}handleSectionControllerInitError(Q,G){this.handleError(Q,{phase:"section-controller-init",details:{sectionId:G.sectionId,attemptId:G.attemptId}})}async disposeSectionController(Q){let G={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},Y=this.getSectionControllerMapKey(G),J=this.sectionControllers.get(Y);if(!J)return;this.clearActiveCohortIfMatches(Y);let X=this.createSectionControllerContext({key:G,input:void 0});try{await this.runSectionControllerDisposePipeline({key:G,context:X,controller:J,persistBeforeDispose:Q.persistBeforeDispose})}catch(j){this.handleError(j,{phase:"section-controller-dispose",details:{sectionId:Q.sectionId,attemptId:Q.attemptId}})}finally{await this.finalizeSectionControllerDispose({mapKey:Y,key:G,context:X,clearPersistence:Q.clearPersistence})}}async runSectionControllerDisposePipeline(Q){if(Q.persistBeforeDispose!==!1)await Q.controller.persist?.();await Q.controller.dispose?.(),await this.hooks.onSectionControllerDispose?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}async finalizeSectionControllerDispose(Q){if(this.sectionControllers.delete(Q.mapKey),this.sectionControllerKeys.delete(Q.mapKey),this.emitSectionControllerLifecycle({type:"disposed",key:Q.key}),Q.clearPersistence)await this.sectionPersistenceStrategies.get(Q.mapKey)?.clearSession?.(Q.context);this.sectionPersistenceStrategies.delete(Q.mapKey)}async ensureTTSReady(Q){if(await this.waitForPendingTTSReconfigure(),this.ttsInitialized)return;if(this.ttsInitPromise)return this.ttsInitPromise;return this.ttsInitPromise=this._initializeTTS(Q).finally(()=>{this.ttsInitPromise=void 0}),this.ttsInitPromise}async waitForPendingTTSReconfigure(){let Q=this.ttsReconfigurePromise;while(Q)await Q,Q=this.ttsReconfigurePromise}async _initializeTTS(Q){if(this.ttsInitialized)return;let G=this.resolveTTSToolConfig(Q),Y=f0(G),J=L8(Y),X=k0(Y);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:J}}),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("tts"))try{let K=await(await this.ensureProviderReady("tts")).createInstance();await this.initializeTTSService(K,X),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"}),console.log("[ToolkitCoordinator] TTS initialized via ToolProviderRegistry");return}catch(Z){let K=Z instanceof Error?Z:Error(String(Z));await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:J,errorType:"TTSRegistryInitError",message:K.message,recovered:!0}),await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:J,fromProvider:"registry",toProvider:"browser",reason:K.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",K)}let j=new b7;try{await this.initializeTTSService(j,X),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(Z){let K=Z instanceof Error?Z:Error(String(Z));throw this.handleError(K,{phase:"tts-init"}),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:K.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:J,errorType:"TTSInitError",message:K.message}),K}}resolveTTSToolConfig(Q){return Q||this.getTTSConfigFromProviders()||{}}async initializeTTSService(Q,G){let Y={...G.providerOptions||{},__pieTelemetry:async(X,j)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...j||{}})}},J={...G,providerOptions:Y};await this.ttsService.initialize(Q,J),await this.ensureBrowserVoicesReady(Q),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,await this.hooks.onTTSReady?.()}async ensureBrowserVoicesReady(Q,G=1200){if(Q.providerId!=="browser")return;if(typeof window>"u")return;if(!("speechSynthesis"in window))return;let Y=window.speechSynthesis;if(Y.getVoices().length>0)return;await new Promise((j)=>{let Z=!1,K=typeof Y.addEventListener==="function"&&typeof Y.removeEventListener==="function",W=!K&&"onvoiceschanged"in Y,B=W?Y.onvoiceschanged:null,U=!1,V=()=>{if(Z)return;if(Z=!0,window.clearTimeout(N),K)Y.removeEventListener("voiceschanged",H);else if(U&&Y.onvoiceschanged===H)Y.onvoiceschanged=B;j()},H=(O)=>{if(!K&&typeof B==="function"&&O)B.call(Y,O);V()},N=window.setTimeout(V,G);if(K)Y.addEventListener("voiceschanged",H,{once:!0});else if(W)Y.onvoiceschanged=H,U=!0});let X=Y.getVoices();await this.emitTelemetry("pie-toolkit-tts-browser-voices-ready",{voiceCount:X.length,timedOut:X.length===0})}getServiceBundle(){return{ttsService:this.ttsService,toolCoordinator:this.toolCoordinator,highlightCoordinator:this.highlightCoordinator,elementToolStateStore:this.elementToolStateStore,catalogResolver:this.catalogResolver,toolProviderRegistry:this.toolProviderRegistry}}async getToolProvider(Q){return this.ensureProviderReady(Q)}async waitUntilReady(){if(this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded();let Q=this.getTTSConfigFromProviders();if(Q?.enabled!==!1)await this.ensureTTSReady(Q);if(!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return this.getInitStatus().coordinator}getInitStatus(){let Q={};for(let Y of this.toolProviderRegistry.getProviderIds())Q[Y]=this.toolProviderRegistry.isInitialized(Y);let G=this.getTTSConfigFromProviders();return{tts:this.ttsInitialized,stateLoaded:this.stateLoaded||!this.hooks.loadToolState,coordinator:(this.stateLoaded||!this.hooks.loadToolState)&&(this.ttsInitialized||G?.enabled===!1),providers:Q}}getTTSConfigFromProviders(){return(this.config.tools?.providers||{}).textToSpeech}assertCanonicalToolId(Q){if(typeof Q!=="string"||Q.trim().length===0)throw Error("Tool id must be a non-empty string.");if(Q==="tts")throw Error('Tool id "tts" is no longer supported. Use "textToSpeech".');if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Q))throw Error(`Unknown tool id "${Q}".`)}installToolContextResolvers(Q){if(!Q)return;for(let[G,Y]of Object.entries(Q)){if(Y==null)continue;if(this.assertCanonicalToolId(G),typeof Y!=="function")throw Error(`Invalid tool context resolver for "${G}": expected a function.`);this.toolContextResolvers.set(G,Y)}}setToolContextResolvers(Q){this.toolContextResolvers.clear(),this.installToolContextResolvers(Q??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Q of this.toolContextResolverChangeListeners)try{Q()}catch(G){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",G)}}isToolEnabled(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]?.enabled!==!1}getToolConfig(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]||null}updateToolConfig(Q,G){this.assertCanonicalToolId(Q);let Y=this.getToolConfig(Q)||{};if(!this.config.tools)this.config.tools=X7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}).config;if(!this.config.tools.providers)this.config.tools.providers={};let J={...this.config.tools.providers||{},[Q]:F9(Q,Y,G)},X=X7({...this.config.tools,providers:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X.config,this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Q}),this._applyToolConfigChange(Q,G)}updateToolPlacement(Q,G){this.updateToolsPlacement({[Q]:[...G]})}updateToolsPlacement(Q){if(!this.config.tools)this.config.tools=X7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}).config;let G=this.config.tools?.placement??{section:[],item:[],passage:[]},Y={section:[...Q.section??G.section??[]],item:[...Q.item??G.item??[]],passage:[...Q.passage??G.passage??[]]},J=X7({...this.config.tools,placement:Y},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});J.config.placement=Y,this.config.tools=J.config,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(Q){return this.policyEngine.decide(Q)}decideFeaturePolicy(Q){let G=this.policyEngine.decideFeature(Q);if(!G.assessmentBound&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Q}" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`);return G}onPolicyChange(Q){return this.policyEngine.onPolicyChange(Q)}onCatalogsChange(Q){return this.catalogResolver.onCatalogsChange(Q)}updateAssessment(Q){this.boundAssessment=Q,this.policyEngine.updateInputs({assessment:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}updateCurrentItemRef(Q){this.boundCurrentItemRef=Q,this.policyEngine.updateInputs({currentItemRef:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}setPnpEnforcement(Q){this.pnpEnforcementOverride=Q,this.policyEngine.updateInputs({pnpEnforcement:this.resolveEffectivePnpEnforcement()})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Q){return this.policyEngine.registerPolicySource(Q)}registerToolContextResolver(Q,G){if(this.assertCanonicalToolId(Q),typeof G!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);return this.toolContextResolvers.set(Q,G),this.notifyToolContextResolverChange(),()=>{if(this.toolContextResolvers.get(Q)!==G)return;this.toolContextResolvers.delete(Q),this.notifyToolContextResolverChange()}}hasToolContextResolver(Q){return this.assertCanonicalToolId(Q),this.toolContextResolvers.has(Q)}resolveToolContext(Q){this.assertCanonicalToolId(Q.toolId);let G=this.toolContextResolvers.get(Q.toolId);if(!G)return null;let Y;try{Y=G(Q)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Q.toolId}" threw:`,X),{toolId:Q.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!Y)return{toolId:Q.toolId,visible:!0,params:{}};let J=Y.params&&typeof Y.params==="object"&&!Array.isArray(Y.params)?Y.params:{};return{toolId:Q.toolId,visible:Y.visible!==!1,params:J,reason:typeof Y.reason==="string"?Y.reason:void 0}}onToolContextResolverChange(Q){return this.toolContextResolverChangeListeners.add(Q),()=>{this.toolContextResolverChangeListeners.delete(Q)}}registerToolRequestTarget(Q){return this.toolRequests.registerTarget(Q)}requestTool(Q){return this.assertCanonicalToolId(Q.toolId),this.toolRequests.request(Q)}canRequestTool(Q,G){try{this.assertCanonicalToolId(Q)}catch{return!1}return this.toolRequests.canRequest(Q,G)}onToolRequestTargetsChange(Q){return this.toolRequests.onTargetsChange(Q)}resolveEffectivePnpEnforcement(){if(this.pnpEnforcementOverride!==null)return this.pnpEnforcementOverride;return g7({assessment:this.boundAssessment,currentItemRef:this.boundCurrentItemRef})}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Q,G){switch(Q){case"textToSpeech":{let Y=this._reconfigureTTSProvider();this.ttsReconfigurePromise=Y,Y.finally(()=>{if(this.ttsReconfigurePromise===Y)this.ttsReconfigurePromise=void 0}),Y.then(async()=>{let J=this.getTTSConfigFromProviders();if(!this.lazyInit&&J?.enabled!==!1)await this.ensureTTSReady(J)});break}case"answerEliminator":break}}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsInitPromise=void 0;try{this.ttsService.stop()}catch{}if(this.toolProviderRegistry.has("tts"))await this.toolProviderRegistry.unregister("tts");let Q=this.getProviderDescriptorTools().find((G)=>G.toolId==="textToSpeech");if(!Q)return;await this.registerProviderFromTool(Q)}}var M9=()=>{};function u0(Q){let{ttsService:G,listenerId:Y,silence:J}=Q;if(typeof G?.onStateChange!=="function")return M9;let X=(j)=>{if(j!==R.PLAYING&&j!==R.LOADING)return;J()};return G.onStateChange(Y,X),()=>{try{G.offStateChange?.(Y,X)}catch{}}}function p0(Q){try{if(Q?.isPlaying?.())Q.pause?.()}catch{}}import{timedMediaProjectionSignature as n9}from"@pie-players/pie-players-shared/timed-media";var g0="pie-register",c0="pie-unregister",l0="pie-item-session-changed";var d0="pie-content-loaded",i0="pie-item-player-error",s0="pie-formative-action",n0="pie-media-time-source";var O9={bubbles:!0,composed:!0,cancelable:!1};function z9(Q,G,Y={}){return new CustomEvent(Q,{detail:G,...O9,...Y})}function b8(Q,G,Y,J={}){return Q.dispatchEvent(z9(G,Y,J))}function y7(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function C8(Q,G){if(Q===G)return!0;if(!Q||!G)return!1;return Q.sectionId===G.sectionId&&Q.attemptId===G.attemptId}function P9(Q){if(Q.runtimeError)return"error";if(Q.allLoadingComplete)return"ready";if(Q.interactionReady)return"interaction-ready";if(Q.sectionReady)return"loading";return"bootstrapping"}function r0(Q){let G=Q.signals.sectionReady&&Q.signals.allLoadingComplete,Y=Q.mode==="strict"?G:Q.signals.interactionReady;return{phase:P9({...Q.signals,allLoadingComplete:G,interactionReady:Y}),interactionReady:Y,allLoadingComplete:G,reason:Q.reason}}function o0(Q){switch(Q){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function R1(Q,G,Y,J="entered"){let X=o0(G);if(!X)return;Q.push({kind:"stage-change",stage:X,status:J,cohort:Y})}function a0(Q){let G={...y7(),phase:"booting-section",cohort:Q.cohort,effectiveRuntime:Q.effectiveRuntime,effectiveToolsConfig:Q.effectiveToolsConfig,itemCount:Q.itemCount},Y=[];return R1(Y,"booting-section",Q.cohort),{state:G,outputs:Y}}function L9(Q,G){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let Y=r0({mode:G.mode,signals:G.signals}),J=[],X=Q.phase,j=Q.loadingCompleteEmitted;if(X==="engine-ready"&&Y.interactionReady)X="interactive",R1(J,X,Q.cohort);if(Y.allLoadingComplete&&Q.cohort&&!j)j=!0,J.push({kind:"loading-complete",cohort:Q.cohort,itemCount:G.itemCount,loadedCount:G.loadedCount});return{state:{...Q,phase:X,readinessSignals:G.signals,loadedCount:G.loadedCount,itemCount:G.itemCount,loadingCompleteEmitted:j},outputs:J}}function c7(Q,G){switch(G.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if(C8(Q.cohort,G.cohort))return c7(Q,{kind:"update-runtime",effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig});return c7(Q,{kind:"cohort-change",cohort:G.cohort,effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig,itemCount:G.itemCount})}return a0({state:Q,cohort:G.cohort,effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig,itemCount:G.itemCount})}case"update-runtime":{if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};return{state:{...Q,effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig},outputs:[]}}case"cohort-change":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(C8(Q.cohort,G.cohort))return c7(Q,{kind:"update-runtime",effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig});let Y=[];if(Q.phase!=="idle")Y.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:Q.cohort});let J=a0({state:Q,cohort:G.cohort,effectiveRuntime:G.effectiveRuntime,effectiveToolsConfig:G.effectiveToolsConfig,itemCount:G.itemCount});return{state:J.state,outputs:[...Y,...J.outputs]}}case"section-controller-resolved":{if(Q.phase!=="booting-section")return{state:{...Q,controllerResolved:!0},outputs:[]};let Y=[];return R1(Y,"engine-ready",Q.cohort),{state:{...Q,phase:"engine-ready",controllerResolved:!0},outputs:Y}}case"update-readiness-signals":return L9(Q,{signals:G.signals,mode:G.mode,loadedCount:G.loadedCount,itemCount:G.itemCount});case"framework-error":return{state:{...Q,lastFrameworkError:G.error,readinessSignals:{...Q.readinessSignals,runtimeError:G.error.recoverable===!0?Q.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:G.error}]};case"dispose":{if(Q.phase==="disposed")return{state:Q,outputs:[]};let Y=[];if(Q.phase!=="idle")R1(Y,"disposed",Q.cohort);return{state:{...Q,phase:"disposed"},outputs:Y}}default:{let Y=G;return{state:Q,outputs:[]}}}}class T8{state=y7();listeners=new Set;getState(){return this.state}dispatch(Q){let G=c7(this.state,Q);if(this.state=G.state,G.outputs.length>0)this.fanOut(G.outputs);return G.outputs}subscribe(Q){this.listeners.add(Q);let G=!0;return()=>{if(!G)return;G=!1,this.listeners.delete(Q)}}disposeListeners(){this.listeners.clear()}fanOut(Q){let G=Array.from(this.listeners),Y=Object.freeze(Q.slice());for(let J of G)try{J(Y)}catch(X){console.warn("[SectionEngineCore] listener failed:",X)}}}function t0(Q){let{coordinator:G,dispatchCoreInput:Y}=Q,J=0,X=null,j=null,Z=!1,K=G.subscribeFrameworkErrors((V)=>{try{Y({kind:"framework-error",error:V})}catch(H){console.warn("[CoordinatorBridge] framework-error dispatch failed:",H)}});function W(){if(!j)return;try{j()}catch(V){console.warn("[CoordinatorBridge] controller unsubscribe failed:",V)}j=null}async function B(V){if(Z)return;J+=1;let H=J;X=V.cohort;let N=await G.getOrCreateSectionController({sectionId:V.cohort.sectionId,attemptId:V.cohort.attemptId||void 0,input:{section:V.section,sectionId:V.cohort.sectionId,assessmentId:V.assessmentId,view:V.view},updateExisting:!0,createDefaultController:V.createDefaultController});if(H!==J||Z)return;W(),V.onControllerResolved?.(N);let O=N.getCompositionModel;if(V.onCompositionChanged?.(O?.()),typeof N.subscribe==="function")j=N.subscribe((P)=>{if(H!==J||Z)return;V.onCompositionChanged?.(O?.())});Y({kind:"section-controller-resolved"})}async function U(){if(Z)return;Z=!0,J+=1,W();try{K()}catch(H){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",H)}let V=X;if(X=null,V)try{await G.disposeSectionController({sectionId:V.sectionId,attemptId:V.attemptId||void 0})}catch(H){console.warn("[CoordinatorBridge] section-controller dispose failed:",H)}}return{resolveSectionController:B,dispose:U}}function e0(Q){let{runtimeId:G,sourceCe:Y}=Q,J=Q.host,X=Q.now??(()=>new Date().toISOString());function j(U){let V={stage:U.stage,status:U.status,runtimeId:G,sectionId:U.cohort?.sectionId,attemptId:U.cohort?.attemptId?U.cohort.attemptId:void 0,timestamp:X(),sourceCe:Y};J.dispatchEvent(new CustomEvent("pie-stage-change",{detail:V}))}function Z(U){let V={runtimeId:G,sectionId:U.cohort.sectionId,attemptId:U.cohort.attemptId?U.cohort.attemptId:void 0,itemCount:U.itemCount,loadedCount:U.loadedCount,timestamp:X(),sourceCe:Y};J.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:V}))}function K(U){J.dispatchEvent(new CustomEvent("framework-error",{detail:U.error}))}function W(U){switch(U.kind){case"stage-change":j(U);return;case"loading-complete":Z(U);return;case"framework-error":K(U);return;default:{let V=U;return}}}function B(U){J=U}return{dispatch:W,setHost:B}}function Q3(Q){let{bus:G}=Q;function Y(J){switch(J.kind){case"framework-error":G.reportFrameworkError(J.error);return;case"stage-change":case"loading-complete":return;default:{let X=J;return}}}return{dispatch:Y}}function G3(Q={}){let G=Q.hook;function Y(X){if(!G)return;try{G(X)}catch(j){console.warn("[InstrumentationBridge] hook failed:",j)}}function J(X){G=X}return{dispatch:Y,setHook:J}}function Y3(){let Q=new Set;function G(j){if(j.length===0)return;let Z=Array.from(Q),K=Object.freeze(j.slice());for(let W of Z)try{W(K)}catch(B){console.warn("[SubscriberFanout] listener failed:",B)}}function Y(j){Q.add(j);let Z=!0;return()=>{if(!Z)return;Z=!1,Q.delete(j)}}function J(){Q.clear()}function X(){return Q.size}return{emit:G,subscribe:Y,dispose:J,getListenerCount:X}}class S8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new T8,this.domEventBridge=e0({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=Q3({bus:Q.frameworkErrorBus}),this.instrumentationBridge=G3({hook:Q.instrumentationHook}),this.subscriberFanout=Y3(),this.coordinatorBridge=Q.coordinator?t0({coordinator:Q.coordinator,dispatchCoreInput:(G)=>this.dispatchInput(G)}):null,this.unsubscribeCore=this.core.subscribe((G)=>{this.routeOutputs(G)})}getState(){return this.core.getState()}dispatchInput(Q){if(this.disposed)return[];return this.core.dispatch(Q)}subscribe(Q){return this.subscriberFanout.subscribe(Q)}setHost(Q){this.domEventBridge.setHost(Q)}setInstrumentationHook(Q){this.instrumentationBridge.setHook(Q)}resolveSectionController(Q){if(!this.coordinatorBridge)throw Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(Q)}async dispose(){if(this.disposed)return;if(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge)await this.coordinatorBridge.dispose()}routeOutputs(Q){for(let G of Q)this.routeOne(G);this.subscriberFanout.emit(Q)}routeOne(Q){switch(Q.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(Q);break;case"framework-error":this.domEventBridge.dispatch(Q),this.frameworkErrorBridge.dispatch(Q);break;default:{let G=Q;return}}this.instrumentationBridge.dispatch(Q)}}var $9={mode:"gather",role:"student"};function E1(Q,G){return Q!==void 0?Q:G}function w9(Q){let G=Q.runtime??{};if(G.onFrameworkError!==void 0)return G.onFrameworkError;return Q.onFrameworkError}function R9(Q){let G=Q.runtime?.tools||{},Y=G.placement||{};return{...G,placement:{...Y}}}function E9(Q){let G=Q.runtime||{},Y=G.player?{...G.player}:null;return{...G,assessmentId:E1(G.assessmentId,Q.assessmentId),playerType:G.playerType??"iife",player:Y,lazyInit:G.lazyInit??!0,accessibility:G.accessibility??null,coordinator:G.coordinator??null,createSectionController:G.createSectionController,isolation:G.isolation??"inherit",env:G.env??$9,toolConfigStrictness:E1(G.toolConfigStrictness,Q.toolConfigStrictness)??"error",onFrameworkError:w9({runtime:Q.runtime,onFrameworkError:Q.onFrameworkError}),onStageChange:E1(G.onStageChange,Q.onStageChange),onLoadingComplete:E1(G.onLoadingComplete,Q.onLoadingComplete),tools:Q.effectiveToolsConfig}}function J3(Q,G){let Y=Q.assessmentId??"section-demo-direct",J=R9({runtime:Q.runtime}),X=E9({assessmentId:Y,runtime:Q.runtime,effectiveToolsConfig:J,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),j=G.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:J,effectiveRuntime:X,playerRuntime:j}}import{createPieLogger as C9,isGlobalDebugEnabled as T9}from"@pie-players/pie-players-shared";function b9(Q,G){if(Q===G)return 0;let Y=Q.compareDocumentPosition(G);if(Y&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(Y&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class y8{shellsByElement=new Map;register(Q){let G=this.shellsByElement.get(Q.element),Y={...Q,sortKey:Date.now()};if(G&&G.kind===Y.kind&&G.itemId===Y.itemId&&G.canonicalItemId===Y.canonicalItemId)return!1;return this.shellsByElement.set(Q.element,Y),!0}unregister(Q){return this.shellsByElement.delete(Q)}getOrderedShells(Q){let G=Array.from(this.shellsByElement.values()).filter((Y)=>!Q||Y.kind===Q);return G.sort((Y,J)=>b9(Y.element,J.element)),G}getCanonicalIdMap(){let Q={};for(let G of this.getOrderedShells("item")){if(!G.itemId)continue;Q[G.itemId]=G.canonicalItemId||G.itemId}return Q}clear(){this.shellsByElement.clear()}}function b1(Q="runtime"){return`${Q}-${Math.random().toString(16).slice(2)}-${Date.now()}`}var S9=C9("section-runtime-engine",()=>T9());class x8{registry=new y8;runtimeId=b1("section-engine");adapter=null;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;loadedRenderableKeys=new Set;attachHost(Q){if(this.adapter){if(this.adapter.setHost(Q.host),Q.instrumentationHook!==void 0)this.adapter.setInstrumentationHook(Q.instrumentationHook);return}this.adapter=new S8({host:Q.host,runtimeId:this.runtimeId,sourceCe:Q.sourceCe,frameworkErrorBus:Q.frameworkErrorBus,coordinator:Q.coordinator,instrumentationHook:Q.instrumentationHook,now:Q.now})}dispatchInput(Q){return this.adapter?.dispatchInput(Q)??[]}subscribe(Q){return this.adapter?.subscribe(Q)??y9}getState(){return this.adapter?.getState()??y7()}getEffectiveRuntime(Q,G){return J3(Q,G).effectiveRuntime}setInstrumentationHook(Q){this.adapter?.setInstrumentationHook(Q)}getRuntimeId(){return this.runtimeId}async initialize(Q){this.activeInitToken+=1;let G=this.activeInitToken;this.coordinator=Q.coordinator,this.sectionId=Q.sectionId,this.attemptId=Q.attemptId;let Y=await Q.coordinator.getOrCreateSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId,input:{section:Q.section,sectionId:Q.sectionId,assessmentId:Q.assessmentId,view:Q.view},updateExisting:!0,createDefaultController:Q.createDefaultController});if(G!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=Y,this.replayRegisteredShellsIntoController(Y),Q.onCompositionChanged?.(Y.getCompositionModel?.()),this.unsubscribeController=Y.subscribe?.((J)=>{try{Q.onControllerEvent?.(J)}catch(X){S9.warn("onControllerEvent handler threw",X)}Q.onCompositionChanged?.(Y.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Q){if(!Q.handleContentRegistered)return;let G=this.registry.getOrderedShells();if(G.length===0)return;for(let J of G){let X=J.canonicalItemId||J.itemId;Q.handleContentRegistered({itemId:J.itemId,canonicalItemId:X,contentKind:J.contentKind||J.kind})}let Y=Date.now();for(let J of G){let X=J.canonicalItemId||J.itemId,j=this.getLoadedKey(X,J.contentKind);if(this.loadedRenderableKeys.has(j))Q.handleContentLoaded?.({itemId:J.itemId,canonicalItemId:X,contentKind:J.contentKind||J.kind,timestamp:Y})}}getLoadedKey(Q,G){return`${G??""}:${Q}`}register(Q){return this.registry.register(Q)}unregister(Q){return this.registry.unregister(Q)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Q){return this.registry.getCanonicalIdMap()[Q]||this.controller?.getCanonicalItemId?.(Q)||Q}handleContentRegistered(Q){this.controller?.handleContentRegistered?.({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId,contentKind:Q.contentKind||Q.kind})}handleContentUnregistered(Q){let G=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(G,Q.contentKind)),this.controller?.handleContentUnregistered?.({itemId:Q.itemId,canonicalItemId:G,contentKind:Q.contentKind||Q.kind})}handleContentLoaded(Q){let G=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(G,Q.contentKind)),this.controller?.handleContentLoaded?.(Q)}handleItemPlayerError(Q){this.controller?.handleItemPlayerError?.(Q)}reportSectionError(Q){this.controller?.reportSectionError?.(Q)}updateItemSession(Q,G){let Y=this.getCanonicalItemId(Q);return this.controller?.updateItemSession?.(Y,G)??null}navigateToItem(Q){return this.controller?.navigateToItem?.(Q)??null}handleFormativeAction(Q){if(!Q?.itemId)return;let G=this.getCanonicalItemId(Q.itemId);if(Q.action==="retry"){this.controller?.retryFormativeItem?.({itemId:G});return}this.controller?.recordFormativeTry?.({itemId:G,outcomes:Q.outcomes})}handleMediaTimeSource(Q){if(Q?.action==="detach"){this.controller?.detachMediaTimeSource?.({origin:Q.origin??"host"});return}if(!Q?.source)return;this.controller?.attachMediaTimeSource?.(Q.source,{origin:Q.origin??"host",renderableId:Q.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId)await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId});if(this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){let Q=this.adapter;this.adapter=null,await Q.dispose()}}}var y9=()=>{};import{ContextConsumer as x9,createContext as f9}from"@pie-players/pie-context";var X3=f9(Symbol.for("pie.sectionRuntimeEngineHostContext"));function Z3(Q,G){let Y=!1,J=new x9(Q,{context:X3,subscribe:!0,onValue:(W)=>{Y=!0,G(W)}});J.connect();let X=(W)=>{if(W.context!==X3)return;J.requestValue()};Q.addEventListener("context-provider",X);let j=0,Z=200,K=globalThis.setInterval(()=>{if(Y||j>=Z){globalThis.clearInterval(K);return}j+=1,J.requestValue()},50);return()=>{globalThis.clearInterval(K),Q.removeEventListener("context-provider",X),J.disconnect()}}var k9=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function j3(Q,G){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(G);let Y=Q.getOnStageChange();if(Y)try{Y(G)}catch(J){(Q.logHandlerError??k9)(J)}return!0}function l7(Q,G){if(typeof Q==="function")return Q;if(Q===null)return null;return typeof G==="function"?G:null}function K3(Q={}){let G=Q.frameDeadlineMs??100,Y=!1,J=null,X=null,j=null,Z=null,K=null;function W(){if(Y=!1,X!==null)Z?.(X),X=null;if(j!==null)K?.(j),j=null;Z=null,K=null}function B(H){if(!Y)return;if(H==="frame")X=null;if(H==="timer")j=null;let N=J;J=null,W(),N?.()}function U(H){if(J=H,Y)return;Y=!0;let N=globalThis,O=l7(Q.requestFrame,N.requestAnimationFrame);Z=l7(Q.cancelFrame,N.cancelAnimationFrame);let P=l7(Q.setTimer,N.setTimeout);if(K=l7(Q.clearTimer,N.clearTimeout),O){let F=O(()=>B("frame"));if(!Y)return;if(X=F,P){let L=P(()=>B("timer"),G);if(Y)j=L}return}let $=l7(Q.queueMicrotaskFn,N.queueMicrotask);if($){$(()=>B("microtask"));return}if(P){let F=P(()=>B("timer"),0);if(Y)j=F;return}B("microtask")}function V(){if(!Y)return;J=null,W()}return{schedule:U,cancel:V,isPending:()=>Y}}function q3(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function W3(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function U3(Q){let{state:G,itemId:Y,payload:J}=Q;if(v9(J)){let Z=h9(J);if(G.lastMetadataSignatureByItemId.get(Y)===Z)return!1;G.lastMetadataSignatureByItemId.set(Y,Z)}let X=I9(J);if(G.lastSessionEventSignatureByItemId.get(Y)===X)return!1;return G.lastSessionEventSignatureByItemId.set(Y,X),!0}function I9(Q){let G={...Q};delete G.timestamp,delete G.sourceRuntimeId;try{return JSON.stringify(G)}catch{return String(G.itemId||"")}}function v9(Q){return Q.intent==="metadata-only"}function h9(Q){try{return JSON.stringify({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,intent:Q.intent,complete:Q.complete??null,component:Q.component??null})}catch{return String(Q.itemId||"")}}var m9=(Q,G)=>{if(customElements.get(Q))return;try{customElements.define(Q,G)}catch(Y){if(!(Y instanceof DOMException&&Y.name==="NotSupportedError"||Y&&typeof Y==="object"&&Y.name==="NotSupportedError")||!customElements.get(Q))throw Y}},r9=v8('<div class="pie-assessment-toolkit-error svelte-vpe4u2" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-vpe4u2"> </div> <div class="pie-assessment-toolkit-error-message svelte-vpe4u2"> </div> <pre class="pie-assessment-toolkit-error-details svelte-vpe4u2"> </pre></div>'),o9=v8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),a9={hash:"svelte-vpe4u2",code:`.pie-assessment-toolkit-anchor.svelte-vpe4u2 {display:none;}.pie-assessment-toolkit-error.svelte-vpe4u2 {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-vpe4u2 {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-vpe4u2 {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-vpe4u2 {margin:0;white-space:pre-wrap;word-break:break-word;}`};function w3(Q,G){_3(G,!0),M3(Q,a9);let Y=b1("toolkit"),J=new x8,X=h(null),j=new m7,Z={mode:"gather",role:"student"},K={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},W=x(G,"assessmentId",7,""),B=x(G,"section",7,null),U=x(G,"sectionId",7,""),V=x(G,"attemptId",7,""),H=x(G,"env",23,()=>({})),N=x(G,"ndsIcons",7,!1),O=x(G,"locale",7,""),P=x(G,"lazyInit",7,!0),$=x(G,"toolConfigStrictness",7,"error"),F=x(G,"tools",23,()=>({})),L=x(G,"toolContextResolvers",7,null),C=x(G,"enabledTools",7,""),v=x(G,"toolRegistry",7,null),I=x(G,"accessibility",23,()=>({})),p=x(G,"player",7,null),E=x(G,"playerType",7,""),g=x(G,"coordinator",7,null),j7=x(G,"createSectionController",7,null),K7=x(G,"onFrameworkError",7,null),q7=x(G,"errorRenderer",7,null),$7=x(G,"onStageChange",7,null),s7=x(G,"assessment",7,null),n7=x(G,"currentItemRef",7,null),r7=x(G,"pnpEnforcement",7,null),W7=x(G,"isolation",7,"inherit"),x7=h(null),d=h(null),Y7=h(null),h8=null,f7=null,k7=null,o7=null,I7=null,a7=null,t7=h(0),y1=h(null),e7=h(null),r=h(null),x1=h("Unable to initialize assessment toolkit."),f1=h(f8([])),m8="",k1="",u8=h(""),p8=null,g8=K3(),U7=[],Q1=new Map,I1=new WeakMap,c8=q3(),i=g9({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:Y,sectionId:m(()=>U()||void 0),attemptId:m(()=>V()||void 0),emit:(q)=>{j3({isSuppressed:()=>_(X)!==null,dispatchDomEvent:(D)=>B7("pie-stage-change",D),getOnStageChange:()=>$7()},q)}}),l8=h(f8(m(()=>`${U()}|${V()}`))),G1=h(!1),t=h(!1),v1=h(!1),h1=h(!1);function R3(){if(!_(x7))return null;let q=_(x7).getRootNode();if(q&&"host"in q)return q.host;return _(x7).parentElement}let f=n(()=>R3());function B7(q,D){if(!_(f)){U7=[...U7,{name:q,detail:D}];return}b8(_(f),q,D)}b(()=>{if(!_(f))return;if(U7.length===0)return;let q=U7;U7=[],queueMicrotask(()=>{let D=_(f);if(!D){U7=[...q,...U7];return}for(let M of q)b8(D,M.name,M.detail)})});function E3(q){if(!q7())return{title:"Unable to initialize assessment toolkit.",details:q.details.length>0?q.details:[q.message]};try{let D=q7()(q)||{};return{title:typeof D.title==="string"&&D.title.trim().length>0?D.title:"Unable to initialize assessment toolkit.",details:Array.isArray(D.details)&&D.details.length>0?D.details.map((M)=>String(M)):q.details.length>0?q.details:[q.message]}}catch(D){let M=D instanceof Error&&D.message.trim().length>0?D.message:String(D||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...q.details,`Error renderer failed: ${M}`]}}}function v7(q){let D=K1({kind:q.kind,source:q.source,error:q.error,recoverable:q.recoverable});return j.reportFrameworkError(D),D}function b3(q){if(q?.type==="timed-media-policy-degraded"){let M=q.degradations||[];j.reportFrameworkError(j1({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:M.map((z)=>z?.message).filter((z)=>typeof z==="string"),recoverable:!0}));return}if(q?.type!=="timed-media-invalid")return;let D=q.errors||[];j.reportFrameworkError(j1({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:D.map((M)=>M?.message).filter((M)=>typeof M==="string"),recoverable:!1}))}function C3(q){if(q?.type!=="timed-media-audio-started")return;if(!_(S))return;p0(_(S).getServiceBundle().ttsService)}function T3(q){return q==="coordinator-init"||q==="runtime-init"||q==="tool-config"}function d8(q){if(!K7())return;try{K7()(q),m8=`${q.kind}|${q.source}|${q.message}`}catch(D){console.error(`[pie-framework:${q.kind}:${q.source}] framework error hook failed`,D)}}b(()=>{let q=j.subscribeFrameworkErrors((D)=>{if(console.error(Y6(D),D.cause),T3(D.kind)){let M=E3(D);w(r,D,!0),w(x1,M.title,!0),w(f1,M.details,!0)}B7("framework-error",D),d8(D)});return()=>{q()}}),b(()=>{if(!_(r))return;let q=`${_(r).kind}|${_(r).source}|${_(r).message}`;if(m8===q)return;d8(_(r))});function S3(q){let D=5381;for(let M=0;M<q.length;M+=1)D=(D<<5)+D^q.charCodeAt(M);return(D>>>0).toString(36)}function s(q){return q&&typeof q==="object"?q:{}}function y3(q){let D=s(q.section),M=typeof D.identifier==="string"?D.identifier:"",z=typeof q.sectionId==="string"?q.sectionId:"";return M||z}function x3(q){return typeof q.currentItemIndex==="number"?q.currentItemIndex:-1}function f3(q){return(Array.isArray(q.renderables)?q.renderables:[]).map((M,z)=>{let A=s(M),k=s(A.entity),o=typeof k.id==="string"&&k.id||`renderable-${z}`,Z1=s(k.config),c1=typeof k.version==="string"&&k.version||(typeof k.version==="number"?String(k.version):"")||(typeof Z1.version==="string"?Z1.version:"");return{id:o,version:c1}})}function k3(q){let D=s(q.itemSessionsByItemId);return Object.keys(D).sort((M,z)=>M.localeCompare(z)).map((M)=>{let z=s(D[M]),A=typeof z.id==="string"?z.id:"",k=Array.isArray(z.data)?z.data:[],o="";try{o=S3(JSON.stringify(k))}catch{o=String(k.length)}return{itemId:M,sessionId:A,payloadSignature:o}})}function I3(q){let D=s(s(q.formative).states);return Object.entries(D).map(([M,z])=>{let A=s(z),k=s(A.lastOutcome).correctness??"";return`${M}:${A.tryCount??0}:${A.revealed===!0?1:0}:${String(k)}:${String(A.revealOverride??"")}`}).sort().join("|")}function v3(q){let D=q.timedMedia;return n9(D)}function h3(q){let D=s(q),M=f3(D).map((A)=>`${A.id}:${A.version}`).join("|"),z=k3(D).map((A)=>`${A.itemId}:${A.sessionId}:${A.payloadSignature}`).join("|");return{sectionId:y3(D),currentItemIndex:x3(D),renderableSignature:M,itemSessionSignature:z,formativeSignature:I3(D),timedMediaSignature:v3(D)}}function m3(q){let D=h3(q);return`${D.sectionId}|${D.currentItemIndex}|${D.renderableSignature}|${D.itemSessionSignature}|${D.formativeSignature}|${D.timedMediaSignature}`}function i8(q){return q==="iife"||q==="esm"||q==="preloaded"||q==="custom"}function u3(q,D){let M=q?.type,z=i8(M)?M:i8(D)?D:q?.tagName?"custom":"iife",A=q?.tagName?.trim();if(z==="custom"&&!A)return{type:"iife",tagName:K.iife,version:void 0,source:void 0,isDefault:!0};return{type:z,tagName:A||K[z],version:q?.version,source:q?.source,loaderConfig:q?.loaderConfig,loaderOptions:q?.loaderOptions,isDefault:!q&&!D}}function s8(q){let D=q||{},M=typeof D.mode==="string"&&D.mode.trim()?D.mode.trim():Z.mode,z=typeof D.role==="string"&&D.role.trim()?D.role.trim():Z.role;return{mode:M,role:z}}function p3(q){let D=s8(q);if(D.mode==="author")return"author";if(D.role==="instructor")return"scorer";return"candidate"}async function g3(){if(j7())return j7()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function n8(){let q=F()||{},D=$3(C());if(D.length===0)return q;let M=q.placement||{},z=Array.isArray(M.section)?M.section:null;if(z&&z.length>0)return q;return{...q,placement:{...M,section:D}}}function c3(){return X7(n8(),{strictness:$(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:v()}).config}function l3(){let q="",D="";try{q=JSON.stringify(n8())}catch{q="[unserializable-tools]"}try{D=JSON.stringify(Object.entries(L()??{}).map(([M,z])=>[M,typeof z]))}catch{D="[unserializable-resolvers]"}return[W()||"",String($()||"error"),q,D].join("|")}function r8(q){return q==="on"||q==="off"?q:null}function d3(q,D){let M=r8(q);if(M)return M;if(D&&typeof D==="object"){let A=D.pnpEnforcement;return r8(typeof A==="string"?A:null)}return null}function i3(q){let D=W()||B()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new w1({assessmentId:D,lazyInit:P(),toolConfigStrictness:$(),deferToolConfigValidation:!0,tools:q,toolRegistry:v(),toolContextResolvers:L(),accessibility:I(),frameworkErrorBus:j})}let S=n(()=>{if(W7()!=="force"&&_(Y7)?.coordinator)return _(Y7).coordinator;return g()||_(d)});b(()=>{_(f),g(),W7(),_(Y7),L(),m(()=>{if(!_(f))return;if(g()){if(_(d))w(d,null);f7=null;return}if(W7()!=="force"&&_(Y7)?.coordinator){if(_(d))w(d,null);f7=null;return}if(_(d)&&f7!==L()){try{_(d).setToolContextResolvers(L()),f7=L()}catch(q){w(e7,q,!0),v7({kind:"coordinator-init",phase:"coordinator-ready",error:q})}return}if(!_(d)){let q=l3();if(k1===q)return;try{let D=c3();w(d,i3(D),!0),f7=L(),k1="",w(r,null),w(x1,"Unable to initialize assessment toolkit."),w(f1,[],!0)}catch(D){w(e7,D,!0),w(d,null),k1=q,v7({kind:"coordinator-init",source:"pie-assessment-toolkit",error:D})}}})});let Y1=i9(),m1=h(0);b(()=>Y1.subscribe(()=>{w(m1,_(m1)+1)})),b(()=>{let q=typeof O()==="string"?O().trim():"";m(()=>{Promise.resolve(Y1.setLocale(q||s9)).catch((D)=>{v7({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:D instanceof Error?D:Error(String(D))})})})});let J7=n(()=>W()||_(S)?.assessmentId||""),e=n(()=>U()||B()?.identifier||`section-${_(J7)||"default"}`),u1=n(()=>s8(H())),s3=n(()=>p3(_(u1))),w7=n(()=>u3(p(),E())),h7=n(()=>c9({player:_(w7),component:"pie-assessment-toolkit"})),J1=n(()=>{if(!_(S))return null;let q=_(S).getServiceBundle();return{toolkitCoordinator:_(S),toolCoordinator:_(S).toolCoordinator,ttsService:q.ttsService,highlightCoordinator:q.highlightCoordinator,catalogResolver:q.catalogResolver,elementToolStateStore:q.elementToolStateStore,assessmentId:_(J7),sectionId:_(e),itemPlayer:_(w7),ndsIcons:N()===!0,locale:(_(m1),Y1.getLocale()),i18n:Y1,reportSessionChanged:(D,M)=>{let z=J.updateItemSession(D,M);t8({itemId:D,result:z,fallbackSession:M})}}}),X1=n(()=>{if(!_(S))return null;return{runtimeId:Y,coordinator:_(S)}});function n3(q){let D=m3(q);if(D===_(u8))return;w(u8,D,!0),w(t7,_(t7)+1),w(y1,q,!0),B7("composition-changed",{composition:_(y1),version:_(t7)})}function p1(q){p8=q??J.getCompositionModel(),g8.schedule(()=>{n3(p8)})}function g1(q){if(!q)return;let D=I1.get(q);if(!D)return;for(let M of D)M();I1.delete(q)}function o8(){for(let q of Q1.values())g1(q.element)}function a8(q){if(g1(q.element),!_(S))return;let D=_(S).getServiceBundle().catalogResolver;I1.set(q.element,[D.registerOwner({owner:{kind:q.kind,itemId:q.itemId,canonicalItemId:q.canonicalItemId,assessmentId:_(J7),sectionId:_(e)},entity:q.item})])}function r3(){o8();for(let q of Q1.values())a8(q)}function t8(q){let M={...q.result?.eventDetail||q.fallbackSession,itemId:q.itemId,canonicalItemId:q.canonicalItemId||q.itemId,sourceRuntimeId:Y};if(!U3({state:c8,itemId:q.itemId,payload:M}))return;B7("session-changed",M)}function o3(q){if(!(q instanceof HTMLElement))return!1;return u9(q,I8)?.runtimeId===Y}function D7(q){return q.detail??null}function a3(q,D){for(let M of D)q.addEventListener(M.name,M.handler);return()=>{for(let M of D)q.removeEventListener(M.name,M.handler)}}b(()=>{if(!_(f))return;if(W7()==="force"){w(Y7,null);return}return L3(_(f),(q)=>{if(q.runtimeId===Y)return;w(Y7,q,!0)})}),b(()=>{let q=_(f);return m(()=>{if(!q){w(X,null);return}let D=Z3(q,(M)=>{if(M.engine===_(X))return;w(X,M.engine,!0)});return()=>{D(),w(X,null)}})}),b(()=>{let q=_(S);if(!q)return;return m(()=>u0({ttsService:q.getServiceBundle().ttsService,listenerId:`timed-media-audio-handoff:${Y}`,silence:()=>J.requestMediaPauseForCompetingAudio()}))}),b(()=>{let q=W7()!=="force"&&_(Y7)?_(Y7).runtimeId:null,D=q?"inherited":"owned";if(D!==h8)h8=D,B7(D==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:Y,parentRuntimeId:q})}),b(()=>{let q=_(e),D=V()||"";W3(c8)}),b(()=>{if(!_(f)||!_(X1))return;return I7=new B3(_(f),{context:I8,initialValue:_(X1)}),I7.connect(),a7=new D3(_(f)),a7.attach(),()=>{a7?.detach(),a7=null,I7?.disconnect(),I7=null}}),b(()=>{if(!_(X1))return;I7?.setValue(_(X1))}),b(()=>{if(!_(f))return;_(f).setAttribute("data-item-player-type",_(w7).type),_(f).setAttribute("data-item-player-tag",_(w7).tagName),_(f).setAttribute("data-env-mode",String(_(u1)?.mode||"")),_(f).setAttribute("data-env-role",String(_(u1)?.role||""))}),b(()=>{if(!_(f)||!_(J1))return;return k7=new B3(_(f),{context:P3,initialValue:_(J1)}),k7.connect(),o7=new D3(_(f)),o7.attach(),()=>{o7?.detach(),o7=null,k7?.disconnect(),k7=null}}),b(()=>{if(_(J1))k7?.setValue(_(J1))}),b(()=>{return _(S),_(J7),_(e),r3(),()=>{o8()}}),b(()=>{if(!_(f))return;return p9({host:_(f),instrumentationProvider:_(h7),component:"pie-assessment-toolkit",eventMap:l9,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:_(J7),sectionId:_(e),attemptId:V()||void 0}})}),b(()=>{s7(),n7(),r7(),F();let q=_(S);if(!q)return;if(q!==_(d))return;m(()=>{q.setPnpEnforcement(d3(r7(),F())),q.updateAssessment(s7()),q.updateCurrentItemRef(n7())})}),b(()=>{if(!_(S))return;return _(S).subscribeTelemetry(({eventName:q,payload:D})=>{if(!d9(_(h7)))return;if(!_(h7).isReady())return;let M=q,z=new Date().toISOString(),A={...D||{},instrumentationLayer:"toolkit",assessmentId:_(J7),sectionId:_(e),attemptId:V()||void 0,component:"pie-assessment-toolkit",sourceEventName:q,timestamp:z};_(h7).trackEvent(M,A);let k=D&&typeof D.errorType==="string"?D.errorType:void 0;if(!q.endsWith("-error")&&!k)return;let o=D&&typeof D.message==="string"?D.message:`Toolkit telemetry error: ${q}`;_(h7).trackError(Error(o),{component:"pie-assessment-toolkit",errorType:k||"ToolkitTelemetryError",...A})})}),b(()=>{if(!B()||!_(S))return;let q=!1;return J.initialize({coordinator:_(S),section:B(),sectionId:_(e),assessmentId:_(J7),attemptId:V()||void 0,view:_(s3),createDefaultController:g3,onCompositionChanged:(D)=>{if(q)return;p1(D)},onControllerEvent:(D)=>{if(q)return;C3(D),b3(D)}}).then(()=>{if(q)return;B7("toolkit-ready",{runtimeId:Y,assessmentId:_(J7),sectionId:_(e),itemPlayer:_(w7),coordinator:_(S)}),B7("section-ready",{sectionId:_(e)}),m(()=>{w(h1,!0)})}).catch((D)=>{m(()=>{if(!_(t))w(t,!0),i.enter("engine-ready","skipped");i.enter("interactive","failed")}),w(e7,D,!0),J.reportSectionError({source:"section-runtime",error:D,timestamp:Date.now()}),v7({kind:"runtime-init",source:"pie-assessment-toolkit",error:D})}),()=>{q=!0}}),b(()=>{if(!_(f))return;let q=_(f),D=(z)=>o3(z.target);return a3(q,[{name:g0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.element||!A?.itemId)return;let k=J.register(A);if(Q1.set(A.element,A),a8(A),J.handleContentRegistered(A),k)p1()}},{name:c0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.itemId)return;let k=A?.element?J.unregister(A.element):!1;if(g1(A.element),A.element)Q1.delete(A.element);if(J.handleContentUnregistered(A),k)p1()}},{name:l0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.itemId)return;let k=J.updateItemSession(A.itemId,A.session);t8({itemId:A.itemId,canonicalItemId:J.getCanonicalItemId(A.itemId),result:k,fallbackSession:A.session})}},{name:d0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.itemId)return;J.handleContentLoaded({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,detail:A.detail,timestamp:Date.now()})}},{name:i0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.itemId)return;J.handleItemPlayerError({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,error:A.error,timestamp:Date.now()})}},{name:s0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.itemId)return;if(A.action!=="check"&&A.action!=="retry")return;J.handleFormativeAction({itemId:A.canonicalItemId||A.itemId,action:A.action,outcomes:A.outcomes})}},{name:n0,handler:(z)=>{if(!D(z))return;let A=D7(z);if(!A?.renderableId)return;if(A.action!=="attach"&&A.action!=="detach")return;J.handleMediaTimeSource({renderableId:A.renderableId,action:A.action,source:A.source,origin:A.origin})}}])});async function t3(){if(!_(S))throw Error("Coordinator not initialized");await _(S).waitUntilReady()}function e3(){if(!_(S))throw Error("Coordinator not initialized");return _(S).getServiceBundle()}function Q5(q){if(!_(S))throw Error("Coordinator not initialized");_(S).setHooks(q)}function G5(q){return J.navigateToItem(q)}function Y5(){return J.getCompositionModel()}function J5(){return _(w7)}async function X5(){await J.persist()}async function Z5(){await J.hydrate()}b(()=>{return()=>{m(()=>{if(i.getCurrent()!==null)i.enter("disposed")})}}),b(()=>{let q=`${U()}|${V()}`;m(()=>{if(q===_(l8))return;if(i.getCurrent()!==null)i.enter("disposed");i.reset({sectionId:U()||void 0,attemptId:V()||void 0}),w(l8,q),w(G1,!1),w(t,!1),w(v1,!1),w(h1,!1)})}),b(()=>{let q=_(t)&&_(h1);m(()=>{if(!q)return;if(_(v1))return;w(v1,!0),i.enter("interactive")})}),b(()=>{let q=_(t7)>0||_(y1)!==null;m(()=>{if(!_(G1)&&q)w(G1,!0),i.enter("composed")})}),b(()=>{if(!_(S))return;if(!_(G1))return;if(_(t))return;let q=_(S),D=!1;return q.waitUntilReady().then(()=>{if(D)return;m(()=>{if(_(t))return;w(t,!0),i.enter("engine-ready")})}).catch(()=>{if(D)return;m(()=>{if(_(t))return;w(t,!0),i.enter("engine-ready","failed")})}),()=>{D=!0}}),b(()=>{return()=>{g8.cancel(),J.dispose().catch((q)=>{w(e7,q,!0),v7({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:q,recoverable:!0})}).finally(()=>{j.dispose()})}});var j5={waitUntilReady:t3,getServiceBundle:e3,setHooks:Q5,navigateToItem:G5,getCompositionModel:Y5,getItemPlayerConfig:J5,persist:X5,hydrate:Z5,get assessmentId(){return W()},set assessmentId(q){W(q),y()},get section(){return B()},set section(q){B(q),y()},get sectionId(){return U()},set sectionId(q){U(q),y()},get attemptId(){return V()},set attemptId(q){V(q),y()},get env(){return H()},set env(q){H(q),y()},get ndsIcons(){return N()},set ndsIcons(q){N(q),y()},get locale(){return O()},set locale(q){O(q),y()},get lazyInit(){return P()},set lazyInit(q){P(q),y()},get toolConfigStrictness(){return $()},set toolConfigStrictness(q){$(q),y()},get tools(){return F()},set tools(q){F(q),y()},get toolContextResolvers(){return L()},set toolContextResolvers(q){L(q),y()},get enabledTools(){return C()},set enabledTools(q){C(q),y()},get toolRegistry(){return v()},set toolRegistry(q){v(q),y()},get accessibility(){return I()},set accessibility(q){I(q),y()},get player(){return p()},set player(q){p(q),y()},get playerType(){return E()},set playerType(q){E(q),y()},get coordinator(){return g()},set coordinator(q){g(q),y()},get createSectionController(){return j7()},set createSectionController(q){j7(q),y()},get onFrameworkError(){return K7()},set onFrameworkError(q){K7(q),y()},get errorRenderer(){return q7()},set errorRenderer(q){q7(q),y()},get onStageChange(){return $7()},set onStageChange(q){$7(q),y()},get assessment(){return s7()},set assessment(q){s7(q),y()},get currentItemRef(){return n7()},set currentItemRef(q){n7(q),y()},get pnpEnforcement(){return r7()},set pnpEnforcement(q){r7(q),y()},get isolation(){return W7()},set isolation(q){W7(q),y()}},e8=o9(),Q6=k8(e8);O3(Q6,(q)=>w(x7,q),()=>_(x7));var K5=C1(Q6,2);{var q5=(q)=>{var D=r9(),M=i7(D),z=i7(M,!0);d7(M);var A=C1(M,2),k=i7(A,!0);d7(A);var o=C1(A,2),Z1=i7(o,!0);d7(o),d7(D),H3((c1)=>{S1(z,_(x1)),S1(k,_(r).message),S1(Z1,c1)},[()=>_(f1).join(`
|
|
225
|
+
`)]),T1(q,D)},W5=(q)=>{var D=F3(),M=k8(D);N3(M,G,"default",{},null),T1(q,D)};A3(K5,(q)=>{if(_(r)&&!_(r).recoverable)q(q5);else q(W5,-1)})}return T1(Q,e8),V3(j5)}m9("pie-assessment-toolkit",z3(w3,{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"},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"},onStageChange:{type:"Object"},assessment:{type:"Object"},currentItemRef:{type:"Object"},pnpEnforcement:{attribute:"pnp-enforcement",type:"String"},isolation:{type:"Object"}},["default"],["waitUntilReady","getServiceBundle","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"}));export{w3 as default};
|