@pie-players/pie-section-player 0.3.73 → 0.3.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +395 -149
  2. package/dist/browser/assets/evaluation-worker-CORp9m0K.js +156459 -0
  3. package/dist/browser/chunks/ItemToolBar-jx38w99s-58defccc.js +1 -0
  4. package/dist/browser/chunks/PUA-tLuTiQ7--f2b27953.js +1 -0
  5. package/dist/browser/chunks/ToolCoordinator-cc2dc319.js +1 -0
  6. package/dist/browser/chunks/accents-BTUYmhn9-cafeb96e.js +1 -0
  7. package/dist/browser/chunks/accents-b-i-CngHZsLL-e0eb98fd.js +1 -0
  8. package/dist/browser/chunks/arabic-BzEHMVZD-30ac1ade.js +1 -0
  9. package/dist/browser/chunks/arrows-VjxlU-jv-2e17c192.js +1 -0
  10. package/dist/browser/chunks/base-dfd67c41.js +1 -0
  11. package/dist/browser/chunks/braille-BeWC_Ruq-a3bb8ef9.js +1 -0
  12. package/dist/browser/chunks/braille-d-Dk6J96GO-d832bfbf.js +1 -0
  13. package/dist/browser/chunks/browser-a3c32178.js +37 -0
  14. package/dist/browser/chunks/calculator-element-271c142f.js +13 -0
  15. package/dist/browser/chunks/calligraphic-Cew9cU3x-04cf0735.js +1 -0
  16. package/dist/browser/chunks/catalog-context-46d3e50e.js +1 -0
  17. package/dist/browser/chunks/catalog-owner-d602f784.js +1 -0
  18. package/dist/browser/chunks/cherokee-Cny3FYho-4da7d2f3.js +1 -0
  19. package/dist/browser/chunks/classPrivateFieldGet2-338e0179.js +1 -0
  20. package/dist/browser/chunks/cyrillic-CfCDulXU-5550df0b.js +1 -0
  21. package/dist/browser/chunks/cyrillic-ss-lU7bNGG9-12eb0188.js +1 -0
  22. package/dist/browser/chunks/defineProperty-a20a667d.js +1 -0
  23. package/dist/browser/chunks/devanagari-CDIz2h-r-18c38725.js +1 -0
  24. package/dist/browser/chunks/dist-41b39e7f.js +1 -0
  25. package/dist/browser/chunks/dist-59132a53.js +1 -0
  26. package/dist/browser/chunks/dist-60d7afef.js +1 -0
  27. package/dist/browser/chunks/dist-ca9b9622.js +1 -0
  28. package/dist/browser/chunks/double-struck-BpJEQk8y-500ce8dd.js +1 -0
  29. package/dist/browser/chunks/en-5ff22e17.js +1 -0
  30. package/dist/browser/chunks/es-a0ba6cb6.js +1 -0
  31. package/dist/browser/chunks/focus-trap-44913bf3.js +1 -0
  32. package/dist/browser/chunks/fraktur-rLEq9DEH-44cc14d8.js +1 -0
  33. package/dist/browser/chunks/greek-BlraJTyL-90ce8924.js +1 -0
  34. package/dist/browser/chunks/greek-ss-D-EN2PK0-91610739.js +1 -0
  35. package/dist/browser/chunks/hebrew-GiQZeybp-b583f555.js +1 -0
  36. package/dist/browser/chunks/latin-b-BhEnC7R2-d13e06ff.js +1 -0
  37. package/dist/browser/chunks/latin-bi-DqiIKv3U-1dec8705.js +1 -0
  38. package/dist/browser/chunks/latin-i-B1xtwaE1-21637466.js +1 -0
  39. package/dist/browser/chunks/latin-xfWFlLkD-5bcea5cf.js +1 -0
  40. package/dist/browser/chunks/logger-8b07fb72.js +1 -0
  41. package/dist/browser/chunks/marrows-DD1NgMQi-15b63755.js +1 -0
  42. package/dist/browser/chunks/math-DpWn1mbG-38eeb914.js +1 -0
  43. package/dist/browser/chunks/math-rendering-ready-9a0fd90a.js +1 -0
  44. package/dist/browser/chunks/mathjax-BKrHE4xs-3ca05bf6.js +232 -0
  45. package/dist/browser/chunks/module-0191e321.js +74 -0
  46. package/dist/browser/chunks/module-shim-58659a86.js +0 -0
  47. package/dist/browser/chunks/module-shim-b4470740.js +12 -0
  48. package/dist/browser/chunks/monospace-D116QD2a-98d484fd.js +1 -0
  49. package/dist/browser/chunks/monospace-ex-DcXpouKS-456b403c.js +1 -0
  50. package/dist/browser/chunks/monospace-l-Ct5wkMDs-f34a4a9e.js +1 -0
  51. package/dist/browser/chunks/mshapes-DCp86WSX-c0055952.js +1 -0
  52. package/dist/browser/chunks/nl-NL-364d61b9.js +1 -0
  53. package/dist/browser/chunks/nl-NL-8b7e6d4b.js +1 -0
  54. package/dist/browser/chunks/overlay-containment-edaaff13.js +1 -0
  55. package/dist/browser/chunks/overlay-placement-e8058232.js +1 -0
  56. package/dist/browser/chunks/phonetics-BwOCw2Y9-d2e3af59.js +1 -0
  57. package/dist/browser/chunks/phonetics-ss-CRtMn02f-579b6135.js +1 -0
  58. package/dist/browser/chunks/pie-api-client-687c319a.js +1 -0
  59. package/dist/browser/chunks/pointer-gesture-ce75f0a7.js +1 -0
  60. package/dist/browser/chunks/preload-helper-6ad28da3.js +1 -0
  61. package/dist/browser/chunks/provider-4c704118.js +1 -0
  62. package/dist/browser/chunks/rolldown-runtime-1287ba31.js +1 -0
  63. package/dist/browser/chunks/runtime-wcU7KOFU-ac86d7b8.js +8536 -0
  64. package/dist/browser/chunks/sanitize-svg-icon-b9082bba.js +3 -0
  65. package/dist/browser/chunks/sans-serif-BYPZKlE9-2efdbcd9.js +1 -0
  66. package/dist/browser/chunks/sans-serif-b-B0kRKiC--b5530dce.js +1 -0
  67. package/dist/browser/chunks/sans-serif-bi-DXWul6mu-5370dba4.js +1 -0
  68. package/dist/browser/chunks/sans-serif-ex-Boux1kMP-aa178f31.js +1 -0
  69. package/dist/browser/chunks/sans-serif-i-676RFaSO-2db54474.js +1 -0
  70. package/dist/browser/chunks/sans-serif-r-DrN9xdZt-0fc72eea.js +1 -0
  71. package/dist/browser/chunks/script-0ohehnXc-526904f4.js +1 -0
  72. package/dist/browser/chunks/shapes-BG47NodJ-d59b0eca.js +1 -0
  73. package/dist/browser/chunks/src-BcptuNS5-ed25d7fd.js +191 -0
  74. package/dist/browser/chunks/sre-0162a7a9.js +53 -0
  75. package/dist/browser/chunks/sre-engine-ace23548.js +1 -0
  76. package/dist/browser/chunks/sre-engine-jd8cc08x-42d270e5.js +1 -0
  77. package/dist/browser/chunks/sre-locales-112320af.js +1 -0
  78. package/dist/browser/chunks/symbols-BqnUxf_t-83087e87.js +1 -0
  79. package/dist/browser/chunks/symbols-b-i-eg9k5hmF-9c461ac2.js +1 -0
  80. package/dist/browser/chunks/tool-annotation-toolbar-997438b4.js +249 -0
  81. package/dist/browser/chunks/tool-answer-eliminator-35483abd.js +13 -0
  82. package/dist/browser/chunks/tool-color-scheme-b7de5cdf.js +26 -0
  83. package/dist/browser/chunks/tool-dictionary-cecff3b4.js +7 -0
  84. package/dist/browser/chunks/tool-graph-cb0338e8.js +11 -0
  85. package/dist/browser/chunks/tool-host-contract-b93b482c.js +1 -0
  86. package/dist/browser/chunks/tool-instance-id-2a92deb0.js +1 -0
  87. package/dist/browser/chunks/tool-line-reader-f8ef3c6a.js +62 -0
  88. package/dist/browser/chunks/tool-periodic-table-43b133b8.js +153 -0
  89. package/dist/browser/chunks/tool-picture-dictionary-33721e91.js +4 -0
  90. package/dist/browser/chunks/tool-protractor-23f77028.js +17 -0
  91. package/dist/browser/chunks/tool-ruler-1d9a03a6.js +15 -0
  92. package/dist/browser/chunks/tool-tts-inline-98c2ce7a.js +179 -0
  93. package/dist/browser/chunks/tts-runtime-config-a7ab1ad4.js +194 -0
  94. package/dist/browser/chunks/variants-2LRNhOUP-966fc49d.js +1 -0
  95. package/dist/browser/chunks/versioned-tag-54a76be9.js +1 -0
  96. package/dist/browser/pie-section-player.js +1727 -0
  97. package/dist/browser.d.ts +10 -0
  98. package/dist/chunks/ItemToolBar-jx38w99s-1287ba31.js +28 -0
  99. package/dist/chunks/module-shim-58659a86.js +2129 -0
  100. package/dist/chunks/{nl-NL-9312c316.js → nl-NL-364d61b9.js} +9 -26
  101. package/dist/chunks/sre-engine-jd8cc08x-42d270e5.js +8 -0
  102. package/dist/components/shared/composition.d.ts +3 -2
  103. package/dist/components/shared/framework-error-latch.d.ts +32 -0
  104. package/dist/components/shared/host-element.d.ts +10 -0
  105. package/dist/components/shared/kernel-host-default-body.d.ts +14 -0
  106. package/dist/components/shared/layout-host-methods.d.ts +385 -0
  107. package/dist/components/shared/missing-tool-providers.d.ts +16 -0
  108. package/dist/components/shared/player-preload.d.ts +14 -10
  109. package/dist/components/shared/section-player-backend-delivery.d.ts +1 -1
  110. package/dist/components/shared/section-player-card-context.d.ts +5 -1
  111. package/dist/components/shared/section-player-host-runtime.d.ts +32 -19
  112. package/dist/components/shared/section-player-layout-context.d.ts +77 -0
  113. package/dist/components/shared/section-player-own-event.d.ts +10 -0
  114. package/dist/components/shared/section-player-runtime-callbacks.d.ts +1 -1
  115. package/dist/components/shared/section-player-shell-layout.svelte.d.ts +3 -11
  116. package/dist/components/shared/section-player-view-state.d.ts +6 -1
  117. package/dist/components/shared/toolkit-ready-wait.d.ts +16 -0
  118. package/dist/contracts/host-hooks.d.ts +4 -12
  119. package/dist/contracts/host-hooks.js +0 -0
  120. package/dist/contracts/runtime-host-contract.d.ts +0 -5
  121. package/dist/contracts/runtime-host-contract.js +0 -0
  122. package/dist/controllers/SectionController.d.ts +14 -0
  123. package/dist/controllers/toolkit-section-contracts.d.ts +1 -17
  124. package/dist/controllers/types.d.ts +25 -11
  125. package/dist/item-section/index.d.ts +22 -0
  126. package/dist/item-section/index.js +37 -0
  127. package/dist/pie-section-player.d.ts +4 -6
  128. package/dist/pie-section-player.js +22006 -41076
  129. package/dist/policies/index.d.ts +5 -16
  130. package/dist/policies/index.js +17 -0
  131. package/dist/policies/types.d.ts +0 -4
  132. package/package.json +33 -68
  133. package/dist/chunks/module-a516757f.js +0 -73997
  134. package/dist/chunks/nl-NL-ef6dd604.js +0 -505
  135. package/dist/chunks/pie-api-client-22de9d9c.js +0 -168
  136. package/dist/chunks/rolldown-runtime-1287ba31.js +0 -20
  137. package/dist/chunks/sre-0162a7a9.js +0 -17637
  138. package/dist/components/item-shell-element.d.ts +0 -1
  139. package/dist/components/shared/shell-registration.d.ts +0 -55
  140. package/dist/contracts/layout-contract.d.ts +0 -17
  141. package/dist/contracts/layout-parity-metadata.d.ts +0 -4
  142. package/dist/contracts/public-events.d.ts +0 -93
  143. package/dist/contracts/stages.d.ts +0 -10
  144. package/dist/policies/guards.d.ts +0 -2
  145. package/dist/utils/z-index.d.ts +0 -5
@@ -0,0 +1,1727 @@
1
+ import{t as xt}from"./chunks/rolldown-runtime-1287ba31.js";import{t as T}from"./chunks/defineProperty-a20a667d.js";import{a as Eu,i as Me,n as xe,r as ze,t as w}from"./chunks/classPrivateFieldGet2-338e0179.js";import{c as MA,d as Rw,f as OA,h as Eb,l as Cu,m as ja,o as Vl,p as LA,r as sf,s as NA,t as DA,u as af}from"./chunks/tool-host-contract-b93b482c.js";import{a as Ra,i as jA,n as ET,r as zA,t as dp}from"./chunks/versioned-tag-54a76be9.js";import{n as za,r as xu,t as ei}from"./chunks/logger-8b07fb72.js";import{t as Mr}from"./chunks/preload-helper-6ad28da3.js";import{a as bm,i as BA,r as Cb,t as xb}from"./chunks/tool-instance-id-2a92deb0.js";import{r as FA,t as HA}from"./chunks/ItemToolBar-jx38w99s-58defccc.js";import{t as Kf}from"./chunks/sanitize-svg-icon-b9082bba.js";import{t as UA}from"./chunks/pointer-gesture-ce75f0a7.js";import{i as qA,n as WA,r as VA,t as GA}from"./chunks/focus-trap-44913bf3.js";import{a as YA,i as Ba,n as KA,o as Pw,r as XA}from"./chunks/provider-4c704118.js";import{a as JA,i as QA,n as ZA,o as hg,r as _w,t as e$}from"./chunks/tts-runtime-config-a7ab1ad4.js";import{n as Rv,t as CT}from"./chunks/catalog-owner-d602f784.js";import{A as lf,C as xT,D as Ro,E as Od,O as t$,S as Ee,T as Rb,_ as RT,a as r$,b as wm,d as PT,f as n$,g as cf,h as i$,i as _T,k as Sm,l as o$,m as s$,n as Wc,p as a$,r as l$,s as c$,t as Pb,u as u$,v as AT,w as $T,x as d$,y as f$}from"./chunks/math-rendering-ready-9a0fd90a.js";if(typeof window<"u"){var Aw,$w;((Aw=($w=window).__svelte??($w.__svelte={})).v??(Aw.v=new Set)).add("5")}var ru={},vn=Symbol("uninitialized");var h$="http://www.w3.org/2000/svg";var Im=Array.isArray,p$=Array.prototype.indexOf,fp=Array.prototype.includes,km=Array.from,hp=Object.keys,Ld=Object.defineProperty,xl=Object.getOwnPropertyDescriptor,MT=Object.getOwnPropertyDescriptors,m$=Object.prototype,g$=Array.prototype,_b=Object.getPrototypeOf,Mw=Object.isExtensible,v$=()=>{};function y$(e){for(var t=0;t<e.length;t++)e[t]()}function OT(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}var b$=1<<24,po=1024,Yi=2048,cc=4096,Ab=8192,w$=16384,$b=32768,Ow=1<<25,uf=65536,uK=1<<17,dK=1<<18,Ru=1<<19,S$=1<<20,wd=1<<25,Lw=1<<21,I$=1<<22,pp=1<<23,Ws=Symbol("$state"),LT=Symbol("component"),NT=Symbol("legacy props"),k$=Symbol(""),T$=Symbol("proxy path"),Pv=Symbol("attributes"),_v=Symbol("class"),Av=Symbol("style"),Bh=Symbol("text"),DT=Symbol("form reset");var df=new class extends Error{constructor(...t){super(...t),T(this,"name","StaleReactionError"),T(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Tm=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function E$(){console.warn("https://svelte.dev/e/derived_inert")}function Em(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function C$(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function x$(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var It=!1;function ci(e){It=e}var cr;function Bn(e){if(e===null)throw Em(),ru;return cr=e}function Gl(){return Bn(_s(cr))}function Tr(e){if(It){if(_s(cr)!==null)throw Em(),ru;cr=e}}function R$(e=1){if(It){for(var t=e,r=cr;t--;)r=_s(r);cr=r}}function mp(e=!0){for(var t=0,r=cr;;){if(r.nodeType===8){var n=r.data;if(n==="]"){if(t===0)return r;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=_s(r);e&&r.remove(),r=i}}function jT(e){if(!e||e.nodeType!==8)throw Em(),ru;return e.data}function zT(e){return e===this.v}function BT(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function FT(e){return!BT(e,this.v)}function Mb(){throw new Error("https://svelte.dev/e/invalid_default_snippet")}function HT(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function P$(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function _$(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function A$(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function $$(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function M$(e){throw new Error("https://svelte.dev/e/effect_orphan")}function O$(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function L$(){throw new Error("https://svelte.dev/e/hydration_failed")}function N$(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function D$(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function j$(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function z$(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function B$(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var Fa=!1,ff=!1;function Nw(e,t){return e.label=t,F$(e.v,t),e}function F$(e,t){return e?.[T$]?.(t),e}var Qr=null;function nu(e){Qr=e}function pn(e,t=!1,r){Qr={p:Qr,i:!1,c:null,e:null,s:e,x:null,r:Bt,l:ff&&!t?{s:null,u:null,$:[]}:null}}function mn(e){var t=Qr,r=t.e;if(r!==null){t.e=null;for(var n of r)fE(n)}return e!==void 0&&(t.x=e),t.i=!0,Qr=t.p,Ob(e)}function Ob(e={}){return Ld(e,LT,{value:!0}),e}function hf(){return!ff||Qr!==null&&Qr.l===null}var pl=[];function UT(){var e=pl;pl=[],y$(e)}function Xo(e){if(pl.length===0&&!Sd){var t=pl;queueMicrotask(()=>{t===pl&&UT()})}pl.push(e)}function H$(){for(;pl.length>0;)UT()}var U$=~(Yi|cc|po);function un(e,t){e.f=e.f&U$|t}function Lb(e){(e.f&512)!==0||e.deps===null?un(e,po):un(e,cc)}function qT(e,t,r){(e.f&2048)!==0?t.add(e):(e.f&4096)!==0&&r.add(e),un(e,po)}function q$(e,t){if(t){const r=document.body;e.autofocus=!0,Xo(()=>{document.activeElement===r&&e.focus()})}}var Dw=!1;function W$(){Dw||(Dw=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{if(!e.defaultPrevented)for(const t of e.target.elements)t[DT]?.()})},{capture:!0}))}function pf(e){var t=ar,r=Bt;Ei(null),mo(null);try{return e()}finally{Ei(t),mo(r)}}function WT(e,t,r,n){const i=hf()?Nd:Nb;var o=e.filter(h=>!h.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=Bt,l=V$(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(h=>h.promise)):null;function u(h){if((a.f&16384)===0){l();try{n([...s,...h])}catch(g){Is(g,a)}gp()}}var d=VT();if(r.length===0){c.then(()=>u([])).finally(d);return}function f(){Promise.all(r.map(h=>Y$(h))).then(u).catch(h=>Is(h,a)).finally(d)}c?c.then(()=>{l(),f(),gp()}):f()}function V$(){var e=Bt,t=ar,r=Qr,n=Kt;if(0)var i;return function(s=!0){mo(e),Ei(t),nu(r),s&&(e.f&16384)===0&&(n?.activate(),n?.apply())}}var G$=!1;function gp(e=!0){G$=!1,mo(null),Ei(null),nu(null),e&&Kt?.deactivate()}function VT(){var e=Bt,t=e.b,r=Kt,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}function Nd(e){var t=2|Yi;return Bt!==null&&(Bt.f|=Ru),{ctx:Qr,deps:null,effects:null,equals:zT,f:t,fn:e,reactions:null,rv:0,v:vn,wv:0,parent:Bt,ac:null}}var id=Symbol("obsolete");function Y$(e,t,r){let n=Bt;n===null&&P$();var i=void 0,o=Kl(vn),s=!ar,a=new Set;return dM(()=>{var l=Bt,c=OT();i=c.promise;try{Promise.resolve(e()).then(c.resolve,h=>{h!==df&&c.reject(h)}).finally(gp)}catch(h){c.reject(h),gp()}var u=Kt;if(s){if((l.f&32768)!==0)var d=VT();if(n.b?.is_rendered())u.async_deriveds.get(l)?.reject(id);else for(const h of a.values())h.reject(id);a.add(c),u.async_deriveds.set(l,c)}const f=(h,g=void 0)=>{d?.(),a.delete(c),g!==id&&(u.activate(),g?(o.f|=pp,iu(o,g)):((o.f&8388608)!==0&&(o.f^=pp),iu(o,h)),u.deactivate())};c.promise.then(f,h=>f(null,h||"unknown"))}),xm(()=>{for(const l of a)l.reject(id)}),new Promise(l=>{function c(u){function d(){u===i?l(o):c(i)}u.then(d,d)}c(i)})}function q(e){const t=Nd(e);return Fa||yE(t),t}function Nb(e){const t=Nd(e);return t.equals=FT,t}function K$(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)Fn(t[r])}}function Db(e){var t,r=Bt,n=e.parent;if(!Zs&&n!==null&&e.v!==vn&&(n.f&24576)!==0)return E$(),e.v;mo(n);try{K$(e),t=IE(e)}finally{mo(r)}return t}function GT(e){var t=Db(e);if(!e.equals(t)&&(e.wv=wE(),(!Kt?.is_fork||e.deps===null)&&(Kt!==null?(Kt.capture(e,t,!0),$v?.capture(e,t,!0)):e.v=t,e.deps===null))){un(e,po);return}Zs||(si!==null?(Bb()||Kt?.is_fork)&&si.set(e,t):Lb(e))}function X$(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&pf(()=>{t.ac.abort(df),t.ac=null}),t.fn!==null&&(t.teardown=v$),jd(t,0),Fb(t))}function YT(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&ou(t)}var KT,vp=null,Ac=null,Kt=null,$v=null,si=null,Mv=null,Sd=!1,pg=!1,Dd=null,yp=null,XT=0;var J$=1,bp=new WeakMap,Rl=new WeakMap,ml=new WeakMap,wp=new WeakMap,Xf=new WeakMap,$c=new WeakMap,sl=new WeakMap,od=new WeakMap,Po=new WeakMap,Ov=new WeakMap,Yl=new WeakMap,Vs=new WeakMap,Ia=new WeakMap,Fh=new WeakMap,sd=new WeakMap,tn=new WeakSet,uc=class JT{constructor(){Eu(this,tn),T(this,"id",J$++),Me(this,bp,!1),T(this,"linked",!0),Me(this,Rl,null),Me(this,ml,null),T(this,"async_deriveds",new Map),T(this,"current",new Map),T(this,"previous",new Map),Me(this,wp,new Set),Me(this,Xf,new Set),Me(this,$c,0),Me(this,sl,new Map),Me(this,od,null),Me(this,Po,[]),Me(this,Ov,[]),Me(this,Yl,new Set),Me(this,Vs,new Set),Me(this,Ia,new Map),Me(this,Fh,new Set),T(this,"is_fork",!1),Me(this,sd,!1),Ac===null?vp=Ac=this:(xe(ml,Ac,this),xe(Rl,this,Ac)),Ac=this}skip_effect(t){w(Ia,this).has(t)||w(Ia,this).set(t,{d:[],m:[]}),w(Fh,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=w(Ia,this).get(t);if(n){w(Ia,this).delete(t);for(var i of n.d)un(i,Yi),r(i);for(i of n.m)un(i,cc),r(i)}w(Fh,this).add(t)}capture(t,r,n=!1){t.v!==vn&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&8388608)===0&&(this.current.set(t,[r,n]),si?.set(t,r)),this.is_fork||(t.v=r)}activate(){Kt=this}deactivate(){Kt=null,si=null}flush(){try{pg=!0,Kt=this,ze(tn,this,Sp).call(this)}finally{XT=0,Mv=null,Dd=null,yp=null,pg=!1,Kt=null,si=null,Ss.clear()}}discard(){for(const t of w(Xf,this))t(this);w(Xf,this).clear();for(const t of this.async_deriveds.values())t.reject(id);ze(tn,this,Ip).call(this),w(od,this)?.resolve()}register_created_effect(t){w(Ov,this).push(t)}increment(t,r){if(xe($c,this,w($c,this)+1),t){let n=w(sl,this).get(r)??0;w(sl,this).set(r,n+1)}}decrement(t,r){if(xe($c,this,w($c,this)-1),t){let n=w(sl,this).get(r)??0;n===1?w(sl,this).delete(r):w(sl,this).set(r,n-1)}w(sd,this)||(xe(sd,this,!0),Xo(()=>{xe(sd,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)w(Yl,this).add(n);for(const n of r)w(Vs,this).add(n);t.clear(),r.clear()}oncommit(t){w(wp,this).add(t)}ondiscard(t){w(Xf,this).add(t)}settled(){return(w(od,this)??xe(od,this,OT())).promise}static ensure(){if(Kt===null){const t=Kt=new JT;!pg&&!Sd&&Xo(()=>{w(bp,t)||t.flush()})}return Kt}apply(){if(!Fa||!this.is_fork&&w(Rl,this)===null&&w(ml,this)===null){si=null;return}si=new Map;for(const[r,[n]]of this.current)si.set(r,n);for(let r=vp;r!==null;r=w(ml,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(const[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(const[n,i]of r.previous)si.has(n)||si.set(n,i)}}schedule(t){if(Mv=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}w(Po,this).push(t)}};KT=uc;function jw(){if(this.is_fork)return!0;for(const r of w(sl,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(w(Ia,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function QT(){var e=[];for(const i of w(Po,this))if(!((i.f&16384)!==0||(i.f&6144)===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&96)!==0){if((n&1024)===0){r=!0;break}t.f^=po}}r||e.push(t)}return xe(Po,this,[]),e}function Sp(){xe(bp,this,!0);for(const s of w(Yl,this))w(Vs,this).delete(s),un(s,Yi),this.schedule(s);for(const s of w(Vs,this))un(s,cc),this.schedule(s);this.apply();for(var e=Dd=[],t=[],r=yp=[];w(Po,this).length>0;){XT++>1e3&&(ze(tn,this,Ip).call(this),tM());for(const s of ze(tn,this,QT).call(this))try{ze(tn,this,ZT).call(this,s,e,t)}catch(a){throw rE(s),ze(tn,this,jw).call(this)||this.discard(),a}}if(Kt=null,r.length>0){var n=KT.ensure();for(const s of r)n.schedule(s)}if(Dd=null,yp=null,ze(tn,this,jw).call(this)){ze(tn,this,ad).call(this,t),ze(tn,this,ad).call(this,e);for(const[s,a]of w(Ia,this))tE(s,a);r.length>0&&ze(tn,Kt,Sp).call(Kt);return}const i=ze(tn,this,Q$).call(this);if(i){ze(tn,this,ad).call(this,t),ze(tn,this,ad).call(this,e),ze(tn,i,Z$).call(i,this);return}w(Yl,this).clear(),w(Vs,this).clear();for(const s of w(wp,this))s(this);w(wp,this).clear(),$v=this,zw(t),zw(e),$v=null,w(od,this)?.resolve();var o=Kt;if(w($c,this)===0&&(w(Po,this).length===0||o!==null)&&(ze(tn,this,Ip).call(this),Fa&&(ze(tn,this,eM).call(this),Kt=o)),w(Po,this).length>0)if(o!==null){for(const s of w(Po,this))w(Po,o).push(s);xe(Po,this,[])}else o=this;o!==null&&(Ss.clear(),ze(tn,o,Sp).call(o))}function ZT(e,t,r){e.f^=po;for(var n=e.first;n!==null;){var i=n.f,o=(i&96)!==0;if(!(o&&(i&1024)!==0||(i&8192)!==0||w(Ia,this).has(n))&&n.fn!==null){o?n.f^=po:(i&4)!==0?t.push(n):Fa&&(i&16777224)!==0?r.push(n):yf(n)&&((i&16)!==0&&w(Vs,this).add(n),ou(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function Q$(){for(var e=w(Rl,this);e!==null;){if(!e.is_fork){for(const[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=w(Rl,e)}return null}function Z$(e){for(const[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(const[r,n]of e.async_deriveds){const i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(w(Yl,e),w(Vs,e));const t=r=>{var n=r.reactions;if(n!==null&&!((r.f&2)!==0&&(r.f&6144)===0))for(const s of n){var i=s.f;if((i&2)!==0)t(s);else{var o=s;i&4194320&&!this.async_deriveds.has(o)&&(w(Vs,this).delete(o),un(o,Yi),this.schedule(o))}}};for(const r of this.current.keys())t(r);this.oncommit(()=>e.discard()),ze(tn,e,Ip).call(e),Kt=this,ze(tn,this,Sp).call(this)}function ad(e){for(var t=0;t<e.length;t+=1)qT(e[t],w(Yl,this),w(Vs,this))}function eM(){for(let u=vp;u!==null;u=w(ml,u)){var e=u.id<this.id,t=[];for(const[d,[f,h]]of this.current){if(u.current.has(d)){var r=u.current.get(d)[0];if(e&&f!==r)u.current.set(d,[f,h]);else continue}t.push(d)}if(e)for(const[d,f]of this.async_deriveds){const h=u.async_deriveds.get(d);h&&f.promise.then(h.resolve).catch(h.reject)}var n=[...u.current.keys()].filter(d=>!u.current.get(d)[1]);if(!(!w(bp,u)||n.length===0)){var i=n.filter(d=>!this.current.has(d));if(i.length===0)e&&u.discard();else if(t.length>0){if(e)for(const d of w(Fh,this))u.unskip_effect(d,f=>{(f.f&4194320)!==0?u.schedule(f):ze(tn,u,ad).call(u,[f])});u.activate();var o=new Set,s=new Map;for(var a of t)eE(a,i,o,s);s=new Map;var l=[...u.current].filter(([d,f])=>{const h=this.current.get(d);return h?h[0]!==f[0]||h[1]!==f[1]:!0}).map(([d])=>d);if(l.length>0)for(const d of w(Ov,this))(d.f&155648)===0&&jb(d,l,s)&&((d.f&4194320)!==0?(un(d,Yi),u.schedule(d)):w(Yl,u).add(d));if(w(Po,u).length>0&&!w(sd,u)){u.apply();for(var c of ze(tn,u,QT).call(u))ze(tn,u,ZT).call(u,c,[],[])}u.deactivate()}}}}function Ip(){if(this.linked){var e=w(Rl,this),t=w(ml,this);e===null?vp=t:xe(ml,e,t),t===null?Ac=e:xe(Rl,t,e),this.linked=!1}}function N(e){var t=Sd;Sd=!0;try{var r;for(e&&(Kt!==null&&!Kt.is_fork&&Kt.flush(),r=e());;){if(H$(),Kt===null)return r;Kt.flush()}}finally{Sd=t}}function tM(){if(0){var e;for(const r of Kt.current.keys())for(const[n,i]of r.updated??[])var t}try{O$()}catch(r){Is(r,Mv)}}var fs=null;function zw(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&24576)===0&&yf(n)&&(fs=new Set,ou(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&mE(n),fs?.size>0)){Ss.clear();for(const i of fs){if((i.f&24576)!==0)continue;const o=[i];let s=i.parent;for(;s!==null;)fs.has(s)&&(fs.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){const l=o[a];(l.f&24576)===0&&ou(l)}}fs.clear()}}fs=null}}function eE(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const i of e.reactions){const o=i.f;(o&2)!==0?eE(i,t,r,n):(o&4194320)!==0&&(o&2048)===0&&jb(i,t,n)&&(un(i,Yi),zb(i))}}function jb(e,t,r){const n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(const i of e.deps){if(fp.call(t,i))return!0;if((i.f&2)!==0&&jb(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function zb(e){Kt.schedule(e)}function tE(e,t){if(!((e.f&32)!==0&&(e.f&1024)!==0)){(e.f&2048)!==0?t.d.push(e):(e.f&4096)!==0&&t.m.push(e),un(e,po);for(var r=e.first;r!==null;)tE(r,t),r=r.next}}function rE(e){un(e,po);for(var t=e.first;t!==null;)rE(t),t=t.next}var kp=new Set,Ss=new Map;var nE=!1;function Kl(e,t){var r={f:0,v:e,reactions:null,equals:zT,rv:0,wv:0};return r}function Be(e,t){const r=Kl(e,t);return yE(r),r}function iE(e,t=!1,r=!0){const n=Kl(e);if(t||(n.equals=FT),ff&&r&&Qr!==null&&Qr.l!==null){var i;((i=Qr.l).s??(i.s=[])).push(n)}return n}function be(e,t,r=!1){ar!==null&&(!Mo||(ar.f&131072)!==0)&&hf()&&(ar.f&4325394)!==0&&(Bo===null||!Bo.has(e))&&z$();let n=r?ui(t):t;return iu(e,n,yp)}var ul=null,Lv=0;function iu(e,t,r=null){if(!e.equals(t)){Zs?Ss.set(e,t):Ss.has(e)||Ss.set(e,e.v);var n=uc.ensure();if(n.capture(e,t),(e.f&2)!==0){const i=e;(e.f&2048)!==0&&Db(i),si===null&&Lb(i)}e.wv=wE(),ul=null,Lv=0,oE(e,Yi,r),ul=null,hf()&&Bt!==null&&(Bt.f&1024)!==0&&(Bt.f&96)===0&&(no===null?mM([e]):no.push(e)),!n.is_fork&&kp.size>0&&!nE&&rM()}return t}function rM(){nE=!1;for(const e of kp){(e.f&1024)!==0&&un(e,cc);let t;try{t=yf(e)}catch{t=!0}t&&ou(e)}kp.clear()}function Id(e){be(e,e.v+1)}function oE(e,t,r){var n=e.reactions;if(n!==null){var i=hf(),o=n.length;if(Lv+=o,Lv>1e5&&ul===null&&(ul=new Set),ul!==null){if(ul.has(e))return;ul.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Bt)){var c=(l&Yi)===0;if(c&&un(a,t),(l&131072)!==0)kp.add(a);else if((l&2)!==0){var u=a;si?.delete(u),oE(u,cc,r)}else if(c){var d=a;(l&16)!==0&&fs!==null&&fs.add(d),r!==null?r.push(d):zb(d)}}}}}var nM=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function ui(e){if(typeof e!="object"||e===null||Ws in e||LT in e)return e;const t=_b(e);if(t!==m$&&t!==g$)return e;var r=new Map,n=Im(e),i=Be(0),o=null,s=Pl,a=d=>{if(Pl===s)return d();var f=ar,h=Pl;Ei(null),Uw(s);var g=d();return Ei(f),Uw(h),g};n&&r.set("length",Be(e.length,o));var l="";let c=!1;function u(d){if(!c){c=!0,l=d,Nw(i,`${l} version`);for(const[f,h]of r)Nw(h,iM(l,f));c=!1}}return new Proxy(e,{defineProperty(d,f,h){(!("value"in h)||h.configurable===!1||h.enumerable===!1||h.writable===!1)&&D$();var g=r.get(f);return g===void 0?a(()=>{var m=Be(h.value,o);return r.set(f,m),m}):be(g,h.value,!0),!0},deleteProperty(d,f){var h=r.get(f);if(h===void 0){if(f in d){const g=a(()=>Be(vn,o));r.set(f,g),Id(i)}}else be(h,vn),Id(i);return!0},get(d,f,h){if(f===Ws)return e;var g=r.get(f),m=f in d;if(g===void 0&&(!m||xl(d,f)?.writable)&&(g=a(()=>{var b=ui(m?d[f]:vn),I=Be(b,o);return I}),r.set(f,g)),g!==void 0){var v=p(g);return v===vn?void 0:v}return Reflect.get(d,f,h)},getOwnPropertyDescriptor(d,f){this.has?.(d,f);var h=Reflect.getOwnPropertyDescriptor(d,f),g=r.get(f);if(g!==void 0){var m=p(g);if(m===vn)return;if(h&&"value"in h)h.value=m;else return{enumerable:!0,configurable:!0,value:m,writable:!0}}return h},has(d,f){if(f===Ws)return!0;var h=r.get(f),g=h!==void 0&&h.v!==vn||Reflect.has(d,f);return(h!==void 0||Bt!==null&&(!g||xl(d,f)?.writable))&&(h===void 0&&(h=a(()=>{var m=g?ui(d[f]):vn,v=Be(m,o);return v}),r.set(f,h)),p(h)===vn)?!1:g},set(d,f,h,g){var m=r.get(f),v=f in d;if(n&&f==="length")for(var b=h;b<m.v;b+=1){var I=r.get(b+"");I!==void 0?be(I,vn):b in d&&(I=a(()=>Be(vn,o)),r.set(b+"",I))}if(m===void 0)(!v||xl(d,f)?.writable)&&(m=a(()=>Be(void 0,o)),be(m,ui(h)),r.set(f,m));else{v=m.v!==vn;var C=a(()=>ui(h));be(m,C)}var x=Reflect.getOwnPropertyDescriptor(d,f);if(x?.set&&x.set.call(g,h),!v){if(n&&typeof f=="string"){var $=r.get("length"),P=Number(f);Number.isInteger(P)&&P>=$.v&&be($,P+1)}Id(i)}return!0},ownKeys(d){p(i);var f=Reflect.ownKeys(d).filter(m=>{var v=r.get(m);return v===void 0||v.v!==vn});for(var[h,g]of r)g.v!==vn&&!(h in d)&&f.push(h);return f},setPrototypeOf(){j$()}})}function iM(e,t){return typeof t=="symbol"?`${e}[Symbol(${t.description??""})]`:nM.test(t)?`${e}.${t}`:/^\d+$/.test(t)?`${e}[${t}]`:`${e}['${t}']`}function Bw(e){try{if(e!==null&&typeof e=="object"&&Ws in e)return e[Ws]}catch{}return e}function sE(e,t){return Object.is(Bw(e),Bw(t))}var Fw,oM,aE,lE,cE;function Nv(){if(Fw===void 0){Fw=window,oM=document,aE=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;lE=xl(t,"firstChild").get,cE=xl(t,"nextSibling").get,Mw(e)&&(e[_v]=void 0,e[Pv]=null,e[Av]=void 0,e.__e=void 0),Mw(r)&&(r[Bh]=void 0)}}function Jn(e=""){return document.createTextNode(e)}function Qs(e){return lE.call(e)}function _s(e){return cE.call(e)}function Er(e,t){if(!It)return Qs(e);var r=Qs(cr);if(r===null)r=cr.appendChild(Jn());else if(t&&r.nodeType!==3){var n=Jn();return r?.before(n),Bn(n),n}return t&&Cm(r),Bn(r),r}function bn(e,t=!1){if(!It){var r=Qs(e);return r instanceof Comment&&r.data===""?_s(r):r}if(t){if(cr?.nodeType!==3){var n=Jn();return cr?.before(n),Bn(n),n}Cm(cr)}return cr}function La(e,t=!1){if(!It)return Qs(e);var r=Er(e,t);return Tr(e),r}function mr(e,t=1,r=!1){let n=It?cr:e;for(var i;t--;)i=n,n=_s(n);if(!It)return n;if(r){if(n?.nodeType!==3){var o=Jn();return n===null?i?.after(o):n.before(o),Bn(o),o}Cm(n)}return Bn(n),n}function uE(e){e.textContent=""}function dE(){return!Fa||fs!==null?!1:(Bt.f&$b)!==0}function mf(e,t,r){return t==null||t==="http://www.w3.org/1999/xhtml"?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function Cm(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function sM(e){var t=Bt;if(t===null)return ar.f|=pp,e;if((t.f&32768)===0&&(t.f&4)===0)throw e;Is(e,t)}function Is(e,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function aM(e){Bt===null&&(ar===null&&M$(e),$$()),Zs&&A$(e)}function lM(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Qo(e,t){var r=Bt;r!==null&&(r.f&8192)!==0&&(e|=Ab);var n={ctx:Qr,deps:null,nodes:null,f:e|Yi|512,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};Kt?.register_created_effect(n);var i=n;if((e&4)!==0)Dd!==null?Dd.push(n):uc.ensure().schedule(n);else if(t!==null){try{ou(n)}catch(s){throw Fn(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&524288)===0&&(i=i.first,(e&16)!==0&&(e&65536)!==0&&i!==null&&(i.f|=uf))}if(i!==null&&(i.parent=r,r!==null&&lM(i,r),ar!==null&&(ar.f&2)!==0&&(e&64)===0)){var o=ar;(o.effects??(o.effects=[])).push(i)}return n}function Bb(){return ar!==null&&!Mo}function xm(e){const t=Qo(8,null);return un(t,po),t.teardown=e,t}function vt(e){aM("$effect");var t=Bt.f;if(!ar&&(t&32)!==0&&Qr!==null&&!Qr.i){var r=Qr;(r.e??(r.e=[])).push(e)}else return fE(e)}function fE(e){return Qo(4|S$,e)}function cM(e){uc.ensure();const t=Qo(64|Ru,e);return()=>{Fn(t)}}function uM(e){uc.ensure();const t=Qo(64|Ru,e);return(r={})=>new Promise(n=>{r.outro?dc(t,()=>{Fn(t),n(void 0)}):(Fn(t),n(void 0))})}function gf(e){return Qo(4,e)}function dM(e){return Qo(I$|Ru,e)}function Rm(e,t=0){return Qo(8|t,e)}function ve(e,t=[],r=[],n=[]){WT(n,t,r,i=>{Qo(8,()=>{e(...i.map(p))})})}function vf(e,t=0){var r=Qo(16|t,e);return r}function hE(e,t=0){var r=Qo(b$|t,e);return r}function Ti(e){return Qo(32|Ru,e)}function pE(e){var t=e.teardown;if(t!==null){const r=Zs,n=ar;Hw(!0),Ei(null);try{t.call(null)}catch(i){Is(i,e.parent)}finally{Hw(r),Ei(n)}}}function Fb(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&pf(()=>{i.abort(df)});var n=r.next;(r.f&64)!==0?r.parent=null:Fn(r,t),r=n}}function fM(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&32)===0&&Fn(t),t=r}}function Fn(e,t=!0){var r=!1;(t||(e.f&262144)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(hM(e.nodes.start,e.nodes.end),r=!0),e.f|=Ow,Fb(e,t&&!r),jd(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const o of n)o.stop();pE(e),e.f^=Ow,e.f|=w$;var i=e.parent;i!==null&&i.first!==null&&mE(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function hM(e,t){for(;e!==null;){var r=e===t?null:_s(e);e.remove(),e=r}}function mE(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function dc(e,t,r=!0){var n=[];e.f|=256,gE(e,n,!0);var i=()=>{r&&Fn(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function gE(e,t,r){if((e.f&8192)===0){e.f^=Ab;var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(e.f&16)!==0;gE(i,t,s?r:!1)}i=o}}}function Tp(e){e.f&=-257,vE(e,!0)}function vE(e,t){if((e.f&256)===0&&(e.f&8192)!==0){e.f^=Ab,(e.f&1024)===0&&(un(e,Yi),uc.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;vE(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(const s of o)(s.is_global||t)&&s.in()}}function Hb(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:_s(r);t.append(r),r=i}}var pM=null,Hh=!1,Zs=!1;function Hw(e){Zs=e}var ar=null,Mo=!1;function Ei(e){ar=e}var Bt=null;function mo(e){Bt=e}var Bo=null;function yE(e){ar!==null&&(!Fa&&(ar.f&2097152)!==0||(ar.f&2)!==0)&&(Bo??(Bo=new Set)).add(e)}var yi=null,Di=0,no=null;function mM(e){no=e}var bE=1,gl=0,Pl=gl;function Uw(e){Pl=e}function wE(){return++bE}function yf(e){var t=e.f;if((t&2048)!==0)return!0;if((t&4096)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(yf(o)&&GT(o),o.wv>e.wv)return!0}(t&512)!==0&&si===null&&un(e,po)}return!1}function SE(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!Fa&&Bo!==null&&Bo.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?SE(o,t,!1):t===o&&(r?un(o,Yi):(o.f&1024)!==0&&un(o,cc),zb(o))}}function IE(e){var t=yi,r=Di,n=no,i=ar,o=Bo,s=Qr,a=Mo,l=Pl,c=e.f;yi=null,Di=0,no=null,ar=(c&96)===0?e:null,Bo=null,nu(e.ctx),Mo=!1,Pl=++gl,e.ac!==null&&(pf(()=>{e.ac.abort(df)}),e.ac=null);try{e.f|=Lw;var u=e.fn,d=u();e.f|=$b;var f=qw(e);if(hf()&&no!==null&&!Mo&&f!==null&&(e.f&6146)===0)for(var h=0;h<no.length;h++)SE(no[h],e);if(i!==null&&i!==e){if(gl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=gl;if(t!==null)for(const g of t)g.rv=gl;no!==null&&(n===null?n=no:n.push(...no))}return(e.f&8388608)!==0&&(e.f^=pp),d}catch(g){return qw(e),sM(g)}finally{e.f^=Lw,yi=t,Di=r,no=n,ar=i,Bo=o,nu(s),Mo=a,Pl=l}}function qw(e){var t=e.deps,r=Kt?.is_fork;if(yi!==null){var n;if(r||jd(e,Di),t!==null&&Di>0)for(t.length=Di+yi.length,n=0;n<yi.length;n++)t[Di+n]=yi[n];else e.deps=t=yi;if(Bb()&&(e.f&512)!==0)for(n=Di;n<t.length;n++){var i;((i=t[n]).reactions??(i.reactions=[])).push(e)}}else!r&&t!==null&&Di<t.length&&(jd(e,Di),t.length=Di);return t}function gM(e,t){let r=t.reactions;if(r!==null){var n=p$.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&2)!==0&&(yi===null||!fp.call(yi,t))){var o=t;(o.f&512)!==0&&(o.f^=512),o.v!==vn&&Lb(o),o.ac!==null&&pf(()=>{o.ac.abort(df),o.ac=null,un(o,Yi)}),X$(o),jd(o,0)}}function jd(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)gM(e,r[n])}function ou(e){var t=e.f;if((t&16384)===0){un(e,po);var r=Bt,n=Hh;if(Bt=e,Hh=(t&96)===0,0)var i,o;try{(t&16777232)!==0?fM(e):Fb(e),pE(e);var s=IE(e);if(e.teardown=typeof s=="function"?s:null,e.wv=bE,0)for(var a of e.deps);}finally{Hh=n,Bt=r}}}function p(e){var t=(e.f&2)!==0;if(pM?.add(e),ar!==null&&!Mo&&!(Bt!==null&&(Bt.f&16384)!==0)&&(Bo===null||!Bo.has(e))){var r=ar.deps;if((ar.f&2097152)!==0)e.rv<gl&&(e.rv=gl,yi===null&&r!==null&&r[Di]===e?Di++:yi===null?yi=[e]:yi.push(e));else{var n;(n=ar).deps??(n.deps=[]),fp.call(ar.deps,e)||ar.deps.push(e);var i=e.reactions;i===null?e.reactions=[ar]:fp.call(i,ar)||i.push(ar)}}if(0){if(!Mo&&reactivity_loss_tracker&&Kt===null&&$v===null&&!reactivity_loss_tracker.warned&&(reactivity_loss_tracker.effect.f&2097152)===0&&!reactivity_loss_tracker.effect_deps.has(e))var o;if(tracing_mode_flag&&!Mo&&tracing_expressions!==null&&ar!==null&&tracing_expressions.reaction===ar&&!e.trace){if(o)var s,a}}if(Zs&&Ss.has(e))return Ss.get(e);if(t){var l=e;if(Zs){var c=l.v;return((l.f&1024)===0&&l.reactions!==null||TE(l))&&(c=Db(l)),Ss.set(l,c),c}var u=(l.f&512)===0&&!Mo&&ar!==null&&(Hh||(ar.f&512)!==0),d=(l.f&$b)===0;yf(l)&&(u&&(l.f|=512),GT(l)),u&&!d&&(YT(l),kE(l))}if(si?.has(e))return si.get(e);if((e.f&8388608)!==0)throw e.v;return e.v}function kE(e){if(e.f|=512,e.deps!==null)for(const t of e.deps)(t.reactions??(t.reactions=[])).push(e),(t.f&2)!==0&&(t.f&512)===0&&(YT(t),kE(t))}function TE(e){if(e.v===vn)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(Ss.has(t)||(t.f&2)!==0&&TE(t))return!0;return!1}function Dr(e){var t=Mo;try{return Mo=!0,e()}finally{Mo=t}}function vM(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(Ws in e)Dv(e);else if(!Array.isArray(e))for(let t in e){const r=e[t];typeof r=="object"&&r&&Ws in r&&Dv(r)}}}function Dv(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{Dv(e[n],t)}catch{}const r=_b(e);if(r!==Object.prototype&&r!==Array.prototype&&r!==Map.prototype&&r!==Set.prototype&&r!==Date.prototype){const n=MT(r);for(let i in n){const o=n[i].get;if(o)try{o.call(e)}catch{}}}}}var Vc=Symbol("events"),EE=new Set,jv=new Set;function CE(e,t,r,n={}){function i(o){if(n.capture||zv.call(t,o),!o.cancelBubble)return pf(()=>r?.call(this,o))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?(i.__removed=!1,Xo(()=>{i.__removed||t.addEventListener(e,i,n)})):t.addEventListener(e,i,n),i}function ld(e,t,r,n,i){var o={capture:n,passive:i},s=CE(e,t,r,o);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&xm(()=>{s.__removed=!0,t.removeEventListener(e,s,o)})}function fo(e,t,r){(t[Vc]??(t[Vc]={}))[e]=r}function Pu(e){for(var t=0;t<e.length;t++)EE.add(e[t]);for(var r of jv)r(e)}var mg=null,gg=!1;function zv(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;mg=e,gg||(gg=!0,setTimeout(()=>{gg=!1,mg=null}));var s=0,a=mg===e&&e[Vc];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[Vc]=t;return}var c=i.indexOf(t);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||e.target,o!==t){Ld(e,"currentTarget",{configurable:!0,get(){return o||r}});var u=ar,d=Bt;Ei(null),mo(null);try{for(var f,h=[];o!==null&&o!==t;){try{var g=o[Vc]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(m){f?h.push(m):f=m}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let m of h)queueMicrotask(()=>{throw m});throw f}}finally{e[Vc]=t,delete e.currentTarget,Ei(u),mo(d)}}}var yM=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function bM(e){return yM?.createHTML(e)??e}function wM(e){var t=mf("template");return t.innerHTML=bM(e.replaceAll("<!>","<!---->")),t.content}function Gs(e,t){var r=Bt;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function Wt(e,t){var r=(t&1)!==0,n=(t&2)!==0,i,o=!e.startsWith("<!>");return()=>{if(It)return Gs(cr,null),cr;i===void 0&&(i=wM(o?e:"<!>"+e),r||(i=Qs(i)));var s=n||aE?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=Qs(s),l=s.lastChild;Gs(a,l)}else Gs(s,s);return s}}function xE(e=""){if(!It){var t=Jn(e+"");return Gs(t,t),t}var r=cr;return r.nodeType!==3?(r.before(r=Jn()),Bn(r)):Cm(r),Gs(r,r),r}function Ys(){if(It)return Gs(cr,null),cr;var e=document.createDocumentFragment(),t=document.createComment(""),r=Jn();return e.append(t,r),Gs(t,r),e}function ht(e,t){if(It){var r=Bt;((r.f&32768)===0||r.nodes.end===null)&&(r.nodes.end=cr),Gl();return}e!==null&&e.before(t)}function SM(e){return e.endsWith("capture")&&e!=="gotpointercapture"&&e!=="lostpointercapture"}var IM=["beforeinput","click","change","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"];function kM(e){return IM.includes(e)}var TM=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"],EM={formnovalidate:"formNoValidate",ismap:"isMap",nomodule:"noModule",playsinline:"playsInline",readonly:"readOnly",defaultvalue:"defaultValue",defaultchecked:"defaultChecked",srcobject:"srcObject",novalidate:"noValidate",allowfullscreen:"allowFullscreen",disablepictureinpicture:"disablePictureInPicture",disableremoteplayback:"disableRemotePlayback"};function CM(e){return e=e.toLowerCase(),EM[e]??e}var hK=[...TM,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"],xM=["touchstart","touchmove"];function RM(e){return xM.includes(e)}var PM=["$state","$state.raw","$derived","$derived.by"],pK=[...PM,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"],_M=["textarea","script","style","title"];function AM(e){return _M.includes(e)}function $M(e){let t=0,r=Kl(0),n;return()=>{Bb()&&(p(r),Rm(()=>(t===0&&(n=Dr(()=>e(()=>Id(r)))),t+=1,()=>{Xo(()=>{t-=1,t===0&&(n?.(),n=void 0,Id(r))})})))}}var MM=uf|Ru;function OM(e,t,r,n){new LM(e,t,r,n)}var Fo=new WeakMap,Bv=new WeakMap,gs=new WeakMap,zd=new WeakMap,Bi=new WeakMap,Ho=new WeakMap,qi=new WeakMap,Oo=new WeakMap,Pa=new WeakMap,Mc=new WeakMap,_l=new WeakMap,Jf=new WeakMap,Fv=new WeakMap,Hv=new WeakMap,Wa=new WeakMap,Ww=new WeakMap,An=new WeakSet,LM=class{constructor(e,t,r,n){Eu(this,An),T(this,"parent",void 0),T(this,"is_pending",!1),T(this,"transform_error",void 0),Me(this,Fo,void 0),Me(this,Bv,It?cr:null),Me(this,gs,void 0),Me(this,zd,void 0),Me(this,Bi,void 0),Me(this,Ho,null),Me(this,qi,null),Me(this,Oo,null),Me(this,Pa,null),Me(this,Mc,0),Me(this,_l,0),Me(this,Jf,!1),Me(this,Fv,new Set),Me(this,Hv,new Set),Me(this,Wa,null),Me(this,Ww,$M(()=>(xe(Wa,this,Kl(w(Mc,this))),()=>{xe(Wa,this,null)}))),xe(Fo,this,e),xe(gs,this,t),xe(zd,this,i=>{var o=Bt;o.b=this,o.f|=128,r(i)}),this.parent=Bt.b,this.transform_error=n??this.parent?.transform_error??(i=>i),xe(Bi,this,vf(()=>{if(It){const i=w(Bv,this);Gl();const o=i.data==="[!";if(i.data.startsWith("[?")){const s=JSON.parse(i.data.slice(2));ze(An,this,DM).call(this,s)}else o?ze(An,this,jM).call(this):ze(An,this,NM).call(this)}else ze(An,this,PE).call(this)},MM)),It&&xe(Fo,this,cr)}defer_effect(e){qT(e,w(Fv,this),w(Hv,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!w(gs,this).pending}update_pending_count(e,t){ze(An,this,_E).call(this,e,t),xe(Mc,this,w(Mc,this)+e),!(!w(Wa,this)||w(Jf,this))&&(xe(Jf,this,!0),Xo(()=>{xe(Jf,this,!1),w(Wa,this)&&iu(w(Wa,this),w(Mc,this))}))}get_effect_pending(){return w(Ww,this).call(this),p(w(Wa,this))}error(e){if(!w(gs,this).onerror&&!w(gs,this).failed)throw e;Kt?.is_fork?(w(Ho,this)&&Kt.skip_effect(w(Ho,this)),w(qi,this)&&Kt.skip_effect(w(qi,this)),w(Oo,this)&&Kt.skip_effect(w(Oo,this)),Kt.oncommit(()=>{ze(An,this,Vw).call(this,e)})):ze(An,this,Vw).call(this,e)}};function NM(){try{xe(Ho,this,Ti(()=>w(zd,this).call(this,w(Fo,this))))}catch(e){this.error(e)}}function DM(e){const t=w(gs,this).failed,{reset:r,invoke_onerror:n}=ze(An,this,RE).call(this,e);Xo(n),t&&xe(Oo,this,Ti(()=>{t(w(Fo,this),()=>e,()=>r)}))}function RE(e){var t=!1,r=!1;const n=()=>{if(t){x$();return}t=!0,r&&B$(),w(Oo,this)!==null&&dc(w(Oo,this),()=>{xe(Oo,this,null)}),ze(An,this,Ub).call(this,()=>{ze(An,this,PE).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,w(gs,this).onerror?.(e,n),r=!1}catch(o){Is(o,w(Bi,this)&&w(Bi,this).parent)}}}}function jM(){const e=w(gs,this).pending;e&&(this.is_pending=!0,xe(qi,this,Ti(()=>e(w(Fo,this)))),Xo(()=>{var t=xe(Pa,this,document.createDocumentFragment()),r=Jn(),n=!1;if(t.append(r),xe(Ho,this,ze(An,this,Ub).call(this,()=>{try{return Ti(()=>w(zd,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){Is(o,w(Bi,this).parent)}return null}})),w(Ho,this)===null){xe(Pa,this,null),n&&ze(An,this,Ep).call(this,Kt);return}w(_l,this)===0&&(w(Fo,this).before(t),xe(Pa,this,null),dc(w(qi,this),()=>{xe(qi,this,null)}),ze(An,this,Ep).call(this,Kt))}))}function PE(){try{if(this.is_pending=this.has_pending_snippet(),xe(_l,this,0),xe(Mc,this,0),xe(Ho,this,Ti(()=>{w(zd,this).call(this,w(Fo,this))})),w(_l,this)>0){var e=xe(Pa,this,document.createDocumentFragment());Hb(w(Ho,this),e);const t=w(gs,this).pending;xe(qi,this,Ti(()=>t(w(Fo,this))))}else ze(An,this,Ep).call(this,Kt)}catch(t){this.error(t)}}function Ep(e){this.is_pending=!1,e.transfer_effects(w(Fv,this),w(Hv,this))}function Ub(e){var t=Bt,r=ar,n=Qr;mo(w(Bi,this)),Ei(w(Bi,this)),nu(w(Bi,this).ctx);try{return uc.ensure(),e()}finally{mo(t),Ei(r),nu(n)}}function _E(e,t){if(!this.has_pending_snippet()){if(this.parent){var r;ze(An,r=this.parent,_E).call(r,e,t)}return}xe(_l,this,w(_l,this)+e),w(_l,this)===0&&(ze(An,this,Ep).call(this,t),w(qi,this)&&dc(w(qi,this),()=>{xe(qi,this,null)}),w(Pa,this)&&(w(Fo,this).before(w(Pa,this)),xe(Pa,this,null)))}function Vw(e){w(Ho,this)&&(Fn(w(Ho,this)),xe(Ho,this,null)),w(qi,this)&&(Fn(w(qi,this)),xe(qi,this,null)),w(Oo,this)&&(Fn(w(Oo,this)),xe(Oo,this,null)),It&&(Bn(w(Bv,this)),R$(),Bn(mp()));let t=w(gs,this).failed;const r=n=>{const{reset:i,invoke_onerror:o}=ze(An,this,RE).call(this,n);o(),t&&xe(Oo,this,ze(An,this,Ub).call(this,()=>{try{return Ti(()=>{var s=Bt;s.b=this,s.f|=128,t(w(Fo,this),()=>n,()=>i)})}catch(s){return Is(s,w(Bi,this).parent),null}}))};Xo(()=>{var n;try{n=this.transform_error(e)}catch(i){Is(i,w(Bi,this)&&w(Bi,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>Is(i,w(Bi,this)&&w(Bi,this).parent)):r(n)})}var Uv=!0;function Qf(e){Uv=e}function ks(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[Bh]??(e[Bh]=e.nodeValue))&&(e[Bh]=r,e.nodeValue=`${r}`)}function qb(e,t){return AE(e,t)}function zM(e,t){Nv(),t.intro=t.intro??!1;const r=t.target,n=It,i=cr;try{for(var o=Qs(r);o&&(o.nodeType!==8||o.data!=="[");)o=_s(o);if(!o)throw ru;ci(!0),Bn(o);const s=AE(e,{...t,anchor:o});return ci(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
2
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==ru&&console.warn("Failed to hydrate: ",s),t.recover===!1&&L$(),Nv(),uE(r),ci(!1),qb(e,t)}finally{ci(n),Bn(i)}}var Zf=new Map;function AE(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Nv();var l=void 0,c=uM(()=>{var u=r??t.appendChild(Jn());OM(u,{pending:()=>{}},h=>{pn({});var g=Qr;if(o&&(g.c=o),i&&(n.$$events=i),It&&Gs(h,null),Uv=s,l=e(h,n)||Ob(),Uv=!0,It&&(Bt.nodes.end=cr,cr===null||cr.nodeType!==8||cr.data!=="]"))throw Em(),ru;mn()},a);var d=new Set,f=h=>{for(var g=0;g<h.length;g++){var m=h[g];if(!d.has(m)){d.add(m);var v=RM(m);for(const C of[t,document]){var b=Zf.get(C);b===void 0&&(b=new Map,Zf.set(C,b));var I=b.get(m);I===void 0?(C.addEventListener(m,zv,{passive:v}),b.set(m,1)):b.set(m,I+1)}}}};return f(km(EE)),jv.add(f),()=>{for(var h of d)for(const v of[t,document]){var g=Zf.get(v),m=g.get(h);--m==0?(v.removeEventListener(h,zv),g.delete(h),g.size===0&&Zf.delete(v)):g.set(h,m)}jv.delete(f),u!==r&&u.parentNode?.removeChild(u)}});return qv.set(l,c),l}var qv=new WeakMap;function $E(e,t){const r=qv.get(e);return r?(qv.delete(e),r(t)):Promise.resolve()}var js=new WeakMap,fa=new WeakMap,Eo=new WeakMap,Fu=new WeakMap,vg=new WeakMap,yg=new WeakMap,Gw=new WeakMap,Wb=class{constructor(e,t=!0){T(this,"anchor",void 0),Me(this,js,new Map),Me(this,fa,new Map),Me(this,Eo,new Map),Me(this,Fu,new Set),Me(this,vg,!0),Me(this,yg,r=>{if(w(js,this).has(r)){var n=w(js,this).get(r),i=w(fa,this).get(n);if(i)Tp(i),w(Fu,this).delete(n);else{var o=w(Eo,this).get(n);o&&(Tp(o.effect),w(fa,this).set(n,o.effect),w(Eo,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(const[s,a]of w(js,this)){if(w(js,this).delete(s),s===r)break;const l=w(Eo,this).get(a);l&&(Fn(l.effect),w(Eo,this).delete(a))}for(const[s,a]of w(fa,this)){if(s===n||w(Fu,this).has(s))continue;const l=()=>{if(Array.from(w(js,this).values()).includes(s)){var c=document.createDocumentFragment();Hb(a,c),c.append(Jn()),w(Eo,this).set(s,{effect:a,fragment:c})}else Fn(a);w(Fu,this).delete(s),w(fa,this).delete(s)};w(vg,this)||!i?(w(Fu,this).add(s),dc(a,l,!1)):l()}}}),Me(this,Gw,r=>{w(js,this).delete(r);const n=Array.from(w(js,this).values());for(const[i,o]of w(Eo,this))n.includes(i)||(Fn(o.effect),w(Eo,this).delete(i))}),this.anchor=e,xe(vg,this,t)}ensure(e,t){var r=Kt,n=dE();if(t&&!w(fa,this).has(e)&&!w(Eo,this).has(e))if(n){var i=document.createDocumentFragment(),o=Jn();i.append(o),w(Eo,this).set(e,{effect:Ti(()=>t(o)),fragment:i})}else w(fa,this).set(e,Ti(()=>t(this.anchor)));if(w(js,this).set(r,e),n){for(const[s,a]of w(fa,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(const[s,a]of w(Eo,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(w(yg,this)),r.ondiscard(w(Gw,this))}else It&&(this.anchor=cr),w(yg,this).call(this,r)}};function BM(e,t,...r){var n=new Wb(e);vf(()=>{const i=t()??null;n.ensure(i,i&&(o=>i(o,...r)))},uf)}function Pm(e){Qr===null&&HT("onMount"),ff&&Qr.l!==null?FM(Qr).m.push(e):vt(()=>{const t=Dr(e);if(typeof t=="function")return t})}function _m(e){Qr===null&&HT("onDestroy"),Pm(()=>()=>Dr(e))}function FM(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}function cn(e,t,r=!1){var n;It&&(n=cr,Gl());var i=new Wb(e),o=r?uf:0;function s(a,l){if(It){var c=jT(n);if(a!==parseInt(c.substring(1))){var u=mp();Bn(u),i.anchor=u,ci(!1),i.ensure(a,l),ci(!0);return}}i.ensure(a,l)}vf(()=>{var a=!1;t((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}function HM(e,t,r){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let d=t[a];dc(d,()=>{if(o){if(o.pending.delete(d),o.done.add(d),o.pending.size===0){var f=e.outrogroups;Wv(e,km(o.done)),f.delete(o),f.size===0&&(e.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&r!==null&&e.pending.size===0;if(l){var c=r,u=c.parentNode;uE(u),u.append(c),e.items.clear()}Wv(e,t,!l)}else o={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(o)}function Wv(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(const s of e.pending.values())for(const a of s)n.add(e.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];if(n?.has(o)){o.f|=wd;const s=document.createDocumentFragment();Hb(o,s)}else Fn(t[i],r)}}var eh;function ME(e,t,r,n,i,o=null){var s=e,a=new Map;if((t&4)!==0){var l=e;s=It?Bn(Qs(l)):l.appendChild(Jn())}It&&Gl();var c=null,u=Nb(()=>{var b=r();return Im(b)?b:b==null?[]:km(b)}),d,f=new Map,h=!0;function g(b){(v.effect.f&16384)===0&&(v.pending.delete(b),v.fallback=c,UM(v,d,s,t,n),c!==null&&(d.length===0?(c.f&33554432)===0?Tp(c):(c.f^=wd,cd(c,null,s)):dc(c,()=>{c=null})))}function m(b){v.pending.delete(b)}var v={effect:vf(()=>{d=p(u);var b=d.length;let I=!1;It&&jT(s)==="[!"!=(b===0)&&(s=mp(),Bn(s),ci(!1),I=!0);for(var C=new Set,x=Kt,$=dE(),P=0;P<b;P+=1){It&&cr.nodeType===8&&cr.data==="]"&&(s=cr,I=!0,ci(!1));var L=d[P],J=n(L,P);if(0)var V;var Y=h?null:a.get(J);Y?(Y.v&&iu(Y.v,L),Y.i&&iu(Y.i,P),$&&x.unskip_effect(Y.e)):(Y=qM(a,h?s:eh??(eh=Jn()),L,J,P,i,t,r),h||(Y.e.f|=wd),a.set(J,Y)),C.add(J)}if(b===0&&o&&!c&&(h?c=Ti(()=>o(s)):(c=Ti(()=>o(eh??(eh=Jn()))),c.f|=wd)),b>C.size&&_$("","",""),It&&b>0&&Bn(mp()),!h)if(f.set(x,C),$){for(const[Pe,M]of a)C.has(Pe)||x.skip_effect(M.e);x.oncommit(g),x.ondiscard(m)}else g(x);I&&ci(!0),p(u)}),flags:t,items:a,pending:f,outrogroups:null,fallback:c};h=!1,It&&(s=cr)}function Hu(e){for(;e!==null&&(e.f&32)===0;)e=e.next;return e}function UM(e,t,r,n,i){var o=(n&8)!==0,s=t.length,a=e.items,l=Hu(e.effect.first),c,u=null,d,f=[],h=[],g,m,v,b;if(o)for(b=0;b<s;b+=1)g=t[b],m=i(g,b),v=a.get(m).e,(v.f&33554432)===0&&(v.nodes?.a?.measure(),(d??(d=new Set)).add(v));for(b=0;b<s;b+=1){if(g=t[b],m=i(g,b),v=a.get(m).e,e.outrogroups!==null)for(const Y of e.outrogroups)Y.pending.delete(v),Y.done.delete(v);if((v.f&8192)!==0&&(Tp(v),o&&(v.nodes?.a?.unfix(),(d??(d=new Set)).delete(v))),(v.f&33554432)!==0)if(v.f^=wd,v===l)cd(v,null,r);else{var I=u?u.next:l;v===e.effect.last&&(e.effect.last=v.prev),v.prev&&(v.prev.next=v.next),v.next&&(v.next.prev=v.prev),ha(e,u,v),ha(e,v,I),cd(v,I,r),u=v,f=[],h=[],l=Hu(u.next);continue}if(v!==l){if(c!==void 0&&c.has(v)){if(f.length<h.length){var C=h[0],x;u=C.prev;var $=f[0],P=f[f.length-1];for(x=0;x<f.length;x+=1)cd(f[x],C,r);for(x=0;x<h.length;x+=1)c.delete(h[x]);ha(e,$.prev,P.next),ha(e,u,$),ha(e,P,C),l=C,u=P,b-=1,f=[],h=[]}else c.delete(v),cd(v,l,r),ha(e,v.prev,v.next),ha(e,v,u===null?e.effect.first:u.next),ha(e,u,v),u=v;continue}for(f=[],h=[];l!==null&&l!==v;)(c??(c=new Set)).add(l),h.push(l),l=Hu(l.next);if(l===null)continue}(v.f&33554432)===0&&f.push(v),u=v,l=Hu(v.next)}if(e.outrogroups!==null){for(const Y of e.outrogroups)Y.pending.size===0&&(Wv(e,km(Y.done)),e.outrogroups?.delete(Y));e.outrogroups.size===0&&(e.outrogroups=null)}if(l!==null||c!==void 0){var L=[];if(c!==void 0)for(v of c)(v.f&8192)===0&&L.push(v);for(;l!==null;)(l.f&8192)===0&&l!==e.fallback&&L.push(l),l=Hu(l.next);var J=L.length;if(J>0){var V=(n&4)!==0&&s===0?r:null;if(o){for(b=0;b<J;b+=1)L[b].nodes?.a?.measure();for(b=0;b<J;b+=1)L[b].nodes?.a?.fix()}HM(e,L,V)}}o&&Xo(()=>{if(d!==void 0)for(v of d)v.nodes?.a?.apply()})}function qM(e,t,r,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?iE(r,!1,!1):Kl(r):null,c=(s&2)!==0?Kl(i):null;return{v:l,i:c,e:Ti(()=>(o(t,l??r,c??i,a),()=>{e.delete(n)}))}}function cd(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,o=t&&(t.f&33554432)===0?t.nodes.start:r;n!==null;){var s=_s(n);if(o.before(n),n===i)return;n=s}}function ha(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}function _u(e,t,r,n,i){if(It&&Gl(),t.$$host?.$$shadowRoot){const a=mf("slot");if(r!=="default"&&(a.name=r),ht(e,a),i!==null){const l=Jn();a.append(l),i(l)}return}var o=t.$$slots?.[r],s=!1;o===!0&&(o=t[r==="default"?"children":r],s=!0),o===void 0?i!==null&&i(e):o(e,s?()=>n:n)}var WM=null;function Yw(e){WM=e}function Cp(e,t,r,n,i,o){let s=It;It&&Gl();var a=!1,l=null;It&&cr.nodeType===1&&(l=cr,Gl());var c=It?cr:e,u=Bt,d=new Wb(c,!1);vf(()=>{const f=t()||null;var h=i?i():r||f==="svg"?h$:void 0;if(f===null){d.ensure(null,null),Qf(!0);return}return d.ensure(f,g=>{if(f){if(l=It?l:mf(f,h),Gs(l,l),n){var m=null;It&&AM(f)&&l.append(m=document.createComment(""));var v=It?Qs(l):l.appendChild(Jn());It&&(v===null?ci(!1):Bn(v)),Yw(u),n(l,v),m?.remove(),Yw(null)}Bt.nodes.end=l,g.before(l)}It&&Bn(g)}),Qf(!0),()=>{f&&Qf(!1)}},uf),xm(()=>{Qf(!0)}),s&&(ci(!0),Bn(c))}function Ln(e,t){gf(()=>{e=Bt?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){const i=mf("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function OE(e,t,r){gf(()=>{var n=Dr(()=>t(e,r?.())||{});if(r&&n?.update){var i=!1,o={};Rm(()=>{var s=r();vM(s),i&&BT(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}function VM(e,t){var r=void 0,n;hE(()=>{r!==(r=t())&&(n&&(Fn(n),n=null),r&&(n=Ti(()=>{gf(()=>r(e))})))})}function LE(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=LE(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function GM(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=LE(e))&&(n&&(n+=" "),n+=t);return n}function YM(e){return typeof e=="object"?GM(e):e??""}var Kw=[...`
3
+ \r\f \v\uFEFF`];function KM(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||Kw.includes(n[s-1]))&&(a===n.length||Kw.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function Xw(e,t=!1){var r=t?" !important;":";",n="";for(var i of Object.keys(e)){var o=e[i];o!=null&&o!==""&&(n+=" "+i+": "+o+r)}return n}function bg(e){return e[0]!=="-"||e[1]!=="-"?e.toLowerCase():e}function XM(e,t){if(t){var r="",n,i;if(Array.isArray(t)?(n=t[0],i=t[1]):n=t,e){e=String(e).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(bg)),i&&l.push(...Object.keys(i).map(bg));var c=0,u=-1;const m=e.length;for(var d=0;d<m;d++){var f=e[d];if(a?f==="/"&&e[d-1]==="*"&&(a=!1):o?o===f&&(o=!1):f==="/"&&e[d+1]==="*"?a=!0:f==='"'||f==="'"?o=f:f==="("?s++:f===")"&&s--,!a&&o===!1&&s===0){if(f===":"&&u===-1)u=d;else if(f===";"||d===m-1){if(u!==-1){var h=bg(e.substring(c,u).trim());if(!l.includes(h)){f!==";"&&d++;var g=e.substring(c,d).trim();r+=" "+g+";"}}c=d+1,u=-1}}}}return n&&(r+=Xw(n)),i&&(r+=Xw(i,!0)),r=r.trim(),r===""?null:r}return e==null?null:String(e)}function yn(e,t,r,n,i,o){var s=e[_v];if(It||s!==r||s===void 0){var a=KM(r,n,o);(!It||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[_v]=r}else if(o&&i!==o)for(var l in o){var c=!!o[l];(i==null||c!==!!i[l])&&e.classList.toggle(l,c)}return o}function wg(e,t={},r,n){for(var i in r){var o=r[i];t[i]!==o&&(r[i]==null?e.style.removeProperty(i):e.style.setProperty(i,o,n))}}function Xl(e,t,r,n){var i=e[Av];if(It||i!==t){var o=XM(t,n);(!It||o!==e.getAttribute("style"))&&(o==null?e.removeAttribute("style"):e.style.cssText=o),e[Av]=t}else n&&(Array.isArray(n)?(wg(e,r?.[0],n[0]),wg(e,r?.[1],n[1],"important")):wg(e,r,n));return n}function NE(e,t){t?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function Jw(e,t){var r=!("__defaultValue"in e);!r&&e.__defaultValue===t||(e.__defaultValue=t,DE(e,!r||"__value"in e))}function DE(e,t){var r=e.__defaultValue,n=e.multiple,i=n?r??[]:null;if(!(n&&!Im(i))){var o=e.selectedIndex,s=t&&n?new Set(e.selectedOptions):null;for(var a of e.options){var l=Gv(a);NE(a,n?i.includes(l):sE(l,r))}if(t)if(s!==null)for(a of e.options){var c=s.has(a);a.selected!==c&&(a.selected=c)}else e.selectedIndex!==o&&(e.selectedIndex=o)}}function Vv(e,t,r=!1){if(e.multiple){if(t==null)return;if(!Im(t))return C$();for(var n of e.options)n.selected=t.includes(Gv(n));return}for(n of e.options){var i=Gv(n);if(sE(i,t)){n.selected=!0;return}}(!r||t!==void 0)&&(e.selectedIndex=-1)}function JM(e){var t=new MutationObserver(r=>{r.every(QM)||("__defaultValue"in e&&DE(e,!1),"__value"in e&&Vv(e,e.__value))});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),xm(()=>{t.disconnect()})}function Gv(e){return"__value"in e?e.__value:e.value}function QM(e){if(e.target.closest("selectedcontent")!==null)return!0;if(e.type==="childList"){var t=[...e.addedNodes,...e.removedNodes];return t.length>0&&t.every(r=>r.nodeName==="SELECTEDCONTENT")}return!1}var Uu=Symbol("class"),qu=Symbol("style"),jE=Symbol("is custom element"),zE=Symbol("is html"),ZM=Tm?"link":"LINK",Qw=Tm?"input":"INPUT",eO=Tm?"option":"OPTION",BE=Tm?"select":"SELECT";function tO(e){if(It){var t=!1,r=()=>{if(!t){if(t=!0,e.hasAttribute("value")){var n=e.value;at(e,"value",null),e.value=n}if(e.hasAttribute("checked")){var i=e.checked;at(e,"checked",null),e.checked=i}}};e[DT]=r,Xo(r),W$()}}function at(e,t,r,n){var i=HE(e);if(It&&(i[t]=e.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&e.nodeName===ZM)){n||void 0;return}i[t]!==(i[t]=r)&&(t==="loading"&&(e[k$]=r),r==null?e.removeAttribute(t):typeof r!="string"&&Vb(e).has(t)?e[t]=r:e.setAttribute(t,r))}function Ce(e,t,r){var n=ar,i=Bt;let o=It;It&&ci(!1),Ei(null),mo(null);try{t!=="style"&&(Yv.has(e.getAttribute("is")||e.nodeName)||!customElements||customElements.get(e.getAttribute("is")||e.nodeName.toLowerCase())?Vb(e).has(t):r&&typeof r=="object")?e[t]=r:at(e,t,r==null?r:String(r))}finally{Ei(n),mo(i),o&&ci(!0)}}function rO(e,t,r,n,i=!1,o=!1){It&&i&&e.nodeName===Qw&&("defaultValue"in r||"defaultChecked"in r||tO(e));var s=HE(e),a=s[jE],l=!s[zE];let c=It&&a;c&&ci(!1);var u=t||{},d=e.nodeName===eO,f=e.nodeName===BE;for(var h in t)!(h in r)&&h[0]+h[1]!=="$$"&&(r[h]=null);r.class?r.class=YM(r.class):(n||r[Uu])&&(r.class=null),r[qu]&&(r.style??(r.style=null));var g=Vb(e);if(e.nodeName===Qw&&"type"in r&&("value"in r||"__value"in r)){var m=r.type;(m!==u.type||m===void 0&&e.hasAttribute("type"))&&(u.type=m,at(e,"type",m,o))}for(const P in r){let L=r[P];if(d&&P==="value"&&L==null){e.value=e.__value="",u[P]=L;continue}if(P==="class"){var v=e.namespaceURI==="http://www.w3.org/1999/xhtml";yn(e,v,L,n,t?.[Uu],r[Uu]),u[P]=L,u[Uu]=r[Uu];continue}if(P==="style"){Xl(e,L,t?.[qu],r[qu]),u[P]=L,u[qu]=r[qu];continue}var b=u[P];if(!(L===b&&!(L===void 0&&e.hasAttribute(P)))){u[P]=L;var I=P[0]+P[1];if(I!=="$$")if(I==="on"){const J={},V="$$"+P;let Y=P.slice(2);var C=kM(Y);if(SM(Y)&&(Y=Y.slice(0,-7),J.capture=!0),!C&&b){if(L!=null)continue;e.removeEventListener(Y,u[V],J),u[V]=null}if(C)fo(Y,e,L),Pu([Y]);else if(L!=null){let Pe=function(M){u[P].call(this,M)};u[V]=CE(Y,e,Pe,J)}}else if(P==="style")at(e,P,L);else if(P==="autofocus")q$(e,!!L);else if(!a&&(P==="__value"||P==="value"&&L!=null))e.value=e.__value=L;else if(P==="selected"&&d)NE(e,L);else{var x=P;l||(x=CM(x));var $=x==="defaultValue"||x==="defaultChecked";if(f&&x==="defaultValue")continue;if(L==null&&!a&&!$)if(s[P]=null,x==="value"||x==="checked"){let J=e;const V=t===void 0;if(x==="value"){let Y=J.defaultValue;J.removeAttribute(x),J.defaultValue=Y,J.value=J.__value=V?Y:null}else{let Y=J.defaultChecked;J.removeAttribute(x),J.defaultChecked=Y,J.checked=V?Y:!1}}else e.removeAttribute(P);else $||(a||typeof L!="string")&&g.has(x)?(e[x]=L,x in s&&(s[x]=vn)):typeof L!="function"&&at(e,x,L,o)}}}return c&&ci(!0),u}function FE(e,t,r=[],n=[],i=[],o,s=!1,a=!1){WT(i,r,n,l=>{var c=void 0,u={},d=e.nodeName===BE,f=!1;if(hE(()=>{var g=t(...l.map(p)),m=rO(e,c,g,o,s,a);if(f&&d){var v=e;"defaultValue"in g&&Jw(v,g.defaultValue),"value"in g&&Vv(v,g.value)}for(let I of Object.getOwnPropertySymbols(u))g[I]||Fn(u[I]);for(let I of Object.getOwnPropertySymbols(g)){var b=g[I];I.description==="@attach"&&(!c||b!==c[I])&&(u[I]&&Fn(u[I]),u[I]=Ti(()=>VM(e,()=>b))),m[I]=b}c=m}),d){var h=e;gf(()=>{var g=c;"defaultValue"in g&&Jw(h,g.defaultValue),Vv(h,g.value,!0),JM(h)})}f=!0})}function HE(e){return e[Pv]??(e[Pv]={[jE]:e.nodeName.includes("-"),[zE]:e.namespaceURI==="http://www.w3.org/1999/xhtml"})}var Yv=new Map;function Vb(e){var t=e.getAttribute("is")||e.nodeName,r=Yv.get(t);if(r)return r;Yv.set(t,r=new Set);for(var n,i=e,o=Element.prototype;o!==i;){n=MT(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&r.add(s);i=_b(i)}return r}var UE,Oc=new WeakMap,xp=new WeakMap,Sg=new WeakMap,Zw=new WeakSet,qE=class{constructor(e){Eu(this,Zw),Me(this,Oc,new WeakMap),Me(this,xp,void 0),Me(this,Sg,void 0),xe(Sg,this,e)}observe(e,t){var r=w(Oc,this).get(e)||new Set;return r.add(t),w(Oc,this).set(e,r),ze(Zw,this,nO).call(this).observe(e,w(Sg,this)),()=>{var n=w(Oc,this).get(e);n.delete(t),n.size===0&&(w(Oc,this).delete(e),w(xp,this).unobserve(e))}}};UE=qE;function nO(){return w(xp,this)??xe(xp,this,new ResizeObserver(e=>{for(var t of e){UE.entries.set(t.target,t);for(var r of w(Oc,this).get(t.target)||[])r(t)}}))}T(qE,"entries",new WeakMap);function Ig(e,t){return e===t||e?.[Ws]===t}function $r(e=Ob(),t,r,n){var i=Qr.r,o=Bt;return gf(()=>{var s,a;return Rm(()=>{s=a,a=n?.()||[],Dr(()=>{Ig(r(...a),e)||(t(e,...a),s&&Ig(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;const c=()=>{a&&Ig(r(...a),e)&&t(null,...a)},u=l.teardown;l.teardown=()=>{c(),u?.()}}}),e}var th=!1;function iO(e){var t=th;try{return th=!1,[e(),th]}finally{th=t}}function D(e,t,r,n){var i=!ff||(r&2)!==0,o=(r&8)!==0,s=(r&16)!==0,a=n,l=!0,c=void 0,u=()=>s&&i?(c??(c=Nd(n)),p(c)):(l&&(l=!1,a=s?Dr(n):n),a);let d;if(o){var f=Ws in e||NT in e;d=xl(e,t)?.set??(f&&t in e?x=>e[t]=x:void 0)}var h,g=!1;o?[h,g]=iO(()=>e[t]):h=e[t],h===void 0&&n!==void 0&&(h=u(),d&&(i&&N$(t),d(h)));var m;if(i?m=()=>{var x=e[t];return x===void 0?u():(l=!0,x)}:m=()=>{var x=e[t];return x!==void 0&&(a=void 0),x===void 0?a:x},i&&(r&4)===0)return m;if(d){var v=e.$$legacy;return(function(x,$){return arguments.length>0?((!i||!$||v||g)&&d($?m():x),x):m()})}var b=!1,I=((r&1)!==0?Nd:Nb)(()=>(b=!1,m()));o&&p(I);var C=Bt;return(function(x,$){if(arguments.length>0){const P=$?p(I):i&&o?ui(x):x;return be(I,P),b=!0,a!==void 0&&(a=P),x}return Zs&&b||(C.f&16384)!==0?I.v:p(I)})}function oO(e){return new sO(e)}var Va=new WeakMap,os=new WeakMap,sO=class{constructor(e){Me(this,Va,void 0),Me(this,os,void 0);var t=new Map,r=(i,o)=>{var s=iE(o,!1,!1);return t.set(i,s),s};const n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return p(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===NT?!0:(p(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return be(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});xe(os,this,(e.hydrate?zM:qb)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!Fa&&(!e?.props?.$$host||e.sync===!1)&&N(),xe(Va,this,n.$$events);for(const i of Object.keys(w(os,this)))i==="$set"||i==="$destroy"||i==="$on"||Ld(this,i,{get(){return w(os,this)[i]},set(o){w(os,this)[i]=o},enumerable:!0});w(os,this).$set=i=>{Object.assign(n,i)},w(os,this).$destroy=()=>{$E(w(os,this))}}$set(e){w(os,this).$set(e)}$on(e,t){w(Va,this)[e]=w(Va,this)[e]||[];const r=(...n)=>t.call(this,...n);return w(Va,this)[e].push(r),()=>{w(Va,this)[e]=w(Va,this)[e].filter(n=>n!==r)}}$destroy(){w(os,this).$destroy()}},WE;typeof HTMLElement=="function"&&(WE=class extends HTMLElement{constructor(e,t,r){super(),T(this,"$$ctor",void 0),T(this,"$$s",void 0),T(this,"$$c",void 0),T(this,"$$cn",!1),T(this,"$$d",{}),T(this,"$$r",!1),T(this,"$$p_d",{}),T(this,"$$l",{}),T(this,"$$l_u",new Map),T(this,"$$me",void 0),T(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){const n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{const o=mf("slot");n!=="default"&&(o.name=n),ht(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},r=aO(this);for(const n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(const n of this.attributes){const i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=Uh(i,n.value,this.$$p_d,"toProp"))}for(const n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=oO({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=cM(()=>{Rm(()=>{this.$$r=!0;for(const n of hp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];const i=Uh(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(const n in this.$$l)for(const i of this.$$l[n]){const o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=Uh(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return hp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function Uh(e,t,r,n){const i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function aO(e){const t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function Tn(e,t,r,n,i,o){let s=class extends WE{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return hp(t).map(a=>(t[a].attribute||a).toLowerCase())}};return hp(t).forEach(a=>{Ld(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=Uh(a,l,t),this.$$d[a]=l;var c=this.$$c;c&&(xl(c,a)?.get?c[a]=l:c.$set({[a]:l}))}})}),n.forEach(a=>{Ld(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}function lO(e){const t=new Set,r=/<\/?([a-zA-Z][a-zA-Z0-9._-]*)(?=[\t\n\f\r />])/g;let n=null;for(;(n=r.exec(e))!==null;){const i=String(n[1]||"").trim();i&&i.includes("-")&&t.add(i)}return t}var VE=e=>{const t=[],r=[];if(!e||typeof e!="object"||Array.isArray(e))return{valid:!1,errors:["Config must be an object."],warnings:r};const n=e,i=n.markup,o=n.elements,s=n.models;if(typeof i!="string"&&t.push("`markup` must be a string."),(!o||typeof o!="object"||Array.isArray(o))&&t.push("`elements` must be an object."),Array.isArray(s)||t.push("`models` must be an array."),t.length>0)return{valid:!1,errors:t,warnings:r};const a=o,l=s,c=Object.keys(a);for(const[h,g]of Object.entries(a)){if(typeof h!="string"||h.trim().length===0){t.push("`elements` contains an empty tag name.");continue}if(typeof g!="string"||g.trim().length===0){t.push(`Element "${h}" must map to a non-empty package spec.`);continue}try{ET(h,g)}catch{t.push(`Element "${h}" has invalid package spec "${g}".`)}}const u=new Set;for(const[h,g]of l.entries()){const m=g?.element;if(typeof m!="string"||m.trim().length===0){t.push(`Model at index ${h} is missing a valid "element" reference.`);continue}u.add(m),m in a||t.push(`Model element "${m}" is not declared in \`elements\`.`)}const d=lO(i);for(const h of d)h in a||t.push(`Markup tag "${h}" is not declared in \`elements\`.`);const f=new Set([...u,...d]);for(const h of c)f.has(h)||r.push(`Element "${h}" is declared in \`elements\` but not referenced by models or markup.`);return{valid:t.length===0,errors:t,warnings:r}},cO=e=>{const t=VE(e);if(!t.valid)throw new Error(`Invalid PIE config contract: ${t.errors.join(" | ")}`)},uO="https://proxy.pie-api.com/bundles/",dO="https://cdn.jsdelivr.net/npm",Kv={retryDelayMs:3e3,timeoutMs:12e4},qs;(function(e){e.player="player.js",e.clientPlayer="client-player.js",e.editor="editor.js",e.esm="esm"})(qs||(qs={}));var Jl;(function(e){e.loading="loading",e.loaded="loaded"})(Jl||(Jl={}));function Xv(e){return typeof e=="function"&&"prototype"in e&&e.prototype instanceof HTMLElement}function fO(e){return e&&typeof e.PIE_REGISTRY=="object"}var Am=()=>{let e;return fO(window)?e=window.PIE_REGISTRY:(e={},window.PIE_REGISTRY=e),e};function Gb(e){const t=Am(),r=t[e.tagName];if(!r||r.status!==Jl.loaded||!hO(e.tagName))return t[e.tagName]=e,e;const n=!r.controller&&!!e.controller,i=r.config==null&&e.config!=null;if(!n&&!i)return r;const o={...r};return n&&(o.controller=e.controller,o.bundleType=e.bundleType),i&&(o.config=e.config),t[e.tagName]=o,o}function hO(e){return typeof customElements<"u"&&customElements.get(e)!==void 0}function bf(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.providerId=="string"&&typeof t.providerName=="string"&&typeof t.initialize=="function"&&typeof t.trackError=="function"&&typeof t.trackEvent=="function"&&typeof t.destroy=="function"&&typeof t.isReady=="function"}var pO=ei("instrumentation-event-bridge",()=>za());function mO(e){if(e===null)return!0;const t=typeof e;if(t==="function"||t==="symbol")return!1;if(t!=="object"||Array.isArray(e))return!0;const r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function gO(e){if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))mO(n)&&(t[r]=n);return t}return typeof e>"u"?{}:{value:e}}function vO(e){pO.warn(`[InstrumentationEventBridge:${e}] Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}function yO(e){try{e.provider.trackError(e.error instanceof Error?e.error:new Error(String(e.error??"Unknown instrumentation bridge error")),{component:e.component,errorType:"InstrumentationBridgeError",sourceEventName:e.sourceEventName})}catch{}}function wf(e){if(!e.host||!e.eventMap.length)return()=>{};if(!e.instrumentationProvider)return()=>{};if(!bf(e.instrumentationProvider))return e.debug&&vO(e.component),()=>{};const t=e.instrumentationProvider,r=[],n=Math.max(0,e.dedupeWindowMs??0),i=new Map,o=(s,a)=>{const l=[a.assessmentId,a.sectionId,a.attemptId,a.itemId,a.canonicalItemId,a.sourceRuntimeId].map(c=>String(c??"")).join("|");return`${s.instrumentationEventName}|${l}`};for(const s of e.eventMap){const a=l=>{try{if(!t.isReady()||e.shouldTrackEvent&&!e.shouldTrackEvent(l))return;const c=gO(l.detail),u=new Date().toISOString(),d={...c,...e.staticAttributes,component:e.component,sourceEventName:s.sourceEventName,timestamp:u};if(n>0){const f=Date.now(),h=o(s,d),g=i.get(h);if(typeof g=="number"&&f-g<n)return;i.set(h,f)}t.trackEvent(s.instrumentationEventName,{...d})}catch(c){yO({provider:t,component:e.component,error:c,sourceEventName:s.sourceEventName})}};e.host.addEventListener(s.sourceEventName,a),r.push(()=>{e.host?.removeEventListener(s.sourceEventName,a)})}return()=>{for(const s of r)s()}}function e1(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function Sc(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(e1(e))return e;if(e1(t))return t}var bO=class{constructor(){T(this,"initialized",!1),T(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}},wO=class extends bO{constructor(...e){super(...e),T(this,"providerId","newrelic"),T(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(Sc()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&Sc()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){Sc()?.noticeError(e,t)}doTrackEvent(e,t){Sc()?.addPageAction(e,t)}doSetUserContext(e,t){const r=Sc();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=Sc();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}};function t1(e){return e&&typeof e=="object"?e:{}}function r1(e){const t=t1(t1(e).loaderConfig);return Object.keys(t).length>0?t:null}function n1(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function i1(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function SO(e,t){return e.kind==="value"||e.kind==="null"?e:t}var rh,IO=ei("instrumentation-provider-resolution",()=>za());function kO(){return rh||(rh=new wO,rh.initialize()),rh}function Au(e){const t=r1(e.runtimePlayer),r=r1(e.player),n=i1(t),i=i1(r),o=n??i??!1,s=SO(n1(t),n1(r));if(s.kind!=="null"){if(s.kind==="unset")return o?kO():void 0;if(bf(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";IO.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var TO=[{sourceEventName:"runtime-owned",instrumentationEventName:"pie-toolkit-runtime-owned"},{sourceEventName:"runtime-inherited",instrumentationEventName:"pie-toolkit-runtime-inherited"},{sourceEventName:"runtime-ready",instrumentationEventName:"pie-toolkit-runtime-ready"},{sourceEventName:"toolkit-ready",instrumentationEventName:"pie-toolkit-ready"},{sourceEventName:"section-ready",instrumentationEventName:"pie-toolkit-section-ready"},{sourceEventName:"framework-error",instrumentationEventName:"pie-toolkit-framework-error"}],$m=[{sourceEventName:"pie-stage-change",instrumentationEventName:"pie-section-stage-change"},{sourceEventName:"pie-loading-complete",instrumentationEventName:"pie-section-loading-complete"},{sourceEventName:"framework-error",instrumentationEventName:"pie-section-framework-error"},{sourceEventName:"element-preload-retry",instrumentationEventName:"pie-section-element-preload-retry"},{sourceEventName:"element-preload-error",instrumentationEventName:"pie-section-element-preload-error"}],EO="",Jv=new Set(["complete","component","elementId","timestamp","sourceRuntimeId"]),CO=new Set(["id","element",...Jv]);function xO(e,t){if(!e&&!t)return!0;if(!e||!t||(e.id||"")!==(t.id||""))return!1;try{return JSON.stringify(e.data||[])===JSON.stringify(t.data||[])}catch{return!1}}function RO(e,t){return!t||e.id!==""?t:{...t,id:""}}function Qv(e,t=EO){if(e&&typeof e=="object"){const r=e;return Array.isArray(r.data)?{id:typeof r.id=="string"?r.id:t,data:r.data}:Array.isArray(e)?{id:t,data:e}:{id:t,data:[e]}}return Array.isArray(e)?{id:t,data:e}:{id:t,data:[]}}function Rp(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>Rp(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"&&r!==void 0&&r!==null&&!(typeof r=="string"&&r.trim()==="")&&!(Array.isArray(r)&&r.length===0)||Rp(r))return!0;return!1}var PO=new Set(["id","element","complete","component","timestamp","sourceRuntimeId","shuffledValues"]);function Zv(e,t){return e==null?!1:typeof e=="string"?e.trim()!=="":typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.some(r=>Zv(r)):typeof e!="object"?!1:Object.entries(e).some(([r,n])=>r==="id"&&t!==void 0&&n===t?!1:Zv(n,r))}function Yb(e){return!e||typeof e!="object"?!1:Array.isArray(e)?e.some(Yb):Object.entries(e).some(([t,r])=>!PO.has(t)&&Zv(r,t))}function Pp(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>Pp(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"||Pp(r))return!0;return!1}function o1(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ga(e,t){if(typeof e.component=="string")return e.component;if(typeof t?.component=="string")return t.component}function Ya(e,t){if(typeof e.complete=="boolean")return e.complete;if(typeof t?.complete=="boolean")return t.complete}function Ka(e,t){const r=typeof e.elementId=="string"&&e.elementId?e.elementId:typeof t?.id=="string"&&t.id?t.id:void 0;return r?{elementId:r}:{}}function GE(e){const t=Object.keys(e);return("id"in e||"element"in e)&&!Pp(e)&&t.every(r=>CO.has(r))}function _O(e){return e.data.length>0&&e.data.every(t=>t&&typeof t=="object"&&!Array.isArray(t)&&GE(t))}function YE(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];r[n]=o1(o)&&o1(i)?YE(o,i):i}return r}function AO(e,t,r,n){const i=Qv(t,e),o=[...i.data],s=o.findIndex(a=>!a||typeof a!="object"?!1:a.id===r);if(s>=0){const a=o[s];o[s]=a&&typeof a=="object"?YE(a,n):n}else o.push(n);return{id:i.id||e,data:o}}function Kb(e){const t=$O(e),r=e.sessionDetail?.sessionCommitReason;return typeof r=="string"&&r?{...t,sessionCommitReason:r}:t}function $O(e){const t=e.sessionDetail||{},r=t&&typeof t=="object"&&"session"in t?t.session:e.sessionDetail,n=typeof e.itemId=="string"&&e.itemId?e.itemId:typeof r?.id=="string"?String(r.id):"";if(!r||typeof r!="object")return{itemId:n,session:null,intent:"metadata-only",component:Ga(t),...Ka(t),complete:Ya(t)};const i=r;if(Array.isArray(i.data)){const l=Qv(i,n),c=RO(l,e.previousItemSession!==void 0?Qv(e.previousItemSession,n):null),u=Object.keys(t),d=u.length>0&&u.every(h=>h==="session"||Jv.has(h)),f=u.some(h=>h!=="session");return d&&f&&c&&xO(l,c)?{itemId:n,session:null,intent:"metadata-only",component:Ga(t),...Ka(t),complete:Ya(t)}:d&&_O(l)?{itemId:n,session:null,intent:"metadata-only",component:Ga(t),...Ka(t),complete:Ya(t)}:{itemId:n,session:l,intent:"replace-item-session",component:Ga(t),...Ka(t),complete:Ya(t)}}const o=Object.keys(i);if(o.length>0&&o.every(l=>Jv.has(l)))return{itemId:n,session:null,intent:"metadata-only",component:Ga(t,i),...Ka(t),complete:Ya(t,i)};if(GE(i))return{itemId:n,session:null,intent:"metadata-only",component:Ga(t,i),...Ka(t,i),complete:Ya(t,i)};const s=Ga(t,i)??"response",a=typeof i.id=="string"&&i.id?i.id:s;return{itemId:n,session:AO(n,e.previousItemSession,a,{id:a,...i}),intent:"merge-element-session",component:s,...Ka(t,i),complete:Ya(t,i)}}var MO="commitPendingSession",KE=Symbol.for("pie.sessionCommit.observedSignature");function XE(e){return!!e&&typeof e=="object"}function JE(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function OO(e){return e?.shadowRoot??null}function LO(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function ey(e,t,r){const n=OO(e);n&&ey(n,t,r);const i=s=>{t.has(s)||(t.add(s),JE(s)&&r.push(s),ey(s,t,r))};for(const s of LO(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function NO(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function DO(e){const t=[],r=new Set;return NO(e)&&JE(e)&&(r.add(e),t.push(e)),ey(e,r,t),t}function jO(e){try{return e.session}catch{return}}function zO(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function BO(e){const t=e[KE];return typeof t=="string"?t:void 0}function s1(e,t){try{Object.defineProperty(e,KE,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function FO(e,t,r){const n=e;if(typeof n.addEventListener!="function")return r();const i=o=>{const s=o.detail;if(!(!XE(s)||"sessionCommitReason"in s))try{s.sessionCommitReason=t}catch{}};n.addEventListener("session-changed",i,!0);try{return r()}finally{n.removeEventListener("session-changed",i,!0)}}function Sf(e,t={}){const r={committed:0,synthesized:0,skipped:0};if(!e)return r;const n=t.reason??"teardown";return FO(e,n,()=>HO(e,n,t.logger,r))}function HO(e,t,r,n){const i=t?"commitPendingSessions":"flushPendingSessionNotifications";for(const o of DO(e)){const s=jO(o);if(!XE(s)){n.skipped+=1;continue}const a=zO(s);if(a===null){n.skipped+=1;continue}const l=BO(o);if(l===a){n.skipped+=1;continue}if(l===void 0&&!Yb(s)){n.skipped+=1;continue}const c=o[MO];if(typeof c=="function"){let u=!1;const d=()=>{u=!0};o.addEventListener("session-changed",d,!0);let f=!1;try{c.call(o)}catch(h){f=!0,r?.warn(`[${i}] ${o.tagName.toLowerCase()} failed to commit its pending session`,h)}finally{o.removeEventListener("session-changed",d,!0)}if(f){n.skipped+=1;continue}if(u){s1(o,a),n.committed+=1;continue}}try{o.dispatchEvent(new CustomEvent("session-changed",{bubbles:!0,composed:!0,detail:{component:o.tagName.toLowerCase(),session:JSON.parse(a),...t?{sessionCommitReason:t}:{}}})),s1(o,a),n.synthesized+=1}catch(u){r?.warn(`[${i}] ${o.tagName.toLowerCase()} session commit dispatch failed`,u),n.skipped+=1}}return n}function UO(e){if(typeof document>"u"||typeof window>"u")return()=>{};const t=i=>{Sf(e.root(),{reason:i,logger:e.logger});try{e.onHidden?.(i)}catch(o){e.logger?.warn("[bindPageLifecycleCommit] onHidden failed",o)}},r=()=>{document.visibilityState==="hidden"&&t("page-hidden")},n=()=>{t("page-hidden")};return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",n),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",n)}}var _p="pie-register",QE="pie-unregister",ZE="pie-item-session-changed",qO="item-session-changed",Xb="pie-content-loaded",eC="pie-item-player-error",WO="pie-formative-action",VO="pie-media-time-source",kg=e=>Array.isArray(e)&&e.length>0;function tC(e){return e.kind==="passage"?{ownerKind:"passage",assessmentId:e.assessmentId,sectionId:e.sectionId,passageId:e.canonicalItemId||e.itemId}:{ownerKind:"itemModel",assessmentId:e.assessmentId,sectionId:e.sectionId,itemId:e.itemId,canonicalItemId:e.canonicalItemId||e.itemId}}function rC(e,t){if(!e)return[];let r=tC(t),n=[];if(kg(e.accessibilityCatalogs)&&n.push({context:r,catalogs:e.accessibilityCatalogs}),kg(e.config?.extractedCatalogs)&&n.push({context:r,catalogs:e.config.extractedCatalogs}),t.kind==="passage"||r.ownerKind!=="itemModel")return n;for(let i of e.config?.models??[])kg(i.accessibilityCatalogs)&&n.push({context:{...r,modelId:i.id},catalogs:i.accessibilityCatalogs});return n}function ty(e,t){let r=rC(e,{kind:t,itemId:""});try{return JSON.stringify(r.map(n=>[n.context.modelId??null,n.catalogs]))}catch{return null}}var Ql=class{constructor(e,t){T(this,"host",void 0),T(this,"context",void 0),T(this,"currentValue",void 0),T(this,"subscriptions",new Map),T(this,"detachedSubscribers",[]),T(this,"isConnected",!1),T(this,"handleContextRequest",r=>{if(r.context!==this.context)return;const n=this.getContextTarget(r,this.host);if(n===this.host)return;if(r.stopPropagation(),!r.subscribe){r.callback(this.currentValue);return}const i=r.callback;let o=this.subscriptions.get(i);if(o)o.consumerHost=n;else{const s={consumerHost:n,callback:i,unsubscribe:()=>{this.subscriptions.get(i)===s&&this.subscriptions.delete(i)}};this.subscriptions.set(i,s),o=s}i(this.currentValue,o.unsubscribe)}),T(this,"handleContextProvider",r=>{if(r.context===this.context&&this.getContextTarget(r,this.host)!==this.host){for(const n of[...this.subscriptions.values()])this.requestAgain(n);r.stopPropagation()}}),this.host=e,this.context=t.context,this.currentValue=t.initialValue}connect(){if(this.isConnected)return;this.isConnected=!0,this.host.addEventListener("context-request",this.handleContextRequest),this.host.addEventListener("context-provider",this.handleContextProvider);const e=this.detachedSubscribers;this.detachedSubscribers=[];for(const t of e)t.consumerHost.isConnected&&this.requestAgain(t);this.host.dispatchEvent(new OA(this.context,this.host))}disconnect(){if(!this.isConnected)return;this.isConnected=!1,this.host.removeEventListener("context-request",this.handleContextRequest),this.host.removeEventListener("context-provider",this.handleContextProvider);const e=[...this.subscriptions.values()];this.subscriptions.clear();for(const t of e)t.consumerHost.isConnected?this.requestAgain(t):this.detachedSubscribers.push(t)}setValue(e,t=!1){!t&&Object.is(this.currentValue,e)||(this.currentValue=e,this.notifySubscribers())}get value(){return this.currentValue}getContextTarget(e,t){if("contextTarget"in e&&e.contextTarget)return e.contextTarget;const r=(typeof e.composedPath=="function"?e.composedPath():[])[0];return r||t}requestAgain({consumerHost:e,callback:t}){e.dispatchEvent(new LA(this.context,e,t,!0))}notifySubscribers(){for(const e of this.subscriptions.values())e.callback(this.currentValue,e.unsubscribe)}},a1,l1,nC,iC,GO="5";typeof window<"u"&&((a1=(l1=window).__svelte??(l1.__svelte={})).v??(a1.v=new Set)).add(GO);var Zn=2,$u=4,If=8,Jb=16777216,Jo=16,So=32,As=64,Qb=128,Zb=256,Uo=512,wn=1024,hn=2048,Ki=4096,di=8192,fi=16384,Ha=32768,Ap=33554432,su=65536,$p=131072,YO=262144,fc=524288,KO=1048576,ws=33554432,Mp=2097152,au=4194304,_a=8388608,Al=Symbol("$state"),oC=Symbol("component"),sC=Symbol("legacy props"),XO=Symbol(""),ry=Symbol("attributes"),ny=Symbol("class"),JO=Symbol("style"),qh=Symbol("text"),kf=new class extends Error{constructor(...e){super(...e),T(this,"name","StaleReactionError"),T(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},QO=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),Mm=3,Mu=8,ZO=1,e2=2,aC=4,t2=8,r2=16,n2=1,i2=2,o2=4,s2=8,a2=16,l2=1,c2=2,lC="[",e0="[!",c1="[?",t0="]",Zl={},Pn=Symbol("uninitialized"),cC="http://www.w3.org/1999/xhtml",u2="http://www.w3.org/2000/svg",d2="http://www.w3.org/1998/Math/MathML";function f2(){console.warn("https://svelte.dev/e/derived_inert")}function Tf(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function h2(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var uC=Array.isArray,p2=Array.prototype.indexOf,Op=Array.prototype.includes,Om=Array.from,Lp=Object.keys,Bd=Object.defineProperty,$l=Object.getOwnPropertyDescriptor,dC=Object.getOwnPropertyDescriptors,m2=Object.prototype,g2=Array.prototype,r0=Object.getPrototypeOf,u1=Object.isExtensible,v2=()=>{};function y2(e){for(var t=0;t<e.length;t++)e[t]()}function fC(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function b2(e){var t=qt;if(t===null)return lr.f|=_a,e;if((t.f&Ha)===0&&(t.f&$u)===0)throw e;Ts(e,t)}function Ts(e,t){if(!(t!==null&&(t.f&fi)!==0)){for(;t!==null;){if((t.f&Qb)!==0&&(t.f&(fi|Ap))===0){if((t.f&Ha)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function w2(){throw Error("https://svelte.dev/e/async_derived_orphan")}function S2(e,t,r){throw Error("https://svelte.dev/e/each_key_duplicate")}function I2(e){throw Error("https://svelte.dev/e/effect_in_teardown")}function k2(){throw Error("https://svelte.dev/e/effect_in_unowned_derived")}function T2(e){throw Error("https://svelte.dev/e/effect_orphan")}function E2(){throw Error("https://svelte.dev/e/effect_update_depth_exceeded")}function C2(){throw Error("https://svelte.dev/e/hydration_failed")}function x2(e){throw Error("https://svelte.dev/e/props_invalid_value")}function R2(){throw Error("https://svelte.dev/e/state_descriptors_fixed")}function P2(){throw Error("https://svelte.dev/e/state_prototype_fixed")}function _2(){throw Error("https://svelte.dev/e/state_unsafe_mutation")}function A2(){throw Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var Ua=!1,Lm=!1,Sn=null;function lu(e){Sn=e}function Ef(e,t=!1,r){Sn={p:Sn,i:!1,c:null,e:null,s:e,x:null,r:qt,l:Lm&&!t?{s:null,u:null,$:[]}:null}}function Cf(e){var t=Sn,r=t.e;if(r!==null){t.e=null;for(var n of r)AC(n)}return e!==void 0&&(t.x=e),t.i=!0,Sn=t.p,n0(e)}function n0(e={}){return Bd(e,oC,{value:!0}),e}function Ou(){return!Lm||Sn!==null&&Sn.l===null}var vl=[];function hC(){var e=vl;vl=[],y2(e)}function Na(e){if(vl.length===0&&!Td){var t=vl;queueMicrotask(()=>{t===vl&&hC()})}vl.push(e)}function $2(){for(;vl.length>0;)hC()}function pC(e){return e===this.v}function mC(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function gC(e){return!mC(e,this.v)}function Nm(e){var t=lr,r=qt;Ci(null),vo(null);try{return e()}finally{Ci(t),vo(r)}}function M2(e,t,r,n){let i=Ou()?Fd:o0;var o=e.filter(h=>!h.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=qt,l=O2(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(h=>h.promise)):null;function u(h){if((a.f&fi)===0){l();try{n([...s,...h])}catch(g){Ts(g,a)}Np()}}var d=vC();if(r.length===0){c.then(()=>u([])).finally(d);return}function f(){Promise.all(r.map(h=>N2(h))).then(u).catch(h=>Ts(h,a)).finally(d)}c?c.then(()=>{l(),f(),Np()}):f()}function O2(){var e=qt,t=lr,r=Sn,n=Xt;return function(i=!0){vo(e),Ci(t),lu(r),i&&(e.f&fi)===0&&(n?.activate(),n?.apply())}}function Np(e=!0){vo(null),Ci(null),lu(null),e&&Xt?.deactivate()}function vC(){var e=qt,t=e.b,r=Xt,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}var L2=~(hn|Ki|wn);function dn(e,t){e.f=e.f&L2|t}function i0(e){(e.f&Uo)!==0||e.deps===null?dn(e,wn):dn(e,Ki)}function Fd(e){var t=Zn|hn;return qt!==null&&(qt.f|=fc),{ctx:Sn,deps:null,effects:null,equals:pC,f:t,fn:e,reactions:null,rv:0,v:Pn,wv:0,parent:qt,ac:null}}var ud=Symbol("obsolete");function N2(e,t,r){let n=qt;n===null&&w2();var i=void 0,o=ec(Pn),s=!lr,a=new Set;return X2(()=>{var l=qt,c=fC();i=c.promise;try{Promise.resolve(e()).then(c.resolve,h=>{h!==kf&&c.reject(h)}).finally(Np)}catch(h){c.reject(h),Np()}var u=Xt;if(s){if((l.f&Ha)!==0)var d=vC();if(n.b?.is_rendered())u.async_deriveds.get(l)?.reject(ud);else for(let h of a.values())h.reject(ud);a.add(c),u.async_deriveds.set(l,c)}let f=(h,g=void 0)=>{d?.(),a.delete(c),g!==ud&&(u.activate(),g?(o.f|=_a,cu(o,g)):((o.f&_a)!==0&&(o.f^=_a),cu(o,h)),u.deactivate())};c.promise.then(f,h=>f(null,h||"unknown"))}),G2(()=>{for(let l of a)l.reject(ud)}),new Promise(l=>{function c(u){function d(){u===i?l(o):c(i)}u.then(d,d)}c(i)})}function Xe(e){let t=Fd(e);return Ua||DC(t),t}function o0(e){let t=Fd(e);return t.equals=gC,t}function D2(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)hi(t[r])}}function s0(e){var t,r=qt,n=e.parent;if(!ea&&n!==null&&e.v!==Pn&&(n.f&(fi|di))!==0)return f2(),e.v;vo(n);try{D2(e),t=FC(e)}finally{vo(r)}return t}function yC(e){var t=s0(e);if(!e.equals(t)&&(e.wv=zC(),(!Xt?.is_fork||e.deps===null)&&(Xt!==null?(Xt.capture(e,t,!0),oy?.capture(e,t,!0)):e.v=t,e.deps===null))){dn(e,wn);return}ea||(ai!==null?(c0()||Xt?.is_fork)&&ai.set(e,t):i0(e))}function j2(e){if(e.effects!==null)for(let t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&Nm(()=>{t.ac.abort(kf),t.ac=null}),t.fn!==null&&(t.teardown=v2),Ud(t,0),d0(t))}function bC(e){if(e.effects!==null)for(let t of e.effects)t.teardown&&t.fn!==null&&uu(t)}var Dp=new Set,Es=new Map,wC=!1;function ec(e,t){return{f:0,v:e,reactions:null,equals:pC,rv:0,wv:0}}function Lr(e,t){let r=ec(e,t);return DC(r),r}function SC(e,t=!1,r=!0){var n;let i=ec(e);return t||(i.equals=gC),Lm&&r&&Sn!==null&&Sn.l!==null&&((n=Sn.l).s??(n.s=[])).push(i),i}function Ut(e,t,r=!1){return lr!==null&&(!Lo||(lr.f&$p)!==0)&&Ou()&&(lr.f&(Zn|Jo|au|$p))!==0&&(qo===null||!qo.has(e))&&_2(),cu(e,r?Ea(t):t,zp)}var dl=null,iy=0;function cu(e,t,r=null){if(!e.equals(t)){ea?Es.set(e,t):Es.has(e)||Es.set(e,e.v);var n=hc.ensure();if(n.capture(e,t),(e.f&Zn)!==0){let i=e;(e.f&hn)!==0&&s0(i),ai===null&&i0(i)}e.wv=zC(),dl=null,iy=0,IC(e,hn,r),dl=null,Ou()&&qt!==null&&(qt.f&wn)!==0&&(qt.f&(So|As))===0&&(io===null?Z2([e]):io.push(e)),!n.is_fork&&Dp.size>0&&!wC&&z2()}return t}function z2(){wC=!1;for(let e of Dp){(e.f&wn)!==0&&dn(e,Ki);let t;try{t=xf(e)}catch{t=!0}t&&uu(e)}Dp.clear()}function kd(e){Ut(e,e.v+1)}function IC(e,t,r){var n=e.reactions;if(n!==null){var i=Ou(),o=n.length;if(iy+=o,iy>1e5&&dl===null&&(dl=new Set),dl!==null){if(dl.has(e))return;dl.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===qt)){var c=(l&hn)===0;if(c&&dn(a,t),(l&$p)!==0)Dp.add(a);else if((l&Zn)!==0){var u=a;ai?.delete(u),IC(u,Ki,r)}else if(c){var d=a;(l&Jo)!==0&&hs!==null&&hs.add(d),r!==null?r.push(d):l0(d)}}}}}function kC(e,t,r){(e.f&hn)!==0?t.add(e):(e.f&Ki)!==0&&r.add(e),dn(e,wn)}var jp=null,Lc=null,Xt=null,oy=null,ai=null,sy=null,Td=!1,Tg=!1,Hd=null,zp=null,TC=0,B2=1,Bp=new WeakMap,Ml=new WeakMap,yl=new WeakMap,Fp=new WeakMap,nh=new WeakMap,Nc=new WeakMap,al=new WeakMap,dd=new WeakMap,_o=new WeakMap,ay=new WeakMap,tc=new WeakMap,Ks=new WeakMap,ka=new WeakMap,Wh=new WeakMap,fd=new WeakMap,rn=new WeakSet,hc=class EC{constructor(){Eu(this,rn),T(this,"id",B2++),Me(this,Bp,!1),T(this,"linked",!0),Me(this,Ml,null),Me(this,yl,null),T(this,"async_deriveds",new Map),T(this,"current",new Map),T(this,"previous",new Map),Me(this,Fp,new Set),Me(this,nh,new Set),Me(this,Nc,0),Me(this,al,new Map),Me(this,dd,null),Me(this,_o,[]),Me(this,ay,[]),Me(this,tc,new Set),Me(this,Ks,new Set),Me(this,ka,new Map),Me(this,Wh,new Set),T(this,"is_fork",!1),Me(this,fd,!1),Lc===null?jp=Lc=this:(xe(yl,Lc,this),xe(Ml,this,Lc)),Lc=this}skip_effect(t){w(ka,this).has(t)||w(ka,this).set(t,{d:[],m:[]}),w(Wh,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=w(ka,this).get(t);if(n){w(ka,this).delete(t);for(var i of n.d)dn(i,hn),r(i);for(i of n.m)dn(i,Ki),r(i)}w(Wh,this).add(t)}capture(t,r,n=!1){t.v!==Pn&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&_a)===0&&(this.current.set(t,[r,n]),ai?.set(t,r)),this.is_fork||(t.v=r)}activate(){Xt=this}deactivate(){Xt=null,ai=null}flush(){try{Tg=!0,Xt=this,ze(rn,this,Hp).call(this)}finally{TC=0,sy=null,Hd=null,zp=null,Tg=!1,Xt=null,ai=null,Es.clear()}}discard(){for(let t of w(nh,this))t(this);w(nh,this).clear();for(let t of this.async_deriveds.values())t.reject(ud);ze(rn,this,Up).call(this),w(dd,this)?.resolve()}register_created_effect(t){w(ay,this).push(t)}increment(t,r){if(xe(Nc,this,w(Nc,this)+1),t){let n=w(al,this).get(r)??0;w(al,this).set(r,n+1)}}decrement(t,r){if(xe(Nc,this,w(Nc,this)-1),t){let n=w(al,this).get(r)??0;n===1?w(al,this).delete(r):w(al,this).set(r,n-1)}w(fd,this)||(xe(fd,this,!0),Na(()=>{xe(fd,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(let n of t)w(tc,this).add(n);for(let n of r)w(Ks,this).add(n);t.clear(),r.clear()}oncommit(t){w(Fp,this).add(t)}ondiscard(t){w(nh,this).add(t)}settled(){return(w(dd,this)??xe(dd,this,fC())).promise}static ensure(){if(Xt===null){let t=Xt=new EC;!Tg&&!Td&&Na(()=>{w(Bp,t)||t.flush()})}return Xt}apply(){if(!Ua||!this.is_fork&&w(Ml,this)===null&&w(yl,this)===null){ai=null;return}ai=new Map;for(let[r,[n]]of this.current)ai.set(r,n);for(let r=jp;r!==null;r=w(yl,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(let[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(let[n,i]of r.previous)ai.has(n)||ai.set(n,i)}}schedule(t){if(sy=t,t.b?.is_pending&&(t.f&($u|If|Jb))!==0&&(t.f&Ha)===0){t.b.defer_effect(t);return}w(_o,this).push(t)}};nC=hc;function d1(){if(this.is_fork)return!0;for(let r of w(al,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(w(ka,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function CC(){var e=[];for(let i of w(_o,this))if(!((i.f&fi)!==0||(i.f&(hn|Ki))===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&(As|So))!==0){if((n&wn)===0){r=!0;break}t.f^=wn}}r||e.push(t)}return xe(_o,this,[]),e}function Hp(){xe(Bp,this,!0);for(let s of w(tc,this))w(Ks,this).delete(s),dn(s,hn),this.schedule(s);for(let s of w(Ks,this))dn(s,Ki),this.schedule(s);this.apply();for(var e=Hd=[],t=[],r=zp=[];w(_o,this).length>0;){TC++>1e3&&(ze(rn,this,Up).call(this),q2());for(let s of ze(rn,this,CC).call(this))try{ze(rn,this,xC).call(this,s,e,t)}catch(a){throw _C(s),!ze(rn,this,d1).call(this)&&this.discard(),a}}if(Xt=null,r.length>0){var n=nC.ensure();for(let s of r)n.schedule(s)}if(Hd=null,zp=null,ze(rn,this,d1).call(this)){ze(rn,this,hd).call(this,t),ze(rn,this,hd).call(this,e);for(let[s,a]of w(ka,this))PC(s,a);r.length>0&&ze(rn,Xt,Hp).call(Xt);return}let i=ze(rn,this,F2).call(this);if(i){ze(rn,this,hd).call(this,t),ze(rn,this,hd).call(this,e),ze(rn,i,H2).call(i,this);return}w(tc,this).clear(),w(Ks,this).clear();for(let s of w(Fp,this))s(this);w(Fp,this).clear(),oy=this,f1(t),f1(e),oy=null,w(dd,this)?.resolve();var o=Xt;if(w(Nc,this)===0&&(w(_o,this).length===0||o!==null)&&(ze(rn,this,Up).call(this),Ua&&(ze(rn,this,U2).call(this),Xt=o)),w(_o,this).length>0)if(o!==null){for(let s of w(_o,this))w(_o,o).push(s);xe(_o,this,[])}else o=this;o!==null&&(Es.clear(),ze(rn,o,Hp).call(o))}function xC(e,t,r){e.f^=wn;for(var n=e.first;n!==null;){var i=n.f,o=(i&(So|As))!==0;if(!(o&&(i&wn)!==0||(i&di)!==0||w(ka,this).has(n))&&n.fn!==null){o?n.f^=wn:(i&$u)!==0?t.push(n):Ua&&(i&(If|Jb))!==0?r.push(n):xf(n)&&((i&Jo)!==0&&w(Ks,this).add(n),uu(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function F2(){for(var e=w(Ml,this);e!==null;){if(!e.is_fork){for(let[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=w(Ml,e)}return null}function H2(e){for(let[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(let[r,n]of e.async_deriveds){let i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(w(tc,e),w(Ks,e));let t=r=>{var n=r.reactions;if(n!==null&&!((r.f&Zn)!==0&&(r.f&(hn|Ki))===0))for(let s of n){var i=s.f;if((i&Zn)!==0)t(s);else{var o=s;i&(au|Jo)&&!this.async_deriveds.has(o)&&(w(Ks,this).delete(o),dn(o,hn),this.schedule(o))}}};for(let r of this.current.keys())t(r);this.oncommit(()=>e.discard()),ze(rn,e,Up).call(e),Xt=this,ze(rn,this,Hp).call(this)}function hd(e){for(var t=0;t<e.length;t+=1)kC(e[t],w(tc,this),w(Ks,this))}function U2(){for(let u=jp;u!==null;u=w(yl,u)){var e=u.id<this.id,t=[];for(let[d,[f,h]]of this.current){if(u.current.has(d)){var r=u.current.get(d)[0];if(e&&f!==r)u.current.set(d,[f,h]);else continue}t.push(d)}if(e)for(let[d,f]of this.async_deriveds){let h=u.async_deriveds.get(d);h&&f.promise.then(h.resolve).catch(h.reject)}var n=[...u.current.keys()].filter(d=>!u.current.get(d)[1]);if(!(!w(Bp,u)||n.length===0)){var i=n.filter(d=>!this.current.has(d));if(i.length===0)e&&u.discard();else if(t.length>0){if(e)for(let d of w(Wh,this))u.unskip_effect(d,f=>{(f.f&(Jo|au))!==0?u.schedule(f):ze(rn,u,hd).call(u,[f])});u.activate();var o=new Set,s=new Map;for(var a of t)RC(a,i,o,s);s=new Map;var l=[...u.current].filter(([d,f])=>{let h=this.current.get(d);return h?h[0]!==f[0]||h[1]!==f[1]:!0}).map(([d])=>d);if(l.length>0)for(let d of w(ay,this))(d.f&(fi|di|$p))===0&&a0(d,l,s)&&((d.f&(au|Jo))!==0?(dn(d,hn),u.schedule(d)):w(tc,u).add(d));if(w(_o,u).length>0&&!w(fd,u)){u.apply();for(var c of ze(rn,u,CC).call(u))ze(rn,u,xC).call(u,c,[],[])}u.deactivate()}}}}function Up(){if(this.linked){var e=w(Ml,this),t=w(yl,this);e===null?jp=t:xe(yl,e,t),t===null?Lc=e:xe(Ml,t,e),this.linked=!1}}function ct(e){var t=Td;Td=!0;try{var r;for(e&&(Xt!==null&&!Xt.is_fork&&Xt.flush(),r=e());;){if($2(),Xt===null)return r;Xt.flush()}}finally{Td=t}}function q2(){try{E2()}catch(e){Ts(e,sy)}}var hs=null;function f1(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&(fi|di))===0&&xf(n)&&(hs=new Set,uu(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&OC(n),hs?.size>0)){Es.clear();for(let i of hs){if((i.f&(fi|di))!==0)continue;let o=[i],s=i.parent;for(;s!==null;)hs.has(s)&&(hs.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){let l=o[a];(l.f&(fi|di))===0&&uu(l)}}hs.clear()}}hs=null}}function RC(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(let i of e.reactions){let o=i.f;(o&Zn)!==0?RC(i,t,r,n):(o&(au|Jo))!==0&&(o&hn)===0&&a0(i,t,n)&&(dn(i,hn),l0(i))}}function a0(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(let i of e.deps){if(Op.call(t,i))return!0;if((i.f&Zn)!==0&&a0(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function l0(e){Xt.schedule(e)}function PC(e,t){if(!((e.f&So)!==0&&(e.f&wn)!==0)){(e.f&hn)!==0?t.d.push(e):(e.f&Ki)!==0&&t.m.push(e),dn(e,wn);for(var r=e.first;r!==null;)PC(r,t),r=r.next}}function _C(e){dn(e,wn);for(var t=e.first;t!==null;)_C(t),t=t.next}function W2(e){qt===null&&(lr===null&&T2(e),k2()),ea&&I2(e)}function V2(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function $s(e,t){var r=qt;r!==null&&(r.f&di)!==0&&(e|=di);var n={ctx:Sn,deps:null,nodes:null,f:e|hn|Uo,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};Xt?.register_created_effect(n);var i=n;if((e&$u)!==0)Hd!==null?Hd.push(n):hc.ensure().schedule(n);else if(t!==null){try{uu(n)}catch(s){throw hi(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&fc)===0&&(i=i.first,(e&Jo)!==0&&(e&su)!==0&&i!==null&&(i.f|=su))}if(i!==null&&(i.parent=r,r!==null&&V2(i,r),lr!==null&&(lr.f&Zn)!==0&&(e&As)===0)){var o=lr;(o.effects??(o.effects=[])).push(i)}return n}function c0(){return lr!==null&&!Lo}function G2(e){let t=$s(If,null);return dn(t,wn),t.teardown=e,t}function Ot(e){W2("$effect");var t=qt.f;if(!lr&&(t&So)!==0&&Sn!==null&&!Sn.i){var r=Sn;(r.e??(r.e=[])).push(e)}else return AC(e)}function AC(e){return $s($u|KO,e)}function Y2(e){hc.ensure();let t=$s(As|fc,e);return()=>{hi(t)}}function K2(e){hc.ensure();let t=$s(As|fc,e);return(r={})=>new Promise(n=>{r.outro?pc(t,()=>{hi(t),n(void 0)}):(hi(t),n(void 0))})}function u0(e){return $s($u,e)}function X2(e){return $s(au|fc,e)}function Dm(e,t=0){return $s(If|t,e)}function nn(e,t=[],r=[],n=[]){M2(n,t,r,i=>{$s(If,()=>{e(...i.map(y))})})}function jm(e,t=0){return $s(Jo|t,e)}function go(e){return $s(So|fc,e)}function $C(e){var t=e.teardown;if(t!==null){let r=ea,n=lr;h1(!0),Ci(null);try{t.call(null)}catch(i){Ts(i,e.parent)}finally{h1(r),Ci(n)}}}function d0(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){let i=r.ac;i!==null&&Nm(()=>{i.abort(kf)});var n=r.next;(r.f&As)!==0?r.parent=null:hi(r,t),r=n}}function J2(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&So)===0&&hi(t),t=r}}function hi(e,t=!0){var r=!1;(t||(e.f&YO)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(MC(e.nodes.start,e.nodes.end),r=!0),e.f|=Ap,d0(e,t&&!r),Ud(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(let o of n)o.stop();$C(e),e.f^=Ap,e.f|=fi;var i=e.parent;i!==null&&i.first!==null&&OC(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function MC(e,t){for(;e!==null;){var r=e===t?null:Zo(e);e.remove(),e=r}}function OC(e){var{parent:t,prev:r,next:n}=e;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function pc(e,t,r=!0){var n=[];e.f|=Zb,LC(e,n,!0);var i=()=>{r&&hi(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function LC(e,t,r){if((e.f&di)===0){e.f^=di;var n=e.nodes&&e.nodes.t;if(n!==null)for(let a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&As)===0){var s=(i.f&su)!==0||(i.f&So)!==0&&(e.f&Jo)!==0;LC(i,t,s?r:!1)}i=o}}}function qp(e){e.f&=~Zb,NC(e,!0)}function NC(e,t){if((e.f&Zb)===0&&(e.f&di)!==0){e.f^=di,(e.f&wn)===0&&(dn(e,hn),hc.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&su)!==0||(r.f&So)!==0;NC(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(let s of o)(s.is_global||t)&&s.in()}}function f0(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:Zo(r);t.append(r),r=i}}var Q2=null,Vh=!1,ea=!1;function h1(e){ea=e}var lr=null,Lo=!1;function Ci(e){lr=e}var qt=null;function vo(e){qt=e}var qo=null;function DC(e){lr!==null&&(!Ua&&(lr.f&Mp)!==0||(lr.f&Zn)!==0)&&(qo??(qo=new Set)).add(e)}var bi=null,ji=0,io=null;function Z2(e){io=e}var jC=1,bl=0,Ol=bl;function p1(e){Ol=e}function zC(){return++jC}function xf(e){var t=e.f;if((t&hn)!==0)return!0;if((t&Ki)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(xf(o)&&yC(o),o.wv>e.wv)return!0}(t&Uo)!==0&&ai===null&&dn(e,wn)}return!1}function BC(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!Ua&&qo!==null&&qo.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&Zn)!==0?BC(o,t,!1):t===o&&(r?dn(o,hn):(o.f&wn)!==0&&dn(o,Ki),l0(o))}}function FC(e){var t=bi,r=ji,n=io,i=lr,o=qo,s=Sn,a=Lo,l=Ol,c=e.f;bi=null,ji=0,io=null,lr=(c&(So|As))===0?e:null,qo=null,lu(e.ctx),Lo=!1,Ol=++bl,e.ac!==null&&(Nm(()=>{e.ac.abort(kf)}),e.ac=null);try{e.f|=Mp;var u=e.fn,d=u();e.f|=Ha;var f=m1(e);if(Ou()&&io!==null&&!Lo&&f!==null&&(e.f&(Zn|Ki|hn))===0)for(var h=0;h<io.length;h++)BC(io[h],e);if(i!==null&&i!==e){if(bl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=bl;if(t!==null)for(let g of t)g.rv=bl;io!==null&&(n===null?n=io:n.push(...io))}return(e.f&_a)!==0&&(e.f^=_a),d}catch(g){return m1(e),b2(g)}finally{e.f^=Mp,bi=t,ji=r,io=n,lr=i,qo=o,lu(s),Lo=a,Ol=l}}function m1(e){var t=e.deps,r=Xt?.is_fork;if(bi!==null){var n,i;if(r||Ud(e,ji),t!==null&&ji>0)for(t.length=ji+bi.length,i=0;i<bi.length;i++)t[ji+i]=bi[i];else e.deps=t=bi;if(c0()&&(e.f&Uo)!==0)for(i=ji;i<t.length;i++)((n=t[i]).reactions??(n.reactions=[])).push(e)}else!r&&t!==null&&ji<t.length&&(Ud(e,ji),t.length=ji);return t}function eL(e,t){let r=t.reactions;if(r!==null){var n=p2.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&Zn)!==0&&(bi===null||!Op.call(bi,t))){var o=t;(o.f&Uo)!==0&&(o.f^=Uo),o.v!==Pn&&i0(o),o.ac!==null&&Nm(()=>{o.ac.abort(kf),o.ac=null,dn(o,hn)}),j2(o),Ud(o,0)}}function Ud(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)eL(e,r[n])}function uu(e){var t=e.f;if((t&fi)===0){dn(e,wn);var r=qt,n=Vh;qt=e,Vh=(t&(So|As))===0;try{(t&(Jo|Jb))!==0?J2(e):d0(e),$C(e);var i=FC(e);e.teardown=typeof i=="function"?i:null,e.wv=jC}finally{Vh=n,qt=r}}}function y(e){var t=(e.f&Zn)!==0;if(Q2?.add(e),lr!==null&&!Lo&&!(qt!==null&&(qt.f&fi)!==0)&&(qo===null||!qo.has(e))){var r=lr.deps;if((lr.f&Mp)!==0)e.rv<bl&&(e.rv=bl,bi===null&&r!==null&&r[ji]===e?ji++:bi===null?bi=[e]:bi.push(e));else{var n;(n=lr).deps??(n.deps=[]),!Op.call(lr.deps,e)&&lr.deps.push(e);var i=e.reactions;i===null?e.reactions=[lr]:Op.call(i,lr)||i.push(lr)}}if(ea&&Es.has(e))return Es.get(e);if(t){var o=e;if(ea){var s=o.v;return((o.f&wn)===0&&o.reactions!==null||UC(o))&&(s=s0(o)),Es.set(o,s),s}var a=(o.f&Uo)===0&&!Lo&&lr!==null&&(Vh||(lr.f&Uo)!==0),l=(o.f&Ha)===0;xf(o)&&(a&&(o.f|=Uo),yC(o)),a&&!l&&(bC(o),HC(o))}if(ai?.has(e))return ai.get(e);if((e.f&_a)!==0)throw e.v;return e.v}function HC(e){if(e.f|=Uo,e.deps!==null)for(let t of e.deps)(t.reactions??(t.reactions=[])).push(e),(t.f&Zn)!==0&&(t.f&Uo)===0&&(bC(t),HC(t))}function UC(e){if(e.v===Pn)return!0;if(e.deps===null)return!1;for(let t of e.deps)if(Es.has(t)||(t.f&Zn)!==0&&UC(t))return!0;return!1}function Wr(e){var t=Lo;try{return Lo=!0,e()}finally{Lo=t}}function tL(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(Al in e)ly(e);else if(!Array.isArray(e))for(let t in e){let r=e[t];typeof r=="object"&&r&&Al in r&&ly(r)}}}function ly(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{ly(e[n],t)}catch{}let r=r0(e);if(r!==Object.prototype&&r!==Array.prototype&&r!==Map.prototype&&r!==Set.prototype&&r!==Date.prototype){let n=dC(r);for(let i in n){let o=n[i].get;if(o)try{o.call(e)}catch{}}}}}function Ea(e){if(typeof e!="object"||e===null||Al in e||oC in e)return e;let t=r0(e);if(t!==m2&&t!==g2)return e;var r=new Map,n=uC(e),i=Lr(0),o=null,s=Ol,a=l=>{if(Ol===s)return l();var c=lr,u=Ol;Ci(null),p1(s);var d=l();return Ci(c),p1(u),d};return n&&r.set("length",Lr(e.length,o)),new Proxy(e,{defineProperty(l,c,u){(!("value"in u)||u.configurable===!1||u.enumerable===!1||u.writable===!1)&&R2();var d=r.get(c);return d===void 0?a(()=>{var f=Lr(u.value,o);return r.set(c,f),f}):Ut(d,u.value,!0),!0},deleteProperty(l,c){var u=r.get(c);if(u===void 0){if(c in l){let d=a(()=>Lr(Pn,o));r.set(c,d),kd(i)}}else Ut(u,Pn),kd(i);return!0},get(l,c,u){if(c===Al)return e;var d=r.get(c),f=c in l;if(d===void 0&&(!f||$l(l,c)?.writable)&&(d=a(()=>Lr(Ea(f?l[c]:Pn),o)),r.set(c,d)),d!==void 0){var h=y(d);return h===Pn?void 0:h}return Reflect.get(l,c,u)},getOwnPropertyDescriptor(l,c){this.has?.(l,c);var u=Reflect.getOwnPropertyDescriptor(l,c),d=r.get(c);if(d!==void 0){var f=y(d);if(f===Pn)return;if(u&&"value"in u)u.value=f;else return{enumerable:!0,configurable:!0,value:f,writable:!0}}return u},has(l,c){if(c===Al)return!0;var u=r.get(c),d=u!==void 0&&u.v!==Pn||Reflect.has(l,c);return(u!==void 0||qt!==null&&(!d||$l(l,c)?.writable))&&(u===void 0&&(u=a(()=>Lr(d?Ea(l[c]):Pn,o)),r.set(c,u)),y(u)===Pn)?!1:d},set(l,c,u,d){var f=r.get(c),h=c in l;if(n&&c==="length")for(var g=u;g<f.v;g+=1){var m=r.get(g+"");m!==void 0?Ut(m,Pn):g in l&&(m=a(()=>Lr(Pn,o)),r.set(g+"",m))}if(f===void 0)(!h||$l(l,c)?.writable)&&(f=a(()=>Lr(void 0,o)),Ut(f,Ea(u)),r.set(c,f));else{h=f.v!==Pn;var v=a(()=>Ea(u));Ut(f,v)}var b=Reflect.getOwnPropertyDescriptor(l,c);if(b?.set&&b.set.call(d,u),!h){if(n&&typeof c=="string"){var I=r.get("length"),C=Number(c);Number.isInteger(C)&&C>=I.v&&Ut(I,C+1)}kd(i)}return!0},ownKeys(l){y(i);var c=Reflect.ownKeys(l).filter(f=>{var h=r.get(f);return h===void 0||h.v!==Pn});for(var[u,d]of r)d.v!==Pn&&!(u in l)&&c.push(u);return c},setPrototypeOf(){P2()}})}var g1,qC,WC,VC;function cy(){if(g1===void 0){g1=window,qC=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;WC=$l(t,"firstChild").get,VC=$l(t,"nextSibling").get,u1(e)&&(e[ny]=void 0,e[ry]=null,e[JO]=void 0,e.__e=void 0),u1(r)&&(r[qh]=void 0)}}function Wi(e=""){return document.createTextNode(e)}function Fi(e){return WC.call(e)}function Zo(e){return VC.call(e)}function fl(e,t){if(!er)return Fi(e);var r=Fi(gr);if(r===null)r=gr.appendChild(Wi());else if(t&&r.nodeType!==Mm){var n=Wi();return r?.before(n),Qn(n),n}return t&&h0(r),Qn(r),r}function oi(e,t=!1){if(!er){var r=Fi(e);return r instanceof Comment&&r.data===""?Zo(r):r}if(t){if(gr?.nodeType!==Mm){var n=Wi();return gr?.before(n),Qn(n),n}h0(gr)}return gr}function Eg(e,t=!1){if(!er)return Fi(e);var r=fl(e,t);return ro(e),r}function Ll(e,t=1,r=!1){let n=er?gr:e;for(var i;t--;)i=n,n=Zo(n);if(!er)return n;if(r){if(n?.nodeType!==Mm){var o=Wi();return n===null?i?.after(o):n.before(o),Qn(o),o}h0(n)}return Qn(n),n}function GC(e){e.textContent=""}function YC(){return!Ua||hs!==null?!1:(qt.f&Ha)!==0}function Rf(e,t,r){return t==null||t===cC?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function h0(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===Mm;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}var er=!1;function No(e){er=e}var gr;function Qn(e){if(e===null)throw Tf(),Zl;return gr=e}function Da(){return Qn(Zo(gr))}function ro(e){if(er){if(Zo(gr)!==null)throw Tf(),Zl;gr=e}}function rL(e=1){if(er){for(var t=e,r=gr;t--;)r=Zo(r);gr=r}}function Wp(e=!0){for(var t=0,r=gr;;){if(r.nodeType===Mu){var n=r.data;if(n===t0){if(t===0)return r;t-=1}else(n===lC||n===e0||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=Zo(r);e&&r.remove(),r=i}}function KC(e){if(!e||e.nodeType!==Mu)throw Tf(),Zl;return e.data}var Gc=Symbol("events"),XC=new Set,uy=new Set;function ih(e,t,r){(t[Gc]??(t[Gc]={}))[e]=r}function nL(e){for(var t=0;t<e.length;t++)XC.add(e[t]);for(var r of uy)r(e)}var Cg=null,xg=!1;function v1(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;Cg=e,!xg&&(xg=!0,setTimeout(()=>{xg=!1,Cg=null}));var s=0,a=Cg===e&&e[Gc];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[Gc]=t;return}var c=i.indexOf(t);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||e.target,o!==t){Bd(e,"currentTarget",{configurable:!0,get(){return o||r}});var u=lr,d=qt;Ci(null),vo(null);try{for(var f,h=[];o!==null&&o!==t;){try{var g=o[Gc]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(m){f?h.push(m):f=m}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let m of h)queueMicrotask(()=>{throw m});throw f}}finally{e[Gc]=t,delete e.currentTarget,Ci(u),vo(d)}}}var iL=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function oL(e){return iL?.createHTML(e)??e}function sL(e){var t=Rf("template");return t.innerHTML=oL(e.replaceAll("<!>","<!---->")),t.content}function Xs(e,t){var r=qt;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function xi(e,t){var r=(t&l2)!==0,n=(t&c2)!==0,i,o=!e.startsWith("<!>");return()=>{if(er)return Xs(gr,null),gr;i===void 0&&(i=sL(o?e:"<!>"+e),!r&&(i=Fi(i)));var s=n||qC?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=Fi(s),l=s.lastChild;Xs(a,l)}else Xs(s,s);return s}}function Mi(){if(er)return Xs(gr,null),gr;var e=document.createDocumentFragment(),t=document.createComment(""),r=Wi();return e.append(t,r),Xs(t,r),e}function Zt(e,t){if(er){var r=qt;((r.f&Ha)===0||r.nodes.end===null)&&(r.nodes.end=gr),Da();return}e!==null&&e.before(t)}var aL=["touchstart","touchmove"];function lL(e){return aL.includes(e)}function cL(e){let t=0,r=ec(0),n;return()=>{c0()&&(y(r),Dm(()=>(t===0&&(n=Wr(()=>e(()=>kd(r)))),t+=1,()=>{Na(()=>{t-=1,t===0&&(n?.(),n=void 0,kd(r))})})))}}var uL=su|fc;function dL(e,t,r,n){new fL(e,t,r,n)}var Wo=new WeakMap,dy=new WeakMap,vs=new WeakMap,qd=new WeakMap,Hi=new WeakMap,Vo=new WeakMap,Vi=new WeakMap,Do=new WeakMap,Aa=new WeakMap,Dc=new WeakMap,Nl=new WeakMap,oh=new WeakMap,fy=new WeakMap,hy=new WeakMap,Xa=new WeakMap,y1=new WeakMap,$n=new WeakSet,fL=class{constructor(e,t,r,n){Eu(this,$n),T(this,"parent",void 0),T(this,"is_pending",!1),T(this,"transform_error",void 0),Me(this,Wo,void 0),Me(this,dy,er?gr:null),Me(this,vs,void 0),Me(this,qd,void 0),Me(this,Hi,void 0),Me(this,Vo,null),Me(this,Vi,null),Me(this,Do,null),Me(this,Aa,null),Me(this,Dc,0),Me(this,Nl,0),Me(this,oh,!1),Me(this,fy,new Set),Me(this,hy,new Set),Me(this,Xa,null),Me(this,y1,cL(()=>(xe(Xa,this,ec(w(Dc,this))),()=>{xe(Xa,this,null)}))),xe(Wo,this,e),xe(vs,this,t),xe(qd,this,i=>{var o=qt;o.b=this,o.f|=Qb,r(i)}),this.parent=qt.b,this.transform_error=n??this.parent?.transform_error??(i=>i),xe(Hi,this,jm(()=>{if(er){let i=w(dy,this);Da();let o=i.data===e0;if(i.data.startsWith(c1)){let s=JSON.parse(i.data.slice(c1.length));ze($n,this,pL).call(this,s)}else o?ze($n,this,mL).call(this):ze($n,this,hL).call(this)}else ze($n,this,QC).call(this)},uL)),er&&xe(Wo,this,gr)}defer_effect(e){kC(e,w(fy,this),w(hy,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!w(vs,this).pending}update_pending_count(e,t){ze($n,this,ZC).call(this,e,t),xe(Dc,this,w(Dc,this)+e),!(!w(Xa,this)||w(oh,this))&&(xe(oh,this,!0),Na(()=>{xe(oh,this,!1),w(Xa,this)&&cu(w(Xa,this),w(Dc,this))}))}get_effect_pending(){return w(y1,this).call(this),y(w(Xa,this))}error(e){if(!w(vs,this).onerror&&!w(vs,this).failed)throw e;Xt?.is_fork?(w(Vo,this)&&Xt.skip_effect(w(Vo,this)),w(Vi,this)&&Xt.skip_effect(w(Vi,this)),w(Do,this)&&Xt.skip_effect(w(Do,this)),Xt.oncommit(()=>{ze($n,this,b1).call(this,e)})):ze($n,this,b1).call(this,e)}};function hL(){try{xe(Vo,this,go(()=>w(qd,this).call(this,w(Wo,this))))}catch(e){this.error(e)}}function pL(e){let t=w(vs,this).failed,{reset:r,invoke_onerror:n}=ze($n,this,JC).call(this,e);Na(n),t&&xe(Do,this,go(()=>{t(w(Wo,this),()=>e,()=>r)}))}function JC(e){var t=!1,r=!1;let n=()=>{if(t){h2();return}t=!0,r&&A2(),w(Do,this)!==null&&pc(w(Do,this),()=>{xe(Do,this,null)}),ze($n,this,p0).call(this,()=>{ze($n,this,QC).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,w(vs,this).onerror?.(e,n),r=!1}catch(i){Ts(i,w(Hi,this)&&w(Hi,this).parent)}}}}function mL(){let e=w(vs,this).pending;e&&(this.is_pending=!0,xe(Vi,this,go(()=>e(w(Wo,this)))),Na(()=>{var t=xe(Aa,this,document.createDocumentFragment()),r=Wi(),n=!1;if(t.append(r),xe(Vo,this,ze($n,this,p0).call(this,()=>{try{return go(()=>w(qd,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){Ts(o,w(Hi,this).parent)}return null}})),w(Vo,this)===null){xe(Aa,this,null),n&&ze($n,this,Vp).call(this,Xt);return}w(Nl,this)===0&&(w(Wo,this).before(t),xe(Aa,this,null),pc(w(Vi,this),()=>{xe(Vi,this,null)}),ze($n,this,Vp).call(this,Xt))}))}function QC(){try{if(this.is_pending=this.has_pending_snippet(),xe(Nl,this,0),xe(Dc,this,0),xe(Vo,this,go(()=>{w(qd,this).call(this,w(Wo,this))})),w(Nl,this)>0){var e=xe(Aa,this,document.createDocumentFragment());f0(w(Vo,this),e);let t=w(vs,this).pending;xe(Vi,this,go(()=>t(w(Wo,this))))}else ze($n,this,Vp).call(this,Xt)}catch(t){this.error(t)}}function Vp(e){this.is_pending=!1,e.transfer_effects(w(fy,this),w(hy,this))}function p0(e){var t=qt,r=lr,n=Sn;vo(w(Hi,this)),Ci(w(Hi,this)),lu(w(Hi,this).ctx);try{return hc.ensure(),e()}finally{vo(t),Ci(r),lu(n)}}function ZC(e,t){if(!this.has_pending_snippet()){var r;this.parent&&ze($n,r=this.parent,ZC).call(r,e,t);return}xe(Nl,this,w(Nl,this)+e),w(Nl,this)===0&&(ze($n,this,Vp).call(this,t),w(Vi,this)&&pc(w(Vi,this),()=>{xe(Vi,this,null)}),w(Aa,this)&&(w(Wo,this).before(w(Aa,this)),xe(Aa,this,null)))}function b1(e){w(Vo,this)&&(hi(w(Vo,this)),xe(Vo,this,null)),w(Vi,this)&&(hi(w(Vi,this)),xe(Vi,this,null)),w(Do,this)&&(hi(w(Do,this)),xe(Do,this,null)),er&&(Qn(w(dy,this)),rL(),Qn(Wp()));let t=w(vs,this).failed,r=n=>{let{reset:i,invoke_onerror:o}=ze($n,this,JC).call(this,n);o(),t&&xe(Do,this,ze($n,this,p0).call(this,()=>{try{return go(()=>{var s=qt;s.b=this,s.f|=Qb,t(w(Wo,this),()=>n,()=>i)})}catch(s){return Ts(s,w(Hi,this).parent),null}}))};Na(()=>{var n;try{n=this.transform_error(e)}catch(i){Ts(i,w(Hi,this)&&w(Hi,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>Ts(i,w(Hi,this)&&w(Hi,this).parent)):r(n)})}function Rg(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[qh]??(e[qh]=e.nodeValue))&&(e[qh]=r,e.nodeValue=`${r}`)}function ex(e,t){return tx(e,t)}function gL(e,t){cy(),t.intro=t.intro??!1;let r=t.target,n=er,i=gr;try{for(var o=Fi(r);o&&(o.nodeType!==Mu||o.data!==lC);)o=Zo(o);if(!o)throw Zl;No(!0),Qn(o);let s=tx(e,{...t,anchor:o});return No(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
4
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==Zl&&console.warn("Failed to hydrate: ",s),t.recover===!1&&C2(),cy(),GC(r),No(!1),ex(e,t)}finally{No(n),Qn(i)}}var sh=new Map;function tx(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){cy();var l=void 0,c=K2(()=>{var u=r??t.appendChild(Wi());dL(u,{pending:()=>{}},h=>{Ef({});var g=Sn;if(o&&(g.c=o),i&&(n.$$events=i),er&&Xs(h,null),l=e(h,n)||n0(),er&&(qt.nodes.end=gr,gr===null||gr.nodeType!==Mu||gr.data!==t0))throw Tf(),Zl;Cf()},a);var d=new Set,f=h=>{for(var g=0;g<h.length;g++){var m=h[g];if(!d.has(m)){d.add(m);var v=lL(m);for(let C of[t,document]){var b=sh.get(C);b===void 0&&(b=new Map,sh.set(C,b));var I=b.get(m);I===void 0?(C.addEventListener(m,v1,{passive:v}),b.set(m,1)):b.set(m,I+1)}}}};return f(Om(XC)),uy.add(f),()=>{for(var h of d)for(let v of[t,document]){var g=sh.get(v),m=g.get(h);--m==0?(v.removeEventListener(h,v1),g.delete(h),g.size===0&&sh.delete(v)):g.set(h,m)}uy.delete(f),u!==r&&u.parentNode?.removeChild(u)}});return py.set(l,c),l}var py=new WeakMap;function vL(e,t){let r=py.get(e);return r?(py.delete(e),r(t)):Promise.resolve()}var zs=new WeakMap,pa=new WeakMap,Co=new WeakMap,Wu=new WeakMap,Pg=new WeakMap,_g=new WeakMap,w1=new WeakMap,rx=class{constructor(e,t=!0){T(this,"anchor",void 0),Me(this,zs,new Map),Me(this,pa,new Map),Me(this,Co,new Map),Me(this,Wu,new Set),Me(this,Pg,!0),Me(this,_g,r=>{if(w(zs,this).has(r)){var n=w(zs,this).get(r),i=w(pa,this).get(n);if(i)qp(i),w(Wu,this).delete(n);else{var o=w(Co,this).get(n);o&&(qp(o.effect),w(pa,this).set(n,o.effect),w(Co,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(let[s,a]of w(zs,this)){if(w(zs,this).delete(s),s===r)break;let l=w(Co,this).get(a);l&&(hi(l.effect),w(Co,this).delete(a))}for(let[s,a]of w(pa,this)){if(s===n||w(Wu,this).has(s))continue;let l=()=>{if(Array.from(w(zs,this).values()).includes(s)){var c=document.createDocumentFragment();f0(a,c),c.append(Wi()),w(Co,this).set(s,{effect:a,fragment:c})}else hi(a);w(Wu,this).delete(s),w(pa,this).delete(s)};w(Pg,this)||!i?(w(Wu,this).add(s),pc(a,l,!1)):l()}}}),Me(this,w1,r=>{w(zs,this).delete(r);let n=Array.from(w(zs,this).values());for(let[i,o]of w(Co,this))n.includes(i)||(hi(o.effect),w(Co,this).delete(i))}),this.anchor=e,xe(Pg,this,t)}ensure(e,t){var r=Xt,n=YC();if(t&&!w(pa,this).has(e)&&!w(Co,this).has(e))if(n){var i=document.createDocumentFragment(),o=Wi();i.append(o),w(Co,this).set(e,{effect:go(()=>t(o)),fragment:i})}else w(pa,this).set(e,go(()=>t(this.anchor)));if(w(zs,this).set(r,e),n){for(let[s,a]of w(pa,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(let[s,a]of w(Co,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(w(_g,this)),r.ondiscard(w(w1,this))}else er&&(this.anchor=gr),w(_g,this).call(this,r)}};function Oi(e,t,r=!1){var n;er&&(n=gr,Da());var i=new rx(e),o=r?su:0;function s(a,l){if(er){var c=KC(n);if(a!==parseInt(c.substring(1))){var u=Wp();Qn(u),i.anchor=u,No(!1),i.ensure(a,l),No(!0);return}}i.ensure(a,l)}jm(()=>{var a=!1;t((l,c=0)=>{a=!0,s(c,l)}),!a&&s(-1,null)},o)}var yL=Symbol("NaN");function Ag(e,t,r){er&&Da();var n=new rx(e),i=!Ou();jm(()=>{var o=t();o!==o&&(o=yL),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,r)})}function bL(e,t,r){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let d=t[a];pc(d,()=>{if(o){if(o.pending.delete(d),o.done.add(d),o.pending.size===0){var f=e.outrogroups;my(e,Om(o.done)),f.delete(o),f.size===0&&(e.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&r!==null&&e.pending.size===0;if(l){var c=r,u=c.parentNode;GC(u),u.append(c),e.items.clear()}my(e,t,!l)}else o={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(o)}function my(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(let s of e.pending.values())for(let a of s)n.add(e.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];n?.has(o)?(o.f|=ws,f0(o,document.createDocumentFragment())):hi(t[i],r)}}var ah;function lh(e,t,r,n,i,o=null){var s=e,a=new Map;if((t&aC)!==0){var l=e;s=er?Qn(Fi(l)):l.appendChild(Wi())}er&&Da();var c=null,u=o0(()=>{var b=r();return uC(b)?b:b==null?[]:Om(b)}),d,f=new Map,h=!0;function g(b){(v.effect.f&fi)===0&&(v.pending.delete(b),v.fallback=c,wL(v,d,s,t,n),c!==null&&(d.length===0?(c.f&ws)===0?qp(c):(c.f^=ws,pd(c,null,s)):pc(c,()=>{c=null})))}function m(b){v.pending.delete(b)}var v={effect:jm(()=>{d=y(u);var b=d.length;let I=!1;er&&KC(s)===e0!=(b===0)&&(s=Wp(),Qn(s),No(!1),I=!0);for(var C=new Set,x=Xt,$=YC(),P=0;P<b;P+=1){er&&gr.nodeType===Mu&&gr.data===t0&&(s=gr,I=!0,No(!1));var L=d[P],J=n(L,P),V=h?null:a.get(J);V?(V.v&&cu(V.v,L),V.i&&cu(V.i,P),$&&x.unskip_effect(V.e)):(V=SL(a,h?s:ah??(ah=Wi()),L,J,P,i,t,r),!h&&(V.e.f|=ws),a.set(J,V)),C.add(J)}if(b===0&&o&&!c&&(h?c=go(()=>o(s)):(c=go(()=>o(ah??(ah=Wi()))),c.f|=ws)),b>C.size&&S2("","",""),er&&b>0&&Qn(Wp()),!h)if(f.set(x,C),$){for(let[Y,Pe]of a)C.has(Y)||x.skip_effect(Pe.e);x.oncommit(g),x.ondiscard(m)}else g(x);I&&No(!0),y(u)}),flags:t,items:a,pending:f,outrogroups:null,fallback:c};h=!1,er&&(s=gr)}function Vu(e){for(;e!==null&&(e.f&So)===0;)e=e.next;return e}function wL(e,t,r,n,i){var o=(n&t2)!==0,s=t.length,a=e.items,l=Vu(e.effect.first),c,u=null,d,f=[],h=[],g,m,v,b;if(o)for(b=0;b<s;b+=1)g=t[b],m=i(g,b),v=a.get(m).e,(v.f&ws)===0&&(v.nodes?.a?.measure(),(d??(d=new Set)).add(v));for(b=0;b<s;b+=1){if(g=t[b],m=i(g,b),v=a.get(m).e,e.outrogroups!==null)for(let Y of e.outrogroups)Y.pending.delete(v),Y.done.delete(v);if((v.f&di)!==0&&(qp(v),o&&(v.nodes?.a?.unfix(),(d??(d=new Set)).delete(v))),(v.f&ws)!==0)if(v.f^=ws,v===l)pd(v,null,r);else{var I=u?u.next:l;v===e.effect.last&&(e.effect.last=v.prev),v.prev&&(v.prev.next=v.next),v.next&&(v.next.prev=v.prev),ma(e,u,v),ma(e,v,I),pd(v,I,r),u=v,f=[],h=[],l=Vu(u.next);continue}if(v!==l){if(c!==void 0&&c.has(v)){if(f.length<h.length){var C=h[0],x;u=C.prev;var $=f[0],P=f[f.length-1];for(x=0;x<f.length;x+=1)pd(f[x],C,r);for(x=0;x<h.length;x+=1)c.delete(h[x]);ma(e,$.prev,P.next),ma(e,u,$),ma(e,P,C),l=C,u=P,b-=1,f=[],h=[]}else c.delete(v),pd(v,l,r),ma(e,v.prev,v.next),ma(e,v,u===null?e.effect.first:u.next),ma(e,u,v),u=v;continue}for(f=[],h=[];l!==null&&l!==v;)(c??(c=new Set)).add(l),h.push(l),l=Vu(l.next);if(l===null)continue}(v.f&ws)===0&&f.push(v),u=v,l=Vu(v.next)}if(e.outrogroups!==null){for(let Y of e.outrogroups)Y.pending.size===0&&(my(e,Om(Y.done)),e.outrogroups?.delete(Y));e.outrogroups.size===0&&(e.outrogroups=null)}if(l!==null||c!==void 0){var L=[];if(c!==void 0)for(v of c)(v.f&di)===0&&L.push(v);for(;l!==null;)(l.f&di)===0&&l!==e.fallback&&L.push(l),l=Vu(l.next);var J=L.length;if(J>0){var V=(n&aC)!==0&&s===0?r:null;if(o){for(b=0;b<J;b+=1)L[b].nodes?.a?.measure();for(b=0;b<J;b+=1)L[b].nodes?.a?.fix()}bL(e,L,V)}}o&&Na(()=>{if(d!==void 0)for(v of d)v.nodes?.a?.apply()})}function SL(e,t,r,n,i,o,s,a){var l=(s&ZO)!==0?(s&r2)===0?SC(r,!1,!1):ec(r):null,c=(s&e2)!==0?ec(i):null;return{v:l,i:c,e:go(()=>(o(t,l??r,c??i,a),()=>{e.delete(n)}))}}function pd(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,o=t&&(t.f&ws)===0?t.nodes.start:r;n!==null;){var s=Zo(n);if(o.before(n),n===i)return;n=s}}function ma(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}function ch(e,t,r=!1,n=!1,i=!1,o=!1){var s=e,a="";if(r){var l=e;er&&(s=Qn(Fi(l)))}nn(()=>{var c=qt;if(a===(a=t()??"")){er&&Da();return}if(r&&!er){c.nodes=null,l.innerHTML=a,a!==""&&Xs(Fi(l),l.lastChild);return}if(c.nodes!==null&&(MC(c.nodes.start,c.nodes.end),c.nodes=null),a!==""){if(er){gr.data;for(var u=Da(),d=u;u!==null&&(u.nodeType!==Mu||u.data!=="");)d=u,u=Zo(u);if(u===null)throw Tf(),Zl;Xs(gr,d),s=Qn(u);return}var f=Rf(n?"svg":i?"math":"template",n?u2:i?d2:void 0);f.innerHTML=a;var h=n||i?f:f.content;if(Xs(Fi(h),h.lastChild),n||i)for(;Fi(h);)s.before(Fi(h));else s.before(h)}})}function nx(e,t,r,n,i){if(er&&Da(),t.$$host?.$$shadowRoot){let a=Rf("slot");if(r!=="default"&&(a.name=r),Zt(e,a),i!==null){let l=Wi();a.append(l),i(l)}return}var o=t.$$slots?.[r],s=!1;o===!0&&(o=t[r==="default"?"children":r],s=!0),o===void 0?i!==null&&i(e):o(e,s?()=>n:n)}function m0(e,t){u0(()=>{e=qt?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){let i=Rf("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function ga(e,t,r){u0(()=>{var n=Wr(()=>t(e,r?.())||{});if(r&&n?.update){var i=!1,o={};Dm(()=>{var s=r();tL(s),i&&mC(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var S1=[...`
5
+ \r\f \v\uFEFF`];function IL(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||S1.includes(n[s-1]))&&(a===n.length||S1.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function Ja(e,t,r,n,i,o){var s=e[ny];if(er||s!==r||s===void 0){var a=IL(r,n,o);(!er||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[ny]=r}else if(o&&i!==o)for(var l in o){var c=!!o[l];(i==null||c!==!!i[l])&&e.classList.toggle(l,c)}return o}var kL=Symbol("is custom element"),TL=Symbol("is html"),EL=QO?"link":"LINK";function pi(e,t,r,n){var i=CL(e);er&&(i[t]=e.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&e.nodeName===EL)||i[t]!==(i[t]=r)&&(t==="loading"&&(e[XO]=r),r==null?e.removeAttribute(t):typeof r!="string"&&ix(e).has(t)?e[t]=r:e.setAttribute(t,r))}function jn(e,t,r){var n=lr,i=qt;let o=er;er&&No(!1),Ci(null),vo(null);try{t!=="style"&&(gy.has(e.getAttribute("is")||e.nodeName)||!customElements||customElements.get(e.getAttribute("is")||e.nodeName.toLowerCase())?ix(e).has(t):r&&typeof r=="object")?e[t]=r:pi(e,t,r==null?r:String(r))}finally{Ci(n),vo(i),o&&No(!0)}}function CL(e){return e[ry]??(e[ry]={[kL]:e.nodeName.includes("-"),[TL]:e.namespaceURI===cC})}var gy=new Map;function ix(e){var t=e.getAttribute("is")||e.nodeName,r=gy.get(t);if(r)return r;gy.set(t,r=new Set);for(var n,i=e,o=Element.prototype;o!==i;){n=dC(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&r.add(s);i=r0(i)}return r}var jc=new WeakMap,Gp=new WeakMap,$g=new WeakMap,I1=new WeakSet,ox=class{constructor(e){Eu(this,I1),Me(this,jc,new WeakMap),Me(this,Gp,void 0),Me(this,$g,void 0),xe($g,this,e)}observe(e,t){var r=w(jc,this).get(e)||new Set;return r.add(t),w(jc,this).set(e,r),ze(I1,this,xL).call(this).observe(e,w($g,this)),()=>{var n=w(jc,this).get(e);n.delete(t),n.size===0&&(w(jc,this).delete(e),w(Gp,this).unobserve(e))}}};iC=ox;function xL(){return w(Gp,this)??xe(Gp,this,new ResizeObserver(e=>{for(var t of e){iC.entries.set(t.target,t);for(var r of w(jc,this).get(t.target)||[])r(t)}}))}T(ox,"entries",new WeakMap);function Mg(e,t){return e===t||e?.[Al]===t}function g0(e=n0(),t,r,n){var i=Sn.r,o=qt;return u0(()=>{var s,a;return Dm(()=>{s=a,a=n?.()||[],Wr(()=>{Mg(r(...a),e)||(t(e,...a),s&&Mg(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&Ap;)l=l.parent;let c=()=>{a&&Mg(r(...a),e)&&t(null,...a)},u=l.teardown;l.teardown=()=>{c(),u?.()}}}),e}var uh=!1;function RL(e){var t=uh;try{return uh=!1,[e(),uh]}finally{uh=t}}function dt(e,t,r,n){var i=!Lm||(r&i2)!==0,o=(r&s2)!==0,s=(r&a2)!==0,a=n,l=!0,c=void 0,u=()=>s&&i?(c??(c=Fd(n)),y(c)):(l&&(l=!1,a=s?Wr(n):n),a);let d;if(o){var f=Al in e||sC in e;d=$l(e,t)?.set??(f&&t in e?x=>e[t]=x:void 0)}var h,g=!1;o?[h,g]=RL(()=>e[t]):h=e[t],h===void 0&&n!==void 0&&(h=u(),d&&(i&&x2(t),d(h)));var m;if(i?m=()=>{var x=e[t];return x===void 0?u():(l=!0,x)}:m=()=>{var x=e[t];return x!==void 0&&(a=void 0),x===void 0?a:x},i&&(r&o2)===0)return m;if(d){var v=e.$$legacy;return function(x,$){return arguments.length>0?((!i||!$||v||g)&&d($?m():x),x):m()}}var b=!1,I=((r&n2)!==0?Fd:o0)(()=>(b=!1,m()));o&&y(I);var C=qt;return function(x,$){if(arguments.length>0){let P=$?y(I):i&&o?Ea(x):x;return Ut(I,P),b=!0,a!==void 0&&(a=P),x}return ea&&b||(C.f&fi)!==0?I.v:y(I)}}function PL(e){return new _L(e)}var Qa=new WeakMap,ss=new WeakMap,_L=class{constructor(e){Me(this,Qa,void 0),Me(this,ss,void 0);var t=new Map,r=(i,o)=>{var s=SC(o,!1,!1);return t.set(i,s),s};let n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return y(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===sC?!0:(y(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return Ut(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});xe(ss,this,(e.hydrate?gL:ex)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!Ua&&(!e?.props?.$$host||e.sync===!1)&&ct(),xe(Qa,this,n.$$events);for(let i of Object.keys(w(ss,this)))i==="$set"||i==="$destroy"||i==="$on"||Bd(this,i,{get(){return w(ss,this)[i]},set(o){w(ss,this)[i]=o},enumerable:!0});w(ss,this).$set=i=>{Object.assign(n,i)},w(ss,this).$destroy=()=>{vL(w(ss,this))}}$set(e){w(ss,this).$set(e)}$on(e,t){w(Qa,this)[e]=w(Qa,this)[e]||[];let r=(...n)=>t.call(this,...n);return w(Qa,this)[e].push(r),()=>{w(Qa,this)[e]=w(Qa,this)[e].filter(n=>n!==r)}}$destroy(){w(ss,this).$destroy()}},sx;typeof HTMLElement=="function"&&(sx=class extends HTMLElement{constructor(e,t,r){super(),T(this,"$$ctor",void 0),T(this,"$$s",void 0),T(this,"$$c",void 0),T(this,"$$cn",!1),T(this,"$$d",{}),T(this,"$$r",!1),T(this,"$$p_d",{}),T(this,"$$l",{}),T(this,"$$l_u",new Map),T(this,"$$me",void 0),T(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){let n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{let o=Rf("slot");n!=="default"&&(o.name=n),Zt(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let t={},r=AL(this);for(let n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(let n of this.attributes){let i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=Gh(i,n.value,this.$$p_d,"toProp"))}for(let n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=PL({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=Y2(()=>{Dm(()=>{this.$$r=!0;for(let n of Lp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];let i=Gh(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(let n in this.$$l)for(let i of this.$$l[n]){let o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=Gh(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return Lp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function Gh(e,t,r,n){let i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function AL(e){let t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function zm(e,t,r,n,i,o){let s=class extends sx{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return Lp(t).map(a=>(t[a].attribute||a).toLowerCase())}};return Lp(t).forEach(a=>{Bd(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=Gh(a,l,t),this.$$d[a]=l;var c=this.$$c;c&&($l(c,a)?.get?c[a]=l:c.$set({[a]:l}))}})}),n.forEach(a=>{Bd(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}var v0=Cu(Symbol.for("pie.assessmentToolkit.runtimeContext")),Yh=Cu(Symbol.for("pie.assessmentToolkit.hostRuntimeContext")),ax=Cu(Symbol.for("pie.assessmentToolkit.shellContext")),$L=Cu(Symbol.for("pie.assessmentToolkit.regionScopeContext")),ML={bubbles:!0,composed:!0,cancelable:!1};function OL(e,t,r={}){return new CustomEvent(e,{detail:t,...ML,...r})}function Wd(e,t,r,n={}){return e.dispatchEvent(OL(t,r,n))}function LL(e,t){return af(e,v0,t)}function NL(e,t){return af(e,ax,t)}function y0(e,t){return af(e,Yh,t)}var du=1e4;function Vd(e,t,r){if(!e)return;let n=Symbol.for(`pie.assessmentToolkit.warned.${t}`),i=e;i[n]||(i[n]=!0,console.warn(r))}function fu(e,t){return lx(e,t,new WeakMap)}function lx(e,t,r){if(Object.is(e,t))return!0;let n=Array.isArray(e);if(n!==Array.isArray(t)||!n&&(!k1(e)||!k1(t)))return!1;let i=e,o=t;if(n&&e.length!==t.length)return!1;let s=r.get(i);if(s?.has(o))return!0;s||(s=new Set,r.set(i,s)),s.add(o);let a=new Set([...Object.keys(i),...Object.keys(o)]);for(let l of a)if(!lx(i[l],o[l],r))return!1;return!0}function k1(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function DL(e,t="iife"){return e==="iife"||e==="esm"||e==="preloaded"?e:t}function T1(e){const t={};return e.forEach(r=>{const n=r.config?.elements||{};Object.entries(n).forEach(([i,o])=>{const s=String(o),a=ET(i,s,{preserveUnversionedTag:!0});if(!t[a])t[a]=s;else if(t[a]!==s)throw new Error(`Element version conflict: ${a} requires both ${t[a]} and ${s}. Each full versioned tag must map to exactly one package spec.`)})}),t}var Pf=xt(((e,t)=>{var r="2.0.0",n=256,i=Number.MAX_SAFE_INTEGER||9007199254740991,o=16,s=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:n,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:i,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),Bm=xt(((e,t)=>{var r=typeof process=="object"&&{}.NODE_DEBUG&&/\bsemver\b/i.test({}.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};t.exports=r})),_f=xt(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=Pf(),o=Bm();e=t.exports={};var s=e.re=[],a=e.safeRe=[],l=e.src=[],c=e.safeSrc=[],u=e.t={},d=0,f="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",i],[f,n]],g=v=>{for(const[b,I]of h)v=v.split(`${b}*`).join(`${b}{0,${I}}`).split(`${b}+`).join(`${b}{1,${I}}`);return v},m=(v,b,I)=>{const C=g(b),x=d++;o(v,x,b),u[v]=x,l[x]=b,c[x]=C,s[x]=new RegExp(b,I?"g":void 0),a[x]=new RegExp(C,I?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${f}*`),m("MAINVERSION",`(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${l[u.PRERELEASEIDENTIFIER]}(?:\\.${l[u.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${l[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[u.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${f}+`),m("BUILD",`(?:\\+(${l[u.BUILDIDENTIFIER]}(?:\\.${l[u.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${l[u.MAINVERSION]}${l[u.PRERELEASE]}?${l[u.BUILD]}?`),m("FULL",`^${l[u.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${l[u.MAINVERSIONLOOSE]}${l[u.PRERELEASELOOSE]}?${l[u.BUILD]}?`),m("LOOSE",`^${l[u.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${l[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${l[u.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:${l[u.PRERELEASE]})?${l[u.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:${l[u.PRERELEASELOOSE]})?${l[u.BUILD]}?)?)?`),m("XRANGE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${l[u.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",l[u.COERCEPLAIN]+`(?:${l[u.PRERELEASE]})?(?:${l[u.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",l[u.COERCE],!0),m("COERCERTLFULL",l[u.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${l[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${l[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${l[u.LONECARET]}${l[u.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${l[u.LONECARET]}${l[u.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${l[u.GTLT]}\\s*(${l[u.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]}|${l[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${l[u.XRANGEPLAIN]})\\s+-\\s+(${l[u.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${l[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[u.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})),b0=xt(((e,t)=>{var r=Object.freeze({loose:!0}),n=Object.freeze({}),i=o=>o?typeof o!="object"?r:o:n;t.exports=i})),cx=xt(((e,t)=>{var r=/^[0-9]+$/,n=(o,s)=>{if(typeof o=="number"&&typeof s=="number")return o===s?0:o<s?-1:1;const a=r.test(o),l=r.test(s);return a&&l&&(o=+o,s=+s),o===s?0:a&&!l?-1:l&&!a?1:o<s?-1:1},i=(o,s)=>n(s,o);t.exports={compareIdentifiers:n,rcompareIdentifiers:i}})),ti=xt(((e,t)=>{var r=Bm(),{MAX_LENGTH:n,MAX_SAFE_INTEGER:i}=Pf(),{safeRe:o,t:s}=_f(),a=b0(),{compareIdentifiers:l}=cx(),c=(d,f)=>{const h=f.split(".");if(h.length>d.length)return!1;for(let g=0;g<h.length;g++)if(l(d[g],h[g])!==0)return!1;return!0},u=class ds{constructor(f,h){if(h=a(h),f instanceof ds){if(f.loose===!!h.loose&&f.includePrerelease===!!h.includePrerelease)return f;f=f.version}else if(typeof f!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof f}".`);if(f.length>n)throw new TypeError(`version is longer than ${n} characters`);r("SemVer",f,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;const g=f.trim().match(h.loose?o[s.LOOSE]:o[s.FULL]);if(!g)throw new TypeError(`Invalid Version: ${f}`);if(this.raw=f,this.major=+g[1],this.minor=+g[2],this.patch=+g[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");g[4]?this.prerelease=g[4].split(".").map(m=>{if(/^[0-9]+$/.test(m)){const v=+m;if(v>=0&&v<i)return v}return m}):this.prerelease=[],this.build=g[5]?g[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(f){if(r("SemVer.compare",this.version,this.options,f),!(f instanceof ds)){if(typeof f=="string"&&f===this.version)return 0;f=new ds(f,this.options)}return f.version===this.version?0:this.compareMain(f)||this.comparePre(f)}compareMain(f){return f instanceof ds||(f=new ds(f,this.options)),this.major<f.major?-1:this.major>f.major?1:this.minor<f.minor?-1:this.minor>f.minor?1:this.patch<f.patch?-1:this.patch>f.patch?1:0}comparePre(f){if(f instanceof ds||(f=new ds(f,this.options)),this.prerelease.length&&!f.prerelease.length)return-1;if(!this.prerelease.length&&f.prerelease.length)return 1;if(!this.prerelease.length&&!f.prerelease.length)return 0;let h=0;do{const g=this.prerelease[h],m=f.prerelease[h];if(r("prerelease compare",h,g,m),g===void 0&&m===void 0)return 0;if(m===void 0)return 1;if(g===void 0)return-1;if(g===m)continue;return l(g,m)}while(++h)}compareBuild(f){f instanceof ds||(f=new ds(f,this.options));let h=0;do{const g=this.build[h],m=f.build[h];if(r("build compare",h,g,m),g===void 0&&m===void 0)return 0;if(m===void 0)return 1;if(g===void 0)return-1;if(g===m)continue;return l(g,m)}while(++h)}inc(f,h,g){if(f.startsWith("pre")){if(!h&&g===!1)throw new Error("invalid increment argument: identifier is empty");if(h){const m=`-${h}`.match(this.options.loose?o[s.PRERELEASELOOSE]:o[s.PRERELEASE]);if(!m||m[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(f){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,g);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,g);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,g),this.inc("pre",h,g);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,g),this.inc("pre",h,g);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const m=Number(g)?1:0;if(this.prerelease.length===0)this.prerelease=[m];else{let v=this.prerelease.length;for(;--v>=0;)typeof this.prerelease[v]=="number"&&(this.prerelease[v]++,v=-2);if(v===-1){if(h===this.prerelease.join(".")&&g===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(m)}}if(h){let v=[h,m];if(g===!1&&(v=[h]),c(this.prerelease,h)){const b=this.prerelease[h.split(".").length];isNaN(b)&&(this.prerelease=v)}else this.prerelease=v}break}default:throw new Error(`invalid increment argument: ${f}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=u})),mc=xt(((e,t)=>{var r=ti(),n=(i,o,s=!1)=>{if(i instanceof r)return i;try{return new r(i,o)}catch(a){if(!s)return null;throw a}};t.exports=n})),jL=xt(((e,t)=>{var r=mc(),n=(i,o)=>{const s=r(i,o);return s?s.version:null};t.exports=n})),zL=xt(((e,t)=>{var r=mc(),n=(i,o)=>{const s=r(i.trim().replace(/^[=v]+/,""),o);return s?s.version:null};t.exports=n})),BL=xt(((e,t)=>{var r=ti(),n=(i,o,s,a,l)=>{typeof s=="string"&&(l=a,a=s,s=void 0);try{return new r(i instanceof r?i.version:i,s).inc(o,a,l).version}catch{return null}};t.exports=n})),FL=xt(((e,t)=>{var r=mc(),n=(i,o)=>{const s=r(i,null,!0),a=r(o,null,!0),l=s.compare(a);if(l===0)return null;const c=l>0,u=c?s:a,d=c?a:s,f=!!u.prerelease.length;if(d.prerelease.length&&!f){if(!d.patch&&!d.minor)return"major";if(d.compareMain(u)===0)return d.minor&&!d.patch?"minor":"patch"}const h=f?"pre":"";return s.major!==a.major?h+"major":s.minor!==a.minor?h+"minor":s.patch!==a.patch?h+"patch":"prerelease"};t.exports=n})),HL=xt(((e,t)=>{var r=ti(),n=(i,o)=>new r(i,o).major;t.exports=n})),UL=xt(((e,t)=>{var r=ti(),n=(i,o)=>new r(i,o).minor;t.exports=n})),qL=xt(((e,t)=>{var r=ti(),n=(i,o)=>new r(i,o).patch;t.exports=n})),WL=xt(((e,t)=>{var r=mc(),n=(i,o)=>{const s=r(i,o);return s&&s.prerelease.length?s.prerelease:null};t.exports=n})),es=xt(((e,t)=>{var r=ti(),n=(i,o,s)=>new r(i,s).compare(new r(o,s));t.exports=n})),VL=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(o,i,s);t.exports=n})),GL=xt(((e,t)=>{var r=es(),n=(i,o)=>r(i,o,!0);t.exports=n})),w0=xt(((e,t)=>{var r=ti(),n=(i,o,s)=>{const a=new r(i,s),l=new r(o,s);return a.compare(l)||a.compareBuild(l)};t.exports=n})),YL=xt(((e,t)=>{var r=w0(),n=(i,o)=>i.sort((s,a)=>r(s,a,o));t.exports=n})),KL=xt(((e,t)=>{var r=w0(),n=(i,o)=>i.sort((s,a)=>r(a,s,o));t.exports=n})),Fm=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)>0;t.exports=n})),S0=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)<0;t.exports=n})),ux=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)===0;t.exports=n})),dx=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)!==0;t.exports=n})),I0=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)>=0;t.exports=n})),k0=xt(((e,t)=>{var r=es(),n=(i,o,s)=>r(i,o,s)<=0;t.exports=n})),fx=xt(((e,t)=>{var r=ux(),n=dx(),i=Fm(),o=I0(),s=S0(),a=k0(),l=(c,u,d,f)=>{switch(u){case"===":return typeof c=="object"&&(c=c.version),typeof d=="object"&&(d=d.version),c===d;case"!==":return typeof c=="object"&&(c=c.version),typeof d=="object"&&(d=d.version),c!==d;case"":case"=":case"==":return r(c,d,f);case"!=":return n(c,d,f);case">":return i(c,d,f);case">=":return o(c,d,f);case"<":return s(c,d,f);case"<=":return a(c,d,f);default:throw new TypeError(`Invalid operator: ${u}`)}};t.exports=l})),XL=xt(((e,t)=>{var r=ti(),n=mc(),{safeRe:i,t:o}=_f(),s=(a,l)=>{if(a instanceof r)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;l=l||{};let c=null;if(!l.rtl)c=a.match(l.includePrerelease?i[o.COERCEFULL]:i[o.COERCE]);else{const m=l.includePrerelease?i[o.COERCERTLFULL]:i[o.COERCERTL];let v;for(;(v=m.exec(a))&&(!c||c.index+c[0].length!==a.length);)(!c||v.index+v[0].length!==c.index+c[0].length)&&(c=v),m.lastIndex=v.index+v[1].length+v[2].length;m.lastIndex=-1}if(c===null)return null;const u=c[2],d=c[3]||"0",f=c[4]||"0",h=l.includePrerelease&&c[5]?`-${c[5]}`:"",g=l.includePrerelease&&c[6]?`+${c[6]}`:"";return n(`${u}.${d}.${f}${h}${g}`,l)};t.exports=s})),JL=xt(((e,t)=>{var r=mc(),n=Pf(),i=ti(),o=(c,u,d)=>{if(!n.RELEASE_TYPES.includes(u))return null;const f=s(c,d);return f&&a(f,u)},s=(c,u)=>{const d=c instanceof i?c.version:c;return r(d,u)},a=(c,u)=>{if(l(u))return c.version;switch(c.prerelease=[],u){case"major":c.minor=0,c.patch=0;break;case"minor":c.patch=0}return c.format()},l=c=>c.startsWith("pre");t.exports=o})),QL=xt(((e,t)=>{var r=class{constructor(){this.max=1e3,this.map=new Map}get(n){const i=this.map.get(n);if(i!==void 0)return this.map.delete(n),this.map.set(n,i),i}delete(n){return this.map.delete(n)}set(n,i){if(!this.delete(n)&&i!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(n,i)}return this}};t.exports=r})),ts=xt(((e,t)=>{var r=/\s+/g,n=class Kh{constructor(A,K){if(K=o(K),A instanceof Kh)return A.loose===!!K.loose&&A.includePrerelease===!!K.includePrerelease?A:new Kh(A.raw,K);if(A instanceof s)return this.raw=A.value,this.set=[[A]],this.formatted=void 0,this;if(this.options=K,this.loose=!!K.loose,this.includePrerelease=!!K.includePrerelease,this.raw=A.trim().replace(r," "),this.set=this.raw.split("||").map(Q=>this.parseRange(Q.trim())).filter(Q=>Q.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const Q=this.set[0];if(this.set=this.set.filter(_=>!I(_[0])),this.set.length===0)this.set=[Q];else if(this.set.length>1){for(const _ of this.set)if(_.length===1&&C(_[0])){this.set=[_];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let A=0;A<this.set.length;A++){A>0&&(this.formatted+="||");const K=this.set[A];for(let Q=0;Q<K.length;Q++)Q>0&&(this.formatted+=" "),this.formatted+=K[Q].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(A){A=A.replace(b,"");const K=((this.options.includePrerelease&&m)|(this.options.loose&&v))+":"+A,Q=i.get(K);if(Q)return Q;const _=this.options.loose,B=_?c[d.HYPHENRANGELOOSE]:c[d.HYPHENRANGE];A=A.replace(B,ye(this.options.includePrerelease)),a("hyphen replace",A),A=A.replace(c[d.COMPARATORTRIM],f),a("comparator trim",A),A=A.replace(c[d.TILDETRIM],h),a("tilde trim",A),A=A.replace(c[d.CARETTRIM],g),a("caret trim",A);let U=A.split(" ").map(_e=>$(_e,this.options)).join(" ").split(/\s+/).map(_e=>ae(_e,this.options));_&&(U=U.filter(_e=>(a("loose invalid filter",_e,this.options),!!_e.match(c[d.COMPARATORLOOSE])))),a("range list",U);const fe=new Map,W=U.map(_e=>new s(_e,this.options));for(const _e of W){if(I(_e))return[_e];fe.set(_e.value,_e)}fe.size>1&&fe.has("")&&fe.delete("");const se=[...fe.values()];return i.set(K,se),se}intersects(A,K){if(!(A instanceof Kh))throw new TypeError("a Range is required");return this.set.some(Q=>x(Q,K)&&A.set.some(_=>x(_,K)&&Q.every(B=>_.every(U=>B.intersects(U,K)))))}test(A){if(!A)return!1;if(typeof A=="string")try{A=new l(A,this.options)}catch{return!1}for(let K=0;K<this.set.length;K++)if(te(this.set[K],A,this.options))return!0;return!1}};t.exports=n;var i=new(QL()),o=b0(),s=Hm(),a=Bm(),l=ti(),{safeRe:c,src:u,t:d,comparatorTrimReplace:f,tildeTrimReplace:h,caretTrimReplace:g}=_f(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:v}=Pf(),b=new RegExp(u[d.BUILD],"g"),I=z=>z.value==="<0.0.0-0",C=z=>z.value==="",x=(z,A)=>{let K=!0;const Q=z.slice();let _=Q.pop();for(;K&&Q.length;)K=Q.every(B=>_.intersects(B,A)),_=Q.pop();return K},$=(z,A)=>(z=z.replace(c[d.BUILD],""),a("comp",z,A),z=Y(z,A),a("caret",z),z=J(z,A),a("tildes",z),z=M(z,A),a("xrange",z),z=ne(z,A),a("stars",z),z),P=z=>!z||z.toLowerCase()==="x"||z==="*",L=(z,A,K)=>P(z)&&!P(A)||P(A)&&K&&!P(K),J=(z,A)=>z.trim().split(/\s+/).map(K=>V(K,A)).join(" "),V=(z,A)=>{const K=A.loose?c[d.TILDELOOSE]:c[d.TILDE],Q=A.includePrerelease?"-0":"";return z.replace(K,(_,B,U,fe,W)=>{a("tilde",z,_,B,U,fe,W);let se;return P(B)?se="":P(U)?se=`>=${B}.0.0${Q} <${+B+1}.0.0-0`:P(fe)?se=`>=${B}.${U}.0${Q} <${B}.${+U+1}.0-0`:W?(a("replaceTilde pr",W),se=`>=${B}.${U}.${fe}-${W} <${B}.${+U+1}.0-0`):se=`>=${B}.${U}.${fe} <${B}.${+U+1}.0-0`,a("tilde return",se),se})},Y=(z,A)=>z.trim().split(/\s+/).map(K=>Pe(K,A)).join(" "),Pe=(z,A)=>{a("caret",z,A);const K=A.loose?c[d.CARETLOOSE]:c[d.CARET],Q=A.includePrerelease?"-0":"";return z.replace(K,(_,B,U,fe,W)=>{a("caret",z,_,B,U,fe,W);let se;return P(B)?se="":P(U)?se=`>=${B}.0.0${Q} <${+B+1}.0.0-0`:P(fe)?B==="0"?se=`>=${B}.${U}.0${Q} <${B}.${+U+1}.0-0`:se=`>=${B}.${U}.0${Q} <${+B+1}.0.0-0`:W?(a("replaceCaret pr",W),B==="0"?U==="0"?se=`>=${B}.${U}.${fe}-${W} <${B}.${U}.${+fe+1}-0`:se=`>=${B}.${U}.${fe}-${W} <${B}.${+U+1}.0-0`:se=`>=${B}.${U}.${fe}-${W} <${+B+1}.0.0-0`):(a("no pr"),B==="0"?U==="0"?se=`>=${B}.${U}.${fe} <${B}.${U}.${+fe+1}-0`:se=`>=${B}.${U}.${fe} <${B}.${+U+1}.0-0`:se=`>=${B}.${U}.${fe} <${+B+1}.0.0-0`),a("caret return",se),se})},M=(z,A)=>(a("replaceXRanges",z,A),z.split(/\s+/).map(K=>H(K,A)).join(" ")),H=(z,A)=>{z=z.trim();const K=A.loose?c[d.XRANGELOOSE]:c[d.XRANGE];return z.replace(K,(Q,_,B,U,fe,W)=>{if(a("xRange",z,Q,_,B,U,fe,W),L(B,U,fe))return z;const se=P(B),_e=se||P(U),Ue=_e||P(fe),it=Ue;return _==="="&&it&&(_=""),W=A.includePrerelease?"-0":"",se?_===">"||_==="<"?Q="<0.0.0-0":Q="*":_&&it?(_e&&(U=0),fe=0,_===">"?(_=">=",_e?(B=+B+1,U=0,fe=0):(U=+U+1,fe=0)):_==="<="&&(_="<",_e?B=+B+1:U=+U+1),_==="<"&&(W="-0"),Q=`${_+B}.${U}.${fe}${W}`):_e?Q=`>=${B}.0.0${W} <${+B+1}.0.0-0`:Ue&&(Q=`>=${B}.${U}.0${W} <${B}.${+U+1}.0-0`),a("xRange return",Q),Q})},ne=(z,A)=>(a("replaceStars",z,A),z.trim().replace(c[d.STAR],"")),ae=(z,A)=>(a("replaceGTE0",z,A),z.trim().replace(c[A.includePrerelease?d.GTE0PRE:d.GTE0],"")),ye=z=>(A,K,Q,_,B,U,fe,W,se,_e,Ue,it)=>(P(Q)?K="":P(_)?K=`>=${Q}.0.0${z?"-0":""}`:P(B)?K=`>=${Q}.${_}.0${z?"-0":""}`:U?K=`>=${K}`:K=`>=${K}${z?"-0":""}`,P(se)?W="":P(_e)?W=`<${+se+1}.0.0-0`:P(Ue)?W=`<${se}.${+_e+1}.0-0`:it?W=`<=${se}.${_e}.${Ue}-${it}`:z?W=`<${se}.${_e}.${+Ue+1}-0`:W=`<=${W}`,`${K} ${W}`.trim()),te=(z,A,K)=>{for(let Q=0;Q<z.length;Q++)if(!z[Q].test(A))return!1;if(A.prerelease.length&&!K.includePrerelease){for(let Q=0;Q<z.length;Q++)if(a(z[Q].semver),z[Q].semver!==s.ANY&&z[Q].semver.prerelease.length>0){const _=z[Q].semver;if(_.major===A.major&&_.minor===A.minor&&_.patch===A.patch)return!0}return!1}return!0}})),Hm=xt(((e,t)=>{var r=Symbol("SemVer ANY"),n=class vy{static get ANY(){return r}constructor(f,h){if(h=i(h),f instanceof vy){if(f.loose===!!h.loose)return f;f=f.value}f=f.trim().split(/\s+/).join(" "),l("comparator",f,h),this.options=h,this.loose=!!h.loose,this.parse(f),this.semver===r?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(f){const h=this.options.loose?o[s.COMPARATORLOOSE]:o[s.COMPARATOR],g=f.match(h);if(!g)throw new TypeError(`Invalid comparator: ${f}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new c(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(f){if(l("Comparator.test",f,this.options.loose),this.semver===r||f===r)return!0;if(typeof f=="string")try{f=new c(f,this.options)}catch{return!1}return a(f,this.operator,this.semver,this.options)}intersects(f,h){if(!(f instanceof vy))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(f.value,h).test(this.value):f.operator===""?f.value===""?!0:new u(this.value,h).test(f.semver):(h=i(h),h.includePrerelease&&(this.value==="<0.0.0-0"||f.value==="<0.0.0-0")||!h.includePrerelease&&(this.value.startsWith("<0.0.0")||f.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&f.operator.startsWith(">")||this.operator.startsWith("<")&&f.operator.startsWith("<")||this.semver.version===f.semver.version&&this.operator.includes("=")&&f.operator.includes("=")||a(this.semver,"<",f.semver,h)&&this.operator.startsWith(">")&&f.operator.startsWith("<")||a(this.semver,">",f.semver,h)&&this.operator.startsWith("<")&&f.operator.startsWith(">")))}};t.exports=n;var i=b0(),{safeRe:o,t:s}=_f(),a=fx(),l=Bm(),c=ti(),u=ts()})),Um=xt(((e,t)=>{var r=ts(),n=(i,o,s)=>{try{o=new r(o,s)}catch{return!1}return o.test(i)};t.exports=n})),ZL=xt(((e,t)=>{var r=ts(),n=(i,o)=>new r(i,o).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" "));t.exports=n})),eN=xt(((e,t)=>{var r=ti(),n=ts(),i=(o,s,a)=>{let l=null,c=null,u=null;try{u=new n(s,a)}catch{return null}return o.forEach(d=>{u.test(d)&&(!l||c.compare(d)===-1)&&(l=d,c=new r(l,a))}),l};t.exports=i})),tN=xt(((e,t)=>{var r=ti(),n=ts(),i=(o,s,a)=>{let l=null,c=null,u=null;try{u=new n(s,a)}catch{return null}return o.forEach(d=>{u.test(d)&&(!l||c.compare(d)===1)&&(l=d,c=new r(l,a))}),l};t.exports=i})),rN=xt(((e,t)=>{var r=ti(),n=ts(),i=Fm(),o=(s,a)=>{s=new n(s,a);let l=new r("0.0.0");if(s.test(l)||(l=new r("0.0.0-0"),s.test(l)))return l;l=null;for(let c=0;c<s.set.length;++c){const u=s.set[c];let d=null;u.forEach(f=>{const h=new r(f.semver.version);switch(f.operator){case">":h.prerelease.length===0?h.patch++:h.prerelease.push(0),h.raw=h.format();case"":case">=":(!d||i(h,d))&&(d=h);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${f.operator}`)}}),d&&(!l||i(l,d))&&(l=d)}return l&&s.test(l)?l:null};t.exports=o})),nN=xt(((e,t)=>{var r=ts(),n=(i,o)=>{try{return new r(i,o).range||"*"}catch{return null}};t.exports=n})),T0=xt(((e,t)=>{var r=ti(),n=Hm(),{ANY:i}=n,o=ts(),s=Um(),a=Fm(),l=S0(),c=k0(),u=I0(),d=(f,h,g,m)=>{f=new r(f,m),h=new o(h,m);let v,b,I,C,x;switch(g){case">":v=a,b=c,I=l,C=">",x=">=";break;case"<":v=l,b=u,I=a,C="<",x="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(f,h,m))return!1;for(let $=0;$<h.set.length;++$){const P=h.set[$];let L=null,J=null;if(P.forEach(V=>{V.semver===i&&(V=new n(">=0.0.0")),L=L||V,J=J||V,v(V.semver,L.semver,m)?L=V:I(V.semver,J.semver,m)&&(J=V)}),L.operator===C||L.operator===x||(!J.operator||J.operator===C)&&b(f,J.semver))return!1;if(J.operator===x&&I(f,J.semver))return!1}return!0};t.exports=d})),iN=xt(((e,t)=>{var r=T0(),n=(i,o,s)=>r(i,o,">",s);t.exports=n})),oN=xt(((e,t)=>{var r=T0(),n=(i,o,s)=>r(i,o,"<",s);t.exports=n})),sN=xt(((e,t)=>{var r=ts(),n=(i,o,s)=>(i=new r(i,s),o=new r(o,s),i.intersects(o,s));t.exports=n})),aN=xt(((e,t)=>{var r=Um(),n=es();t.exports=(i,o,s)=>{const a=[];let l=null,c=null;const u=i.sort((g,m)=>n(g,m,s));for(const g of u)r(g,o,s)?(c=g,l||(l=g)):(c&&a.push([l,c]),c=null,l=null);l&&a.push([l,null]);const d=[];for(const[g,m]of a)g===m?d.push(g):!m&&g===u[0]?d.push("*"):m?g===u[0]?d.push(`<=${m}`):d.push(`${g} - ${m}`):d.push(`>=${g}`);const f=d.join(" || "),h=typeof o.raw=="string"?o.raw:String(o);return f.length<h.length?f:o}})),lN=xt(((e,t)=>{var r=ts(),n=Hm(),{ANY:i}=n,o=Um(),s=es(),a=(h,g,m={})=>{if(h===g)return!0;h=new r(h,m),g=new r(g,m);let v=!1;e:for(const b of h.set){for(const I of g.set){const C=u(b,I,m);if(v=v||C!==null,C)continue e}if(v)return!1}return!0},l=[new n(">=0.0.0-0")],c=[new n(">=0.0.0")],u=(h,g,m)=>{if(h===g)return!0;if(h.length===1&&h[0].semver===i){if(g.length===1&&g[0].semver===i)return!0;m.includePrerelease?h=l:h=c}if(g.length===1&&g[0].semver===i){if(m.includePrerelease)return!0;g=c}const v=new Set;let b,I;for(const Y of h)Y.operator===">"||Y.operator===">="?b=d(b,Y,m):Y.operator==="<"||Y.operator==="<="?I=f(I,Y,m):v.add(Y.semver);if(v.size>1)return null;let C;if(b&&I){if(C=s(b.semver,I.semver,m),C>0)return null;if(C===0&&(b.operator!==">="||I.operator!=="<="))return null}for(const Y of v){if(b&&!o(Y,String(b),m)||I&&!o(Y,String(I),m))return null;for(const Pe of g)if(!o(Y,String(Pe),m))return!1;return!0}let x,$,P,L,J=I&&!m.includePrerelease&&I.semver.prerelease.length?I.semver:!1,V=b&&!m.includePrerelease&&b.semver.prerelease.length?b.semver:!1;J&&J.prerelease.length===1&&I.operator==="<"&&J.prerelease[0]===0&&(J=!1);for(const Y of g){if(L=L||Y.operator===">"||Y.operator===">=",P=P||Y.operator==="<"||Y.operator==="<=",b){if(V&&Y.semver.prerelease&&Y.semver.prerelease.length&&Y.semver.major===V.major&&Y.semver.minor===V.minor&&Y.semver.patch===V.patch&&(V=!1),Y.operator===">"||Y.operator===">="){if(x=d(b,Y,m),x===Y&&x!==b)return!1}else if(b.operator===">="&&!Y.test(b.semver))return!1}if(I){if(J&&Y.semver.prerelease&&Y.semver.prerelease.length&&Y.semver.major===J.major&&Y.semver.minor===J.minor&&Y.semver.patch===J.patch&&(J=!1),Y.operator==="<"||Y.operator==="<="){if($=f(I,Y,m),$===Y&&$!==I)return!1}else if(I.operator==="<="&&!Y.test(I.semver))return!1}if(!Y.operator&&(I||b)&&C!==0)return!1}return!(b&&P&&!I&&C!==0||I&&L&&!b&&C!==0||V||J)},d=(h,g,m)=>{if(!h)return g;const v=s(h.semver,g.semver,m);return v>0?h:v<0||g.operator===">"&&h.operator===">="?g:h},f=(h,g,m)=>{if(!h)return g;const v=s(h.semver,g.semver,m);return v<0?h:v>0||g.operator==="<"&&h.operator==="<="?g:h};t.exports=a})),cN=xt(((e,t)=>{var r=_f(),n=Pf(),i=ti(),o=cx(),s=mc(),a=jL(),l=zL(),c=BL(),u=FL(),d=HL(),f=UL(),h=qL(),g=WL(),m=es(),v=VL(),b=GL(),I=w0(),C=YL(),x=KL(),$=Fm(),P=S0(),L=ux(),J=dx(),V=I0(),Y=k0(),Pe=fx(),M=XL(),H=JL(),ne=Hm(),ae=ts(),ye=Um(),te=ZL(),z=eN(),A=tN(),K=rN(),Q=nN(),_=T0(),B=iN(),U=oN(),fe=sN(),W=aN(),se=lN();t.exports={parse:s,valid:a,clean:l,inc:c,diff:u,major:d,minor:f,patch:h,prerelease:g,compare:m,rcompare:v,compareLoose:b,compareBuild:I,sort:C,rsort:x,gt:$,lt:P,eq:L,neq:J,gte:V,lte:Y,cmp:Pe,coerce:M,truncate:H,Comparator:ne,Range:ae,satisfies:ye,toComparators:te,maxSatisfying:z,minSatisfying:A,minVersion:K,validRange:Q,outside:_,gtr:B,ltr:U,intersects:fe,simplifyRange:W,subset:se,SemVer:i,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:n.SEMVER_SPEC_VERSION,RELEASE_TYPES:n.RELEASE_TYPES,compareIdentifiers:o.compareIdentifiers,rcompareIdentifiers:o.rcompareIdentifiers}})),ao=cN(),Og=class extends Error{constructor(e,t,r){super(r),T(this,"tagName",void 0),T(this,"packageSpec",void 0),T(this,"name","ElementPackagePolicyError"),this.tagName=e,this.packageSpec=t}};function qm(e){return(0,ao.valid)(e)===e}function E1(e){const t=Ra(e);return{packageName:t.name,packagePath:t.path?`${t.name}/${t.path}`:t.name,version:t.version}}function hx(e,t){if(!t)return;const r=t.allowedPackages.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(const[n,i]of Object.entries(e)){const o=String(i).trim();let s;try{s=E1(o)}catch{throw new Og(n,o,`Element package policy rejected invalid package spec "${o}" for ${n}.`)}if((t.requireExactVersions??!0)&&!qm(s.version)){const a=s.version.includes("+")?"does not allow semver build metadata because legacy IIFE bundle routes use + as a package separator":"requires an exact version";throw new Og(n,o,`Element package policy ${a} for ${n}; received "${o}".`)}if(!r.some(a=>{if(a===o)return!0;try{const l=E1(a);return l.version.length===0&&l.packagePath===s.packagePath}catch{return!1}}))throw new Og(n,o,`Element package policy does not allow "${o}" for ${n}.`)}}var wl=class extends Error{constructor(e){const t=[...e.keys()];super(`Backend adapter failure for ${e.size} tag(s): ${t.join(", ")}`),T(this,"name","AdapterFailure"),T(this,"reasons",void 0),this.reasons=e}},uN="pie-mathjax-version-conflict",dN="pie-mathjax-no-asset-root",Lg={[uN]:["condition","docsUrl"],[dN]:["effect","docsUrl"]},dh=Symbol.for("@pie-players/pie-players-shared/mathjax-version-conflict-tracked");function fN(e){const t=globalThis;t[dh]??(t[dh]=new WeakMap);let r=t[dh].get(e);return r||(r=new WeakSet,t[dh].set(e,r)),r}function hN(e,t){const r=n=>{const i=t();if(!i)return;const o=fN(n);if(o.has(i))return;o.add(i);const s=n.detail,a=s&&typeof s=="object"?s:{};try{i.trackEvent(n.type,Object.fromEntries(Lg[n.type].map(l=>[l,a[l]])))}catch{}};for(const n of Object.keys(Lg))e.addEventListener(n,r);return()=>{for(const n of Object.keys(Lg))e.removeEventListener(n,r)}}var rc={delivery:{subpath:"",tagSuffix:""},author:{subpath:"/author",tagSuffix:"-config",fallback:"delivery"},print:{subpath:"/print",tagSuffix:"-print",fallback:"delivery"}};function pN(e){const t=e.cdnBaseUrl.replace(/\/+$/,""),r=gN(e.cdnProvider,t),n=e.moduleResolution??"url",i=e.view??"delivery",o=e.loadControllers??!0,s=SN(i,e.viewConfig),a=Yp(s,i),l=new Set,c=new Map,u=new Map,d=new Map,f=new WeakSet;let h={},g=C1,m=x1,v,b=A1,I;const C={replaceImporter(z){g=z},observeImportMapInjection(z){v=z},replacePackageMetadataLoader(z){m=z},replaceImportShimLoader(z){b=z,I=void 0},restore(){g=C1,m=x1,b=A1,I=void 0,v=void 0,l.clear(),c.clear(),u.clear(),d.clear(),h={}}};async function x(z,A){if(!z||Object.keys(z).length===0)return;n==="import-map"&&$1(),ne(A.doc);const K={};for(const[_,B]of Object.entries(z)){const U=Ra(B).name;if(n==="import-map"){const fe=c.get(U);if(fe&&fe!==B)throw new Error(`Conflicting browser ESM package version for ${U}: ${fe} is already mapped, but ${B} was requested`)}l.has(B)||(K[_]=B)}if(Object.keys(K).length>0){let _;try{_=await RN(K,s,r,o,n==="import-map",m,h,ae)}catch(se){throw te(se),se}for(const[se,_e]of _.unpublished)d.set(se,_e),typeof console<"u"&&console.error&&console.error(`[pie-esm] ${_e}`);const B=n==="url"?await Y(_.metadata,A.doc):void 0,U=B?M(B,A.doc):void 0,fe=ON({..._.imports,...U?.imports},A.doc);let W;if(Object.keys(fe).length>0){const se=JSON.stringify({imports:fe},null,2);$1(),W=LN(se,A.doc,U?.mappedRuntime),v?.(se,A.doc)}for(const[se,_e]of U?.served??[])u.set(se,_e);h=_.sharedDependencyVersions;for(const se of Object.values(K))l.add(se),n==="import-map"&&c.set(Ra(se).name,se);W&&await L(fe,W,A.doc)}const Q=new Map;if(await Promise.all(Object.entries(z).map(async([_,B])=>{const U=Ra(B).name;let fe;try{fe=bm(_,`element tag for ${U}`)}catch(le){Q.set(_,{kind:"define-failed",tag:_,cause:le instanceof Error?le.message:String(le)});return}const W=R1(U,B,s,n,r,i),se=d.get(B);if(se){Q.set(_,{kind:"module-load-failed",tag:_,specifier:W,cause:se});return}const _e=u.get(B);let Ue;if(_e&&(Ue=await $(B,_e,A.doc)),!Ue){let le;try{le=await P(W,A.doc)}catch(de){if(s.fallback){const Ne=R1(U,B,rc[s.fallback]??rc.delivery,n,r,s.fallback);try{le=await P(Ne,A.doc)}catch(Ae){Q.set(_,{kind:"module-load-failed",tag:_,specifier:Ne,cause:Ae instanceof Error?Ae.message:String(Ae)});return}}else{Q.set(_,{kind:"module-load-failed",tag:_,specifier:W,cause:de instanceof Error?de.message:String(de)});return}}if(Ue=P1(le,i),!Ue){Q.set(_,{kind:"no-element-class",tag:_,packageName:U});return}}if(!Xv(Ue)){Q.set(_,{kind:"not-a-constructor",tag:_,packageName:U});return}try{Cb(fe,class extends Ue{},`element tag for ${U}`)}catch(le){Q.set(_,{kind:"define-failed",tag:_,cause:le instanceof Error?le.message:String(le)});return}let it=null;if(o){const le=u.get(B),de=le?.views.controller;if(le&&de)try{const Ne=await P(r.browserViewUrl(B,de),A.doc);it=Ne?.default??Ne}catch(Ne){ye(B,le.declaration,le.runtime,`its editor-runtime controller failed to load: ${Ng(Ne)}`)}if(!it){const Ne=kN(U,B,n,r);try{const Ae=await P(Ne,A.doc);it=Ae?.default??Ae}catch{}}}Gb({package:B,status:Jl.loaded,tagName:fe,element:Ue,controller:it,config:null,bundleType:qs.esm})})),Q.size>0)throw new wl(Q)}async function $(z,A,K){const Q=r.browserViewUrl(z,A.views[a]);try{const _=P1(await P(Q,K),i);if(Xv(_))return _;throw new Error(`${Q} exports no custom element class`)}catch(_){u.delete(z),ye(z,A.declaration,A.runtime,`its editor-runtime ${a} view failed to load: ${Ng(_)}`);return}}async function P(z,A){return await DN(A),Sx(A)?(await V(A))(z):g(z)}async function L(z,A,K){let Q="applied";try{A.type===E0?(await V(K)).addImportMap({imports:z}):await J(z)&&(Q="rejected",await V(K))}finally{NN(A,Q)}}async function J(z){const A="react"in z?"react":Object.keys(z)[0];try{return await g(A),!1}catch{}try{await g(z[A])}catch{return!1}return!0}function V(z){return I??(I=b().then(A=>(A.addImportMap({imports:wy(z)}),A),A=>{throw I=void 0,A})),I}async function Y(z,A){const K=[];for(const[_,B]of z){const U=_N(B);if(U!==void 0){if(U===null){ye(_,void 0,void 0,"its pie.browserEditorRuntime declaration is invalid");continue}U.views[a]&&K.push({packageVersion:_,declaration:U})}}if(K.length===0)return{candidates:K};if(!Ix()){for(const{packageVersion:_,declaration:B}of K)ye(_,B,void 0,"this browser does not support import maps");return{candidates:[]}}if(_1(A))return{candidates:K};const Q=$N(K);return{candidates:K,target:{runtime:Q,...await Pe(Q)}}}async function Pe(z){const A=`${z.name}@${z.version}`;let K;try{K=await m(A,r.packageJsonUrl(A))}catch(_){return{failure:`the package.json of ${A} could not be loaded: ${Ng(_)}`}}if(!K)return{failure:`the package.json of ${A} could not be loaded`};const Q=AN(K);return Q?{modules:Q}:{failure:`${A} declares no valid pie.browserModules`}}function M(z,A){const K={imports:{},served:new Map};if(z.candidates.length===0)return K;let Q=_1(A);if(!Q){const{target:_}=z;let B=_?.failure;if(_?.modules){const fe=wy(A),W=Object.keys(_.modules).find(se=>se in fe);W&&(B=`the page already maps ${W}`)}if(B||!_?.modules){for(const{packageVersion:fe,declaration:W}of z.candidates)ye(fe,W,void 0,B??"the page no longer maps its editor runtime");return K}Q=_.runtime;const U=`${Q.name}@${Q.version}`;for(const[fe,W]of Object.entries(_.modules))K.imports[fe]=r.browserViewUrl(U,W);K.mappedRuntime=U}for(const{packageVersion:_,declaration:B}of z.candidates){if(!MN(Q,B)){ye(_,B,Q,`the page maps ${Q.name}@${Q.version}, which cannot serve ${B.name}@${B.version}`);continue}K.served.set(_,{views:B.views,declaration:B,runtime:Q}),B.version!==Q.version&&ae({dependencyName:Q.name,existingVersion:Q.version,requestedVersion:B.version,resolvedVersion:Q.version,packageVersion:_})}return K}function H(){if(!e.trackPageActions)return;const z=e.instrumentationProvider;if(bf(z)&&z.isReady())return z}function ne(z){const A=z.defaultView;!A||f.has(A)||(f.add(A),hN(A,H))}function ae(z,A=`[pie-esm] Shared dependency version conflict resolved for ${String(z.dependencyName)}`){typeof console<"u"&&console.warn&&console.warn(A,z);const K=H();if(K)try{K.trackEvent("pie-esm-shared-dependency-conflict",z)}catch{}}function ye(z,A,K,Q){ae({dependencyName:A?.name,existingVersion:K?.version,requestedVersion:A?.version,packageVersion:z,fallback:"./browser/*",reason:Q},`[pie-esm] ${z} loads ./browser/* in place of its editor-runtime variant: ${Q}`)}function te(z){const A=z instanceof Error?z:new Error(String(z));typeof console<"u"&&console.error&&console.error("[pie-esm] Shared dependency resolution failed",A);const K=H();if(K)try{K.trackError(A,{component:"esm-adapter",errorType:"EsmSharedDependencyError"})}catch{}}return{load:x,get __seams(){return C}}}function C1(e){return Mr(()=>import(e),[],import.meta.url)}var fh=new Map;function x1(e,t){const r=fh.get(t);if(r)return r;const n=mN(t);fh.set(t,n);const i=()=>{fh.get(t)===n&&fh.delete(t)};return n.then(o=>{o===null&&i()},i),n}async function mN(e){const t=typeof window<"u"&&typeof window.fetch=="function"?window.fetch.bind(window):void 0;if(!t)return null;const r=await t(e);return r.ok?await r.json():null}var px="dist/runtime-support.js";function gN(e,t){if(vN(e))return e;const r=e??(t.includes("esm.sh")?"esm.sh":"jsdelivr");return r==="esm.sh"?bN(t):yN(t,r)}function vN(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.packageJsonUrl=="function"&&typeof t.browserViewUrl=="function"&&typeof t.browserControllerUrl=="function"&&typeof t.sharedDependencyUrl=="function"}function yN(e,t="jsdelivr"){return{name:t,packageJsonUrl:r=>`${e}/${r}/package.json`,browserViewUrl:(r,n)=>`${e}/${r}/dist/browser/${n}/index.js`,browserControllerUrl:r=>`${e}/${r}/dist/browser/controller/index.js`,runtimeSupportUrl:r=>`${e}/${r}/${px}`,sharedDependencyUrl:(r,n,i)=>`${e}/${r}@${n}${i?`/${i}/+esm`:"/+esm"}`}}function bN(e){const t=e.replace(/\/+$/,""),r=wN(t);return{name:"esm.sh",packageJsonUrl:n=>`${r}/${n}/package.json`,browserViewUrl:(n,i)=>`${r}/${n}/dist/browser/${i}/index.js`,browserControllerUrl:n=>`${r}/${n}/dist/browser/controller/index.js`,runtimeSupportUrl:n=>`${r}/${n}/${px}`,sharedDependencyUrl:(n,i,o)=>{const s=o?`/${o}`:"";return`${t}/${n}@${i}${s}`}}}function wN(e){try{const t=new URL(e);if(t.hostname==="raw.esm.sh")return t.toString().replace(/\/+$/,"");if(t.hostname==="esm.sh")return t.hostname="raw.esm.sh",t.toString().replace(/\/+$/,"")}catch{}return"https://raw.esm.sh"}function SN(e,t){return t??rc[e]??rc.delivery}function IN(e,t,r,n,i){if(!e?.exports)return;const o=new Set([`./browser/${Yp(r,i)}`]);if(r.fallback){const s=rc[r.fallback];s&&o.add(`./browser/${Yp(s,r.fallback)}`)}n&&o.add("./browser/controller");for(const s of o)if(!(s in e.exports))return`${t} does not publish browser ESM export ${s}; use IIFE/preloaded mode or publish browser ESM artifacts first`}function yy(e){const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:null}function Yp(e,t="delivery"){return yy(e.subpath)??t}function Xh(e,t,r,n="delivery"){const i=Yp(t,n);return r.browserViewUrl(e,i)}function mx(e,t){return t.browserControllerUrl(e)}function R1(e,t,r,n,i,o){return n==="import-map"?r.subpath?`${e}${r.subpath}`:e:Xh(t,r,i,o)}function kN(e,t,r,n){return r==="import-map"?`${e}/controller`:mx(t,n)}function P1(e,t){if(!(!e||typeof e!="object"))return t==="author"?e.default??e.Configure??e.Element:t==="print"?e.default??e.Print??e.Element:e.default??e.Element}var gx=["react","react-dom"];function TN(e,t,r){const n=e?.pie?.browserSharedDependencies?.[t];if(!n)throw new Error(`${r} is missing required pie.browserSharedDependencies.${t}`);if(!qm(n))throw new Error(`${r} pie.browserSharedDependencies.${t} must be an exact version; received "${n}"`);return n}function EN(e,t){return!!(e?.pie?.browserSharedDependencies?.[t]||e?.peerDependencies?.[t]||e?.dependencies?.[t]||e?.optionalDependencies?.[t])}function CN(e,t,r,n,i,o,s,a){if(!i)return;const l=t[n];let c=i;l&&l!==i&&(c=xN(n,l,i,s,r.has(n)),a({dependencyName:n,existingVersion:l,requestedVersion:i,resolvedVersion:c,packageVersion:s})),t[n]=c,e[n]=o.sharedDependencyUrl(n,c),n==="react"&&(e["react/jsx-runtime"]=o.sharedDependencyUrl("react",c,"jsx-runtime"),e["react/jsx-dev-runtime"]=o.sharedDependencyUrl("react",c,"jsx-dev-runtime")),n==="react-dom"&&(e["react-dom/client"]=o.sharedDependencyUrl("react-dom",c,"client"))}function xN(e,t,r,n,i){if((0,ao.major)(t)!==(0,ao.major)(r))throw new Error(`Conflicting shared browser dependency ${e}: ${t} vs ${r} from ${n}; different major versions cannot share one browser singleton`);if(i&&(0,ao.compare)(r,t)>0)throw new Error(`Conflicting shared browser dependency ${e}: ${t} is already selected, but ${n} requires higher version ${r}; the browser singleton cannot be upgraded after import-map injection`);return(0,ao.compare)(t,r)>=0?t:r}async function RN(e,t,r,n,i,o,s,a){const l={},c={...s},u=new Set(Object.keys(s)),d=new Map,f=new Map;for(const[,h]of Object.entries(e)){const g=await o(h,r.packageJsonUrl(h)),m=IN(g,h,t,n,yy(t.subpath)??"delivery");if(m){f.set(h,m);continue}d.set(h,g);const v=Ra(h).name;if(i&&(l[v]=Xh(h,rc.delivery,r,"delivery"),t.subpath&&(l[`${v}${t.subpath}`]=Xh(h,t,r,yy(t.subpath)??"delivery")),n&&(l[`${v}/controller`]=mx(h,r)),t.fallback)){const b=rc[t.fallback];if(b){const I=b.subpath?`${v}${b.subpath}`:v;l[I]=Xh(h,b,r,t.fallback)}}for(const b of gx)EN(g,b)&&CN(l,c,u,b,TN(g,b,h),r,h,a)}return{imports:l,sharedDependencyVersions:c,metadata:d,unpublished:f}}var vx="data-pie-editor-runtime",yx=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,bx=/^[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/,PN=/^(?:@[A-Za-z0-9_-][A-Za-z0-9._-]*\/)?[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/;function by(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _N(e){const t=e?.pie?.browserEditorRuntime;if(t===void 0)return;if(!by(t)||!by(t.views))return null;const{name:r,version:n}=t;if(typeof r!="string"||!yx.test(r)||typeof n!="string"||!qm(n))return null;const i=Object.entries(t.views);return i.length===0||!i.every(([,o])=>typeof o=="string"&&bx.test(o))?null:{name:r,version:n,views:Object.fromEntries(i)}}function AN(e){const t=e.pie?.browserModules;if(!by(t))return null;const r=Object.entries(t);return r.length>0&&r.every(([n,i])=>PN.test(n)&&!gx.some(o=>n===o||n.startsWith(`${o}/`))&&typeof i=="string"&&bx.test(i))?Object.fromEntries(r):null}function $N(e){const{name:t}=e[0].declaration;let{version:r}=e[0].declaration;for(const{declaration:n}of e)n.name===t&&(0,ao.compare)(n.version,r)>0&&(r=n.version);return{name:t,version:r}}function MN(e,t){return e.name!==t.name||(0,ao.major)(e.version)!==(0,ao.major)(t.version)||(0,ao.major)(e.version)===0&&(0,ao.minor)(e.version)!==(0,ao.minor)(t.version)?!1:(0,ao.compare)(e.version,t.version)>=0}function Wm(e){return typeof e.querySelectorAll=="function"?Array.from(e.querySelectorAll(`script[type="importmap"], script[type="${E0}"]`)):[]}function _1(e){for(const t of Wm(e)){const r=t.getAttribute(vx),n=r?.lastIndexOf("@")??-1;if(!r||n<=0)continue;const i=r.slice(0,n),o=r.slice(n+1);if(yx.test(i)&&qm(o))return{name:i,version:o}}return null}function Ng(e){return e instanceof Error?e.message:String(e)}function ON(e,t){const r=wy(t);return Object.fromEntries(Object.entries(e).filter(([n])=>!(n in r)))}var Vm="data-pie-import-map",wx="pie-import-map-settled",E0="importmap-shim";function LN(e,t,r){const n=t.createElement("script");return n.type=Sx(t)?E0:"importmap",n.setAttribute(Vm,"pending"),r&&n.setAttribute(vx,r),n.textContent=e,t.head.appendChild(n),n}function NN(e,t){e.setAttribute(Vm,t),e.dispatchEvent(new Event(wx))}function Sx(e){return Wm(e).some(t=>t.getAttribute(Vm)==="rejected")}async function DN(e){const t=Wm(e).filter(r=>r.getAttribute(Vm)==="pending");await Promise.all(t.map(r=>new Promise(n=>r.addEventListener(wx,()=>n(),{once:!0}))))}function wy(e){const t=Object.create(null);for(const r of Wm(e))try{const n=JSON.parse(r.textContent||"{}")?.imports;if(!n||typeof n!="object")continue;for(const[i,o]of Object.entries(n))typeof o=="string"&&!(i in t)&&(t[i]=o)}catch{}return t}async function A1(){const e=globalThis;e.importShim||(e.esmsInitOptions={...e.esmsInitOptions,shimMode:!0,noLoadEventRetriggers:!0},await Mr(()=>import("./chunks/module-shim-58659a86.js"),[],import.meta.url));const t=e.importShim;if(typeof t!="function"||typeof t.addImportMap!="function")throw new Error("es-module-shims did not initialize, so this browser cannot load browser ESM elements after the page's first module load. Use the iife or preloaded strategy.");try{t.addImportMap({imports:{}})}catch{throw new Error("This page runs es-module-shims in polyfill mode, and this browser rejects import maps added after the page's first module load. Load es-module-shims in shim mode, or use the iife or preloaded strategy.")}return t}function Ix(){const e=typeof HTMLScriptElement<"u"?HTMLScriptElement:void 0;return typeof e?.supports=="function"&&e.supports("importmap")}function $1(){if(!Ix())throw new Error('This browser does not support import maps. Use moduleResolution="url" or switch to iife/preloaded strategy.')}function jN(e){const t=new Map;for(const n of Object.values(e)){const i=String(n),o=Ra(i).name,s=t.get(o)??new Set;s.add(i),t.set(o,s)}const r=[...t.entries()].filter(([,n])=>n.size>1).map(([n])=>n).sort();return r.length>0?`IIFE bundles cannot load multiple package specs for: ${r.join(", ")}`:void 0}function zN(e){const t=e.bundleType??qs.clientPlayer,r=e.needsControllers??!0;let n=M1;const i=new Map,o={replaceLoadBundleScript(f){n=f,i.clear()},restore(){n=M1,i.clear()}};async function s(f,h){const g=i.get(f);if(g)return g;const m=a(f,h).finally(()=>{i.delete(f)});return i.set(f,m),m}async function a(f,h){const{retryDelayMs:g,timeoutMs:m}=UN(e.bundleRetry),v=Date.now();let b=0;for(;;){b+=1;try{await n(f,h);const I=Date.now()-v;b>1&&(e.onBundleRetryStatus?.({state:"completed",url:f,attempt:b,elapsedMs:I,timeoutMs:m}),c("pie-iife-bundle-retry-success",{url:f,attempt:b,elapsedMs:I,timeoutMs:m}));return}catch(I){const C=Date.now()-v,x=m-C,$=I instanceof Error?I.message:String(I);if(x<=0){const L=new Error(`IIFE bundle load timed out after ${m}ms: ${f}`);throw e.onBundleRetryStatus?.({state:"timeout",url:f,attempt:b,elapsedMs:C,timeoutMs:m,reason:$}),c("pie-iife-bundle-retry-timeout",{url:f,attempt:b,elapsedMs:C,timeoutMs:m,lastError:$}),u(L,{url:f,attempt:b,elapsedMs:C,timeoutMs:m,lastError:$}),L}const P=Math.min(g,x);e.onBundleRetryStatus?.({state:"retrying",url:f,attempt:b,elapsedMs:C,timeoutMs:m,retryDelayMs:P,reason:$}),c("pie-iife-bundle-retry",{url:f,attempt:b,elapsedMs:C,retryDelayMs:P,timeoutMs:m,lastError:$}),await qN(P)}}}function l(){if(!e.trackPageActions)return;const f=e.instrumentationProvider;if(bf(f)&&f.isReady())return f}function c(f,h){const g=l();if(g)try{g.trackEvent(f,h)}catch{}}function u(f,h){const g=l();if(g)try{g.trackError(f,{...h,component:"iife-adapter",errorType:"IifeBundleRetryError"})}catch{}}async function d(f,h){if(!f||Object.keys(f).length===0)return;const g=jN(f);if(g){const C=new Map;for(const x of Object.keys(f))C.set(x,{kind:"backend-rejected",tag:x,cause:g});throw new wl(C)}const m=FN(f,t,e);try{await s(m,h.doc)}catch(C){const x=C instanceof Error?C.message:String(C),$=new Map;for(const P of Object.keys(f))$.set(P,{kind:"bundle-load-failed",tag:P,url:m,cause:x});throw new wl($)}const v=BN();if(!v){const C=new Map;for(const x of Object.keys(f))C.set(x,{kind:"bundle-load-failed",tag:x,url:m,cause:"window.pie.default missing after bundle load"});throw new wl(C)}const b=new Map,I=t===qs.editor;for(const[C,x]of Object.entries(f)){const $=jA(x),P=v[$];if(!P){b.set(C,{kind:"package-not-in-bundle",tag:C,packageName:$,availablePackages:Object.keys(v)});continue}const L=I?P.Configure??WN():P.Element;if(!L){b.set(C,{kind:"no-element-class",tag:C,packageName:$});continue}if(!Xv(L)){b.set(C,{kind:"not-a-constructor",tag:C,packageName:$});continue}let J;try{J=bm(C,`element tag for ${$}`)}catch(V){b.set(C,{kind:"define-failed",tag:C,cause:V instanceof Error?V.message:String(V)});continue}try{Cb(J,class extends L{},`element tag for ${$}`)}catch(V){b.set(C,{kind:"define-failed",tag:C,cause:V instanceof Error?V.message:String(V)});continue}Gb({package:x,status:Jl.loaded,tagName:J,element:L,controller:r?P.controller??null:null,config:P.config??null,bundleType:t})}if(b.size>0)throw new wl(b)}return{load:d,get __seams(){return o}}}function M1(e,t){return new Promise((r,n)=>{const i=t.createElement("script");i.src=e,i.defer=!0,i.setAttribute("data-pie-bundle","true"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load IIFE bundle from: ${e}`)),t.head.appendChild(i)})}function BN(){const e=globalThis.window?.pie?.default;if(!(!e||typeof e!="object"))return e}function FN(e,t,r){const n=Object.keys(e).sort().join(",");if(r.bundleInfo?.url){const s=r.bundleInfo.url.includes("?")?"&":"?";return n?`${r.bundleInfo.url}${s}elements=${encodeURIComponent(n)}`:r.bundleInfo.url}const i=zA(Object.values(e)),o=`${HN(r.bundleHost)}${i}/${t}`;return n?`${o}?elements=${encodeURIComponent(n)}`:o}function HN(e){return`${e.trim().replace(/\/+$/,"")}/`}function UN(e){return{retryDelayMs:typeof e?.retryDelayMs=="number"&&e.retryDelayMs>0?e.retryDelayMs:Kv.retryDelayMs,timeoutMs:typeof e?.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:Kv.timeoutMs}}function qN(e){return new Promise(t=>setTimeout(t,e))}function WN(){return class extends HTMLElement{constructor(...t){super(...t),T(this,"_model",void 0),T(this,"_configuration",void 0)}get model(){return this._model}set model(t){this._model=t}get configuration(){return this._configuration}set configuration(t){this._configuration=t}}}var VN=class extends Error{constructor(e,t,r){super(e),T(this,"name","ElementLoaderError"),T(this,"unregisteredTags",void 0),T(this,"reasons",void 0),this.unregisteredTags=t,this.reasons=r}},GN=class extends Error{constructor(e,t,r,n={}){super(YN(e,t,r,n)),T(this,"name","ElementAssertionError"),T(this,"expectedTags",void 0),T(this,"missingTags",void 0),T(this,"currentlyRegisteredTags",void 0),this.expectedTags=e,this.missingTags=t,this.currentlyRegisteredTags=r}};function YN(e,t,r,n){const i=t.map(o=>{const s=kx(n[o]),a=dp(o).baseName,l=s?r.filter(u=>KN(u)===s):r.filter(u=>dp(u).baseName===a);!l.includes(a)&&Af(a)&&l.push(a);const c=s??a;return l.length>0?`${c} is registered as [${l.join(", ")}]`:`nothing is registered for ${c}`});return`ElementLoader.assertRegistered: missing [${t.join(", ")}] of [${e.join(", ")}]; ${i.join("; ")}.`}function kx(e){if(e)try{return Ra(e).name||void 0}catch{return}}function KN(e){return kx(Am()[e]?.package)}var XN=5e3,JN=Kv.timeoutMs,hh=new Map,O1=new Map,QN=new Map;async function ZN(e,t){if(!e||Object.keys(e).length===0)return;hx(e,t.elementPackagePolicy);const r=Object.keys(e),n=t.whenDefinedTimeoutMs??XN,i=t.loadTimeoutMs??JN;if(f5(r))return;const o=o5(t.backend,e),s=hh.get(o);if(s)return s;const a=e5(e,r,n5(t.backend),{doc:i5(t.doc),whenDefinedTimeoutMs:n},n,i);hh.set(o,a);try{await a}finally{hh.get(o)===a&&hh.delete(o)}}async function e5(e,t,r,n,i,o){let s;try{await t5(r.load(e,n),t,o)}catch(u){s=u instanceof Error?u:new Error(String(u))}const a=await Promise.all(t.map(async u=>{if(Af(u))return{tag:u,ok:!0};const d=z1(s,u);if(d&&d.kind!=="timeout")return{tag:u,ok:!1};try{return await h5(u,i),{tag:u,ok:!0}}catch{return{tag:u,ok:!1}}})),l=new Set,c=new Map;for(const u of a){if(u.ok)continue;l.add(u.tag);const d=z1(s,u.tag);c.set(u.tag,d??{kind:"timeout",tag:u.tag,timeoutMs:i})}if(l.size>0)throw new VN(`Element registration failed; missing tags: ${[...l].join(", ")}`,l,c)}async function t5(e,t,r){let n;try{await Promise.race([e,new Promise((i,o)=>{n=setTimeout(()=>{const s=new Map;for(const a of t)s.set(a,{kind:"timeout",tag:a,timeoutMs:r});o(new wl(s))},r)})])}finally{n&&clearTimeout(n)}}function r5(e){const t=Array.isArray(e)?{}:e??{},r=Array.isArray(e)?e:Object.keys(t);if(r.length===0)return;const n=r.filter(i=>!Af(i));if(n.length!==0)throw new GN(r,n,p5(),t)}function n5(e){if(Tx(e))return e;if("kind"in e){if(e.kind==="iife")return zN(e);if(e.kind==="esm"){const t=Ex(e),r=QN.get(t);if(r)return r;const n=O1.get(t);if(n)return n;const i=pN(e);return O1.set(t,i),i}}throw new Error("ElementLoader: invalid backend option")}function Tx(e){return typeof e.load=="function"&&!("kind"in e)}function i5(e){if(e)return e;if(typeof document<"u")return document;throw new Error("ElementLoader: no Document available; pass options.doc explicitly")}function o5(e,t){const r=Ex(e),n=Object.entries(t).sort(([i],[o])=>i.localeCompare(o));return`${r}|${JSON.stringify(n)}`}var L1=new WeakMap,s5=0,N1=new WeakMap,a5=0,D1=new WeakMap,l5=0;function Ex(e){if(Tx(e)){let t=L1.get(e);return t||(t=`b${++s5}`,L1.set(e,t)),`backend#${t}`}if("kind"in e){if(e.kind==="iife")return`iife#${j1({kind:"iife",bundleHost:e.bundleHost,bundleType:e.bundleType??"",needsControllers:e.needsControllers??!0,bundleInfo:e.bundleInfo??null,debugEnabled:e.debugEnabled??null,bundleRetry:e.bundleRetry??null,onBundleRetryStatus:e.onBundleRetryStatus??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`;if(e.kind==="esm")return`esm#${j1({kind:"esm",cdnBaseUrl:e.cdnBaseUrl,cdnProvider:e.cdnProvider??null,moduleResolution:e.moduleResolution??"url",view:e.view??"delivery",viewConfig:e.viewConfig??null,loadControllers:e.loadControllers??!0,debugEnabled:e.debugEnabled??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`}return"unknown"}function j1(e){return JSON.stringify(Sy(e,new Map))}function Sy(e,t){if(e==null)return e;const r=typeof e;if(r==="string"||r==="number"||r==="boolean")return e;if(r==="function")return{__functionRef:u5(e)};if(r!=="object")return String(e);const n=e,i=t.get(n);if(i)return{__cycleRef:i};const o=`cycle#${t.size+1}`;if(t.set(n,o),Array.isArray(e))return e.map(a=>Sy(a,t));if(!c5(e))return{__objectRef:d5(n)};const s={};for(const a of Object.keys(e).sort())s[a]=Sy(e[a],t);return s}function c5(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function u5(e){let t=N1.get(e);return t||(t=`fn#${++a5}`,N1.set(e,t)),t}function d5(e){let t=D1.get(e);return t||(t=`obj#${++l5}`,D1.set(e,t)),t}function f5(e){return e.every(t=>Af(t))}function Af(e){return typeof customElements>"u"?!1:customElements.get(e)!==void 0}async function h5(e,t){if(typeof customElements>"u")throw new Error(`no customElements to await ${e}`);let r;try{return await Promise.race([customElements.whenDefined(e).then(()=>{}),new Promise((n,i)=>{r=setTimeout(()=>i(new Error(`Timeout waiting for ${e}`)),t)})])}finally{r&&clearTimeout(r)}}function p5(){return typeof window>"u"?[]:Object.values(Am()).filter(e=>e?.status===Jl.loaded).map(e=>e.tagName).filter(e=>typeof e=="string"&&Af(e)).sort()}function z1(e,t){if(e)return e instanceof wl?e.reasons.get(t):{kind:"backend-rejected",tag:t,cause:e.message}}function m5(e){return e.loadControllers??(e.author||!e.hosted)}function g5(e,t=y5()){const r=e?.elements;if(!t||!r||typeof r!="object")return e;let n=!1;const i={};for(const[o,s]of Object.entries(r)){const a=String(s),l=v5(a,t);i[o]=l??a,l!==void 0&&l!==a&&(n=!0)}return n?{...e,elements:i}:e}function v5(e,t){let r;try{r=Ra(e).name}catch{return}const n=t[r];return typeof n=="string"&&n.length>0?n:void 0}function y5(){if(typeof window>"u")return;const e=window.PIE_PRELOADED_ELEMENTS;return e&&typeof e=="object"?e:void 0}function b5(e){if(typeof window>"u"||typeof customElements>"u")return[];const t=[];for(const[r,n]of Object.entries(e)){if(customElements.get(r))continue;const i=w5(r,n);if(!i)continue;const{entry:o,elementClass:s}=i;Cb(r,class extends s{},`preloaded element tag for ${n}`),Gb({...o,tagName:r}),t.push(r)}return t}function w5(e,t){const{existingEncodedVersion:r}=dp(e);if(!r)return;let n;for(const i of Object.values(Am())){if(i?.status!==Jl.loaded||i.package!==t||typeof i.tagName!="string"||dp(i.tagName).existingEncodedVersion!==r)continue;const o=customElements.get(i.tagName);o&&(!n||!n.entry.controller&&i.controller)&&(n={entry:i,elementClass:o})}return n}function S5(e){let t=e&&typeof e=="object"?{...e}:e;t&&typeof t=="object"&&(delete t.timestamp,delete t.sourceRuntimeId);try{return JSON.stringify(t)}catch{return String(t)}}var I5=e=>!!(e&&typeof e=="object"&&e.sessionCommitReason);function k5(e){let{host:t,kind:r,identity:n,mode:i,send:o}=e,s=ei(t.localName||"pie-shell",()=>!1),a="",l=f=>{let{itemId:h,canonicalItemId:g}=n();if(!h)return;o(ZE,{itemId:h,session:f});let m=Kb({itemId:h,sessionDetail:f});if(m.intent==="metadata-only"||!m.session)return;let v={itemId:h,canonicalItemId:g||h,session:m.session,...m.sessionCommitReason?{sessionCommitReason:m.sessionCommitReason}:{}};Wd(t,qO,v)},c=f=>{if(i()!=="section"||(f.stopPropagation(),r!=="item"))return;let h=f.detail,g=S5(h);!I5(h)&&g===a||(a=g,l(h))},u=f=>{i()==="section"&&f.stopPropagation();let{itemId:h,canonicalItemId:g,contentKind:m}=n();if(!h)return;let v={itemId:h,canonicalItemId:g||h,contentKind:m,detail:f.detail};o(Xb,v)},d=f=>{i()==="section"&&f.stopPropagation();let{itemId:h,canonicalItemId:g,contentKind:m}=n();if(!h)return;let v={itemId:h,canonicalItemId:g||h,contentKind:m,error:f.detail};o(eC,v)};return t.addEventListener("session-changed",c),t.addEventListener("load-complete",u),t.addEventListener("player-error",d),{disconnect:()=>{try{r==="item"&&i()==="section"&&Sf(t,{reason:"teardown",logger:s})}finally{t.removeEventListener("session-changed",c),t.removeEventListener("load-complete",u),t.removeEventListener("player-error",d)}}}}function T5(e,t){return e.kind===t.kind&&e.host===t.host&&e.itemId===t.itemId&&e.canonicalItemId===t.canonicalItemId&&e.contentKind===t.contentKind&&fu(e.settings,t.settings)}function B1(e){return ty(e.item,e.kind)}function Cx(e,t){return e.isConnected||!t?e:t.eventTarget}function Dg(e,t,r){let n={kind:t.kind,itemId:t.itemId,canonicalItemId:t.canonicalItemId,contentKind:t.contentKind,item:t.item,...t.settings?{settings:t.settings}:{},element:t.host,...r?{runtimeId:r.runtimeId}:{}};Wd(Cx(t.host,r),e,n)}function E5(){let e=null,t=null,r;function n(){let o=e;if(!o)return;let s=r;e=null,t=null,r=void 0,Dg(QE,o,s)}function i(o,s){if(!o){n();return}if(e&&r?.runtimeId!==s?.runtimeId&&n(),e&&T5(e,o)){if(e.item===o.item)return;let a=B1(o);if(a!==null&&a===t){e=o;return}e=o,t=a,Dg(_p,o,s);return}e=o,t=B1(o),r=s,Dg(_p,o,s)}return{sync:i,retire:n}}var C5=50;function F1(e,t,r){let n=new Ql(e,{context:t,initialValue:r});return n.connect(),{provider:n,value:r}}function H1(e,t,r){r(e.value,t)||(e.value=t,e.provider.setValue(t))}var x5=(e,t,r)=>{if(e===t)return!0;if(!e||!t||e.id!==t.id)return!1;let n=ty(e,r);return n!==null&&n===ty(t,r)},R5=(e,t)=>e.kind===t.kind&&e.itemId===t.itemId&&e.canonicalItemId===t.canonicalItemId&&e.contentKind===t.contentKind&&e.regionPolicy===t.regionPolicy&&e.scopeElement===t.scopeElement&&x5(e.item,t.item,e.kind),P5=(e,t)=>e.scopeElement===t.scopeElement&&e.ttsHighlightTargetResolver===t.ttsHighlightTargetResolver,ph=(e,t,r)=>{e.getAttribute(t)!==r&&e.setAttribute(t,r)};function _5(){let e=E5(),t=Date.now(),r=null,n=null,i=null,o=null,s=null,a=null,l=[],c=null,u=()=>{s!==null&&e.sync(a,s)};function d(m,v){if(m==="pie-content-loaded"&&(c=v),r&&s!==null){Wd(Cx(r,s),m,{...v,runtimeId:s.runtimeId});return}l.push({type:m,detail:v}),l.length>C5&&l.shift()}function f(m){if(m.runtimeId===s?.runtimeId)return;let v=s!==null;s={runtimeId:m.runtimeId,eventTarget:m.eventTarget},u();let b=l;l=[];for(let I of b)d(I.type,I.detail);v&&c&&d(Xb,c)}function h(){for(let m of[n,i])m?.provider.disconnect();o?.(),o=null,s=null,l=[],c=null,a=null,n=null,i=null,r=null}function g(m){if(!m){e.sync(null),h();return}m.host!==r&&h(),r=m.host;let v=m.canonicalItemId||m.itemId,b=m.regionPolicy||"default",I=m.scopeElement||m.host,C={kind:m.kind,itemId:m.itemId,canonicalItemId:v,contentKind:m.contentKind,regionPolicy:b,scopeElement:I,item:m.item??null,contextVersion:t};n?H1(n,C,R5):n=F1(r,ax,C);let x={scopeElement:I,ttsHighlightTargetResolver:m.ttsHighlightTargetResolver??null};i?H1(i,x,P5):i=F1(r,$L,x),ph(r,"data-item-id",m.itemId),ph(r,"data-canonical-item-id",v),ph(r,"data-pie-shell-root",m.kind),ph(r,"data-region-policy",b);let $=a;a=m.itemId?{kind:m.kind,host:r,itemId:m.itemId,canonicalItemId:v,contentKind:m.contentKind,item:m.item??null,settings:m.settings??null}:null,$&&($.itemId!==a?.itemId||$.canonicalItemId!==a?.canonicalItemId)&&(c=null),o??(o=y0(r,f)),u()}return{publish:g,retire:e.retire,disconnect:h,send:d}}var A5=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},$5=xi('<div class="pie-item-scope-anchor svelte-980v5l" aria-hidden="true"></div> <!>',1),M5={hash:"svelte-980v5l",code:".pie-item-scope-anchor.svelte-980v5l {display:none;}"};function O5(e,t){Ef(t,!0),m0(e,M5);let r=dt(t,"itemId",7,""),n=dt(t,"canonicalItemId",7,""),i=dt(t,"contentKind",7,"assessment-item"),o=dt(t,"regionPolicy",7,"default"),s=dt(t,"scopeElement",7,null),a=dt(t,"ttsHighlightTargetResolver",7,null),l=dt(t,"item",7,null),c=dt(t,"settings",7,null),u=Lr(null),d=Xe(()=>{let b=y(u)?.getRootNode();return b instanceof ShadowRoot?b.host:null}),f=_5();Ot(()=>{if(!y(d))return;let b=y(d),I=!1,C=!1,x=y0(b,L=>{C=!0,I=L.sectionBound===!0}),$=setTimeout(()=>{C||!b.isConnected||Vd(b.ownerDocument,"itemScopeWithoutToolkit",`[pie-item-scope] No <pie-assessment-toolkit> has answered item "${r()}" after ${du/1e3} s, so the item is not registered and the tools inside the scope have no runtime. Place the scope inside the toolkit element; it keeps waiting for one. Reported once per page.`)},du),P=k5({host:b,kind:"item",identity:()=>({itemId:r(),canonicalItemId:n(),contentKind:i()}),mode:()=>I?"section":"plain",send:f.send});return()=>{clearTimeout($);try{P.disconnect()}finally{x(),f.retire(),f.disconnect()}}}),Ot(()=>{f.publish(y(d)?{host:y(d),kind:"item",itemId:r(),canonicalItemId:n(),contentKind:i(),regionPolicy:o(),scopeElement:s(),ttsHighlightTargetResolver:a(),item:l(),settings:c()}:null)});var h={get itemId(){return r()},set itemId(b){r(b),ct()},get canonicalItemId(){return n()},set canonicalItemId(b){n(b),ct()},get contentKind(){return i()},set contentKind(b){i(b),ct()},get regionPolicy(){return o()},set regionPolicy(b){o(b),ct()},get scopeElement(){return s()},set scopeElement(b){s(b),ct()},get ttsHighlightTargetResolver(){return a()},set ttsHighlightTargetResolver(b){a(b),ct()},get item(){return l()},set item(b){l(b),ct()},get settings(){return c()},set settings(b){c(b),ct()}},g=$5(),m=oi(g);g0(m,b=>Ut(u,b),()=>y(u));var v=Ll(m,2);return nx(v,t,"default",{},null),Zt(e,g),Cf(h)}A5("pie-item-scope",zm(O5,{itemId:{attribute:"item-id",type:"String"},canonicalItemId:{attribute:"canonical-item-id",type:"String"},contentKind:{attribute:"content-kind",type:"String"},regionPolicy:{attribute:"region-policy",type:"String"},scopeElement:{type:"Object"},ttsHighlightTargetResolver:{type:"Object"},item:{type:"Object"},settings:{type:"Object"}},["default"],[],{mode:"open"}));var L5=new Set(["assessment","section","item","passage","rubric"]);function xx(e){return L5.has(e)}function N5(e,t,r){let n=e.trim(),i=r.trim();if(!n||!i)throw Error("Tool instance ids require non-empty tool and scope ids");if(!xx(t))throw Error(`Unknown tool scope level '${t}'. Register custom levels with registerToolScopeLevel().`);return`${n}:${t}:${i}`}function D5(e){let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return!r||!i||!xx(n)?null:{baseToolId:r,scopeLevel:n,scopeId:i}}function j5(e){return(...t)=>{console.debug(`[${e}]`,...t)}}var Gu=j5("ToolCoordinator"),Kp;(function(e){e[e.BASE=0]="BASE",e[e.TOOL=1e3]="TOOL",e[e.MODAL=2e3]="MODAL",e[e.CONTROL=3e3]="CONTROL",e[e.HIGHLIGHT=4e3]="HIGHLIGHT"})(Kp||(Kp={}));function U1(e,t){return t?.baseId?(D5(e)?.baseToolId??e)===t.baseId:!0}function q1(e){return{id:e.id,name:e.name,isVisible:e.isVisible,element:e.element,layer:e.layer}}var z5=class{constructor(){T(this,"tools",new Map),T(this,"listeners",new Set)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){for(let e of this.listeners)try{e()}catch(t){console.warn("[ToolCoordinator] listener failed:",t)}}registerTool(e,t,r,n){Gu("registerTool called:",{id:e,name:t,hasElement:!!r,layer:n});let i=this.tools.get(e);if(i){i.name=t;let o=i.registered;i.registered=!0,n!==void 0&&!i.layerDeclared?(i.layer=n,i.layerDeclared=!0,this.stackOnTop(i)):o||this.stackOnTop(i)}else i={id:e,name:t,registered:!0,element:null,layer:n??Kp.TOOL,layerDeclared:n!==void 0,isVisible:!1,baseZIndex:0},this.tools.set(e,i),this.stackOnTop(i);r&&this.updateToolElement(e,r)}unregisterTool(e){let t=this.tools.get(e);t?.registered&&(this.detachElement(t),t.registered=!1)}releaseTool(e){let t=this.tools.get(e);t&&(this.detachElement(t),this.tools.delete(e),t.isVisible&&this.notifyListeners())}showTool(e){let t=this.tools.get(e);if(!t){Gu(`Tool ${e} not found`);return}t.element&&this.bringToFront(t.element),this.setVisible(t,!0)}hideTool(e){let t=this.tools.get(e);if(!t){Gu(`Tool ${e} not found`);return}this.setVisible(t,!1)}toggleTool(e){let t=this.tools.get(e);if(!t){Gu(`Tool ${e} not found`);return}t.isVisible?this.hideTool(e):this.showTool(e)}isToolVisible(e){return this.tools.get(e)?.isVisible??!1}bringToFront(e){let t=Array.from(this.tools.values()).find(r=>r.element===e);t&&this.stackOnTop(t)}getRegisteredTools(){return Array.from(this.tools.values()).filter(e=>e.registered).map(e=>e.id)}getToolElement(e){return this.tools.get(e)?.element??null}setVisible(e,t){e.isVisible!==t&&(e.isVisible=t,this.notifyListeners())}detachElement(e){e.element&&e.mouseDownHandler&&e.element.removeEventListener("mousedown",e.mouseDownHandler),e.element=null,e.mouseDownHandler=void 0}stackOnTop(e){let t=Array.from(this.tools.values()).filter(n=>n.registered&&n.layer===e.layer&&n!==e).sort((n,i)=>n.baseZIndex-i.baseZIndex),r=e.layer+t.length+1;e.baseZIndex===r&&t.every(n=>n.baseZIndex<r)||[...t,e].forEach((n,i)=>{n.baseZIndex=e.layer+1+i,n.element&&(n.element.style.zIndex=String(n.baseZIndex))})}updateToolElement(e,t){let r=this.tools.get(e);if(!r?.registered){Gu(`Tool ${e} not found`);return}if(r.element===t||r.element?.isConnected&&r.element.contains(t))return;this.detachElement(r);let n=()=>this.bringToFront(t);t.addEventListener("mousedown",n),r.element=t,r.mouseDownHandler=n,t.style.zIndex=String(r.baseZIndex),r.isVisible&&this.bringToFront(t)}hideAllTools(e){let t=!1;for(let r of this.tools.values())!r.isVisible||!U1(r.id,e)||(r.isVisible=!1,t=!0);t&&this.notifyListeners()}getToolState(e){let t=this.tools.get(e);return t?.registered?q1(t):void 0}getVisibleTools(e){return Array.from(this.tools.values()).filter(t=>t.isVisible&&U1(t.id,e)).map(q1)}},B5=(e,t)=>{let r=t?.toolTagMap?.[e];if(r===void 0&&!e.includes("-"))throw Error(`No element tag is mapped for tool "${e}". Install a tag map on the registry via setComponentOverrides({ toolTagMap }) — for the packaged capabilities, PACKAGED_TOOL_TAG_MAP from "@pie-players/pie-default-tool-loaders".`);return bm(r??e,`tool component tag for "${e}"`)},F5=["assessment","section","item","passage","rubric","element"];function Jh(e,t){if(typeof e!="string"||e.trim().length===0)throw Error(`Invalid tool registration: "${t}" must be a non-empty string.`)}var H5=[{pattern:/<script\b/i,reason:"contains a <script> tag"},{pattern:/\son[a-z]+\s*=/i,reason:"contains an inline event handler (on*=) attribute"},{pattern:/javascript:/i,reason:"contains a javascript: URL"},{pattern:/<foreignObject\b/i,reason:"contains a <foreignObject> element"}];function U5(e,t,r){let n=t.trimStart(),i=n.toLowerCase().startsWith("<svg"),o=/^https?:/i.test(n);if(/^data:/i.test(n))throw Error(`Invalid tool registration "${e}": "${r}" may not be a data: URL.`);if(!(!i&&!o)){for(let{pattern:s,reason:a}of H5)if(s.test(t))throw Error(`Invalid tool registration "${e}": "${r}" ${a}. Inline SVG icons must not include scriptable content.`)}}function W1(e){Jh(e.toolId,"toolId"),Jh(e.name,"name"),Jh(e.description,"description");let t=e.activation==="region";if((!t||e.icon!==void 0)&&typeof e.icon!="string"&&typeof e.icon!="function")throw Error(`Invalid tool registration "${e.toolId}": "icon" must be a string or function.`);if(typeof e.icon=="string"&&U5(e.toolId,e.icon,"icon"),!Array.isArray(e.supportedLevels)||e.supportedLevels.length===0)throw Error(`Invalid tool registration "${e.toolId}": "supportedLevels" must be a non-empty array.`);let r=e.supportedLevels.find(n=>!F5.includes(n));if(r)throw Error(`Invalid tool registration "${e.toolId}": unsupported level "${r}".`);if(e.activation!==void 0&&e.activation!=="toolbar-toggle"&&e.activation!=="selection-gateway"&&e.activation!=="region")throw Error(`Invalid tool registration "${e.toolId}": unsupported activation "${String(e.activation)}".`);if(e.surfaces!==void 0&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>typeof n!="string"||n.trim().length===0)))throw Error(`Invalid tool registration "${e.toolId}": "surfaces" must be an array of non-empty strings.`);if(t&&!e.surfaces?.length)throw Error(`Invalid tool registration "${e.toolId}": region tools must declare at least one host surface in "surfaces".`);if(t&&typeof e.renderSurface!="function")throw Error(`Invalid tool registration "${e.toolId}": region tools must implement "renderSurface".`);if(e.resolvesWithoutGrant!==void 0&&typeof e.resolvesWithoutGrant!="boolean")throw Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" must be a boolean.`);if(e.resolvesWithoutGrant&&!e.requiresAuthoredContent)throw Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" requires "requiresAuthoredContent".`);if(e.renderSurface!==void 0&&typeof e.renderSurface!="function")throw Error(`Invalid tool registration "${e.toolId}": "renderSurface" must be a function.`);if(e.renderSurface&&!e.surfaces?.length)throw Error(`Invalid tool registration "${e.toolId}": "renderSurface" requires at least one entry in "surfaces".`);if(e.singletonScope!==void 0&&e.singletonScope!=="section")throw Error(`Invalid tool registration "${e.toolId}": unsupported singletonScope "${String(e.singletonScope)}".`);if(e.activation==="selection-gateway"&&e.singletonScope!=="section")throw Error(`Invalid tool registration "${e.toolId}": selection-gateway tools must declare singletonScope "section".`);if(e.activation!=="region"&&typeof e.isVisibleInContext!="function")throw Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function.`);if(e.isVisibleInContext!==void 0&&typeof e.isVisibleInContext!="function")throw Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function when present.`);if(e.isApplicableToContent!==void 0&&typeof e.isApplicableToContent!="function")throw Error(`Invalid tool registration "${e.toolId}": "isApplicableToContent" must be a function when present.`);if(e.requiresAuthoredContent!==void 0&&(typeof e.requiresAuthoredContent!="object"||e.requiresAuthoredContent===null||typeof e.requiresAuthoredContent.resolve!="function"))throw Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" must be an object with a "resolve" function.`);if(e.renderToolbar!==void 0){if(typeof e.renderToolbar!="function")throw Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}else if(!t)throw Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}var Iy=class{constructor(){T(this,"tools",new Map),T(this,"componentOverrides",{}),T(this,"watchedUndefinedToolElements",new Set),T(this,"moduleLoaders",new Map),T(this,"loadedToolModules",new Set),T(this,"warnedLoaderReplacements",new Set),T(this,"warnedUnregisteredAllowedTools",new Set),T(this,"moduleLoadPromises",new Map),T(this,"changeListeners",new Set)}emitChange(e){for(let t of this.changeListeners)try{t(e)}catch(r){console.warn("[ToolRegistry] change listener failed:",r)}}onRegistryChange(e){this.changeListeners.add(e);let t=!0;return()=>{t&&(t=!1,this.changeListeners.delete(e))}}normalizeToolId(e){return e.trim()}normalizeToolIds(e){return e.map(t=>this.normalizeToolId(t))}register(e){if(W1(e),this.tools.has(e.toolId))throw Error(`Tool '${e.toolId}' is already registered`);this.tools.set(e.toolId,e),this.emitChange({kind:"register",toolIds:[e.toolId]})}override(e){if(W1(e),!this.tools.has(e.toolId))throw Error(`Cannot override non-existent tool '${e.toolId}'`);this.tools.set(e.toolId,e),this.emitChange({kind:"override",toolIds:[e.toolId]})}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.emitChange({kind:"unregister",toolIds:[e]}))}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getAllToolIds(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}getToolsByLevel(e){return this.getAllTools().filter(t=>t.supportedLevels.includes(e))}getToolActivation(e){return this.get(e)?.activation||"toolbar-toggle"}getToolSingletonScope(e){return this.get(e)?.singletonScope||null}getToolsBySurface(e){return e?this.getAllTools().filter(t=>typeof t.renderSurface=="function"&&t.surfaces?.includes(e)):[]}getContentDependentSupportIds(){return this.getAllTools().filter(e=>e.requiresAuthoredContent).map(e=>e.toolId).sort()}filterToolIdsByActivation(e,t){return e.filter(r=>this.getToolActivation(r)===t)}filterVisibleInContext(e,t){let r=[];for(let n of e){let i=this.get(n);if(!i){this.warnedUnregisteredAllowedTools.has(n)||(this.warnedUnregisteredAllowedTools.add(n),console.warn(`Tool '${n}' is allowed but not registered`));continue}if(i.supportedLevels.includes(t.level))try{i.isVisibleInContext?.(t)&&r.push(i)}catch(o){console.error(`Error evaluating visibility for tool '${n}':`,o)}}return r}isApplicableToAnyContext(e,t){let r=this.get(e);return!r?.isApplicableToContent||t.length===0?!0:t.some(n=>{try{return r.isApplicableToContent?.(n)??!0}catch(i){return console.error(`Error evaluating applicability for tool '${e}':`,i),!0}})}getToolMetadata(){return this.getAllTools().map(e=>({toolId:e.toolId,name:e.name,description:e.description,supportedLevels:e.supportedLevels,activation:e.activation||"toolbar-toggle",singletonScope:e.singletonScope||null,surfaces:e.surfaces||[],requiresAuthoredContent:!!e.requiresAuthoredContent,contentDependencyDescription:e.requiresAuthoredContent?.description??null}))}clear(){let e=this.getAllToolIds();e.length!==0&&(this.tools.clear(),this.emitChange({kind:"clear",toolIds:e}))}setComponentOverrides(e){this.componentOverrides!==e&&(this.componentOverrides=e,this.emitChange({kind:"component-overrides",toolIds:[]}))}setToolModuleLoaders(e){let t=Object.entries(e).filter(n=>n[1]!==void 0);for(let[n,i]of t)if(Jh(n,"tool module loader id"),typeof i!="function")throw Error(`Invalid tool module loader for "${n}": expected a function.`);let r=[];for(let[n,i]of t)if(this.moduleLoaders.get(n)!==i){if(this.loadedToolModules.has(n)||this.moduleLoadPromises.has(n)){this.warnLoaderReplacedAfterLoad(n);continue}this.moduleLoaders.set(n,i),r.push(n)}r.length>0&&this.emitChange({kind:"module-loaders",toolIds:r})}warnLoaderReplacedAfterLoad(e){this.warnedLoaderReplacements.has(e)||(this.warnedLoaderReplacements.add(e),console.warn(`[ToolRegistry] Ignored a new module loader for "${e}": its module already loaded, so the elements it defines stay in place. Register loaders before the tool first renders.`))}async ensureToolModuleLoaded(e){if(this.loadedToolModules.has(e))return;let t=this.moduleLoadPromises.get(e);if(t){await t;return}let r=this.moduleLoaders.get(e);if(!r){this.watchUndefinedToolElement(e);return}let n=(async()=>{await r(),this.loadedToolModules.add(e),this.warnIfLoadedToolElementUndefined(e)})();this.moduleLoadPromises.set(e,n);try{await n}finally{this.moduleLoadPromises.delete(e)}}undefinedToolElementTag(e){if(typeof customElements>"u"||typeof document>"u")return null;let t=this.componentOverrides;if(t.toolComponentFactories?.[e])return null;let r;try{r=B5(e,t)}catch{return null}return customElements.get(r)?null:r}warnIfLoadedToolElementUndefined(e){let t=this.undefinedToolElementTag(e);t&&Vd(document,`loadedToolElementUndefined.${e}.${t}`,`[ToolRegistry] Tool "${e}" renders <${t}>, but its module loader finished without defining it, so the tool renders blank. The tag map and the loader disagree: map "${e}" to the tag its loader defines, or register a loader that defines <${t}>. Reported once per page.`)}watchUndefinedToolElement(e){if(this.watchedUndefinedToolElements.has(e))return;let t=this.undefinedToolElementTag(e);if(!t)return;this.watchedUndefinedToolElements.add(e);let r=document,n=setTimeout(()=>{customElements.get(t)||Vd(r,`undefinedToolElement.${e}`,`[ToolRegistry] Tool "${e}" renders <${t}>, which is still undefined after ${du/1e3} s, and its registry has no module loader for it. Pass toolModuleLoaders to createPackagedToolRegistry (DEFAULT_TOOL_MODULE_LOADERS from @pie-players/pie-default-tool-loaders loads the stock tools), register one with setToolModuleLoaders, or import the tool's package before it renders. Reported once per page.`)},du);customElements.whenDefined(t).then(()=>clearTimeout(n))}async ensureToolModulesLoaded(e){let t=await Promise.allSettled(e.map(n=>this.ensureToolModuleLoaded(n))),r=new Map;return t.forEach((n,i)=>{n.status==="rejected"&&r.set(e[i],n.reason)}),r}isToolModuleLoaded(e){return this.loadedToolModules.has(e)}renderForToolbar(e,t,r){let n=this.get(e);if(!n)throw Error(`Tool '${e}' is not registered`);if(typeof n.renderToolbar!="function")throw Error(`Tool '${e}' has activation "${n.activation||"toolbar-toggle"}" and renders into a host surface, not a toolbar. Remove it from toolbar placement.`);let i={...r,componentOverrides:{...this.componentOverrides||{},...r.componentOverrides||{}}};return n.renderToolbar(t,i)}renderForSurface(e,t){let r=this.get(e);if(!r)throw Error(`Tool '${e}' is not registered`);if(typeof r.renderSurface!="function")throw Error(`Tool '${e}' does not render into a host surface. Surface capabilities declare "surfaces" and implement "renderSurface".`);return r.renderSurface({...t,componentOverrides:{...this.componentOverrides||{},...t.componentOverrides||{}}})}},jg={assessment:[],section:[],item:[],passage:[],rubric:[],element:[]},zg={section:[...jg.section],item:[...jg.item],passage:[...jg.passage]};function Dl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function va(e,t){if(e==null)return[];if(!Array.isArray(e))throw Error(`Invalid tools config at "${t}": expected an array of tool ids.`);if(e.find(r=>typeof r!="string")!==void 0)throw Error(`Invalid tools config at "${t}": all entries must be strings.`);return e}function q5(e){if(e!=null){if(!Dl(e))throw Error('Invalid tools config at "placement": expected an object with section/item/passage arrays.');return e}}function W5(e){if(e!=null){if(!Dl(e))throw Error('Invalid tools config at "policy": expected an object with allowed/blocked arrays.');return e}}function V5(e,t){if(t==null)return;if(!Dl(t))throw Error(`Invalid tools config at "providers.${e}": expected an object.`);let r=t;if("enabled"in r&&r.enabled!==void 0&&typeof r.enabled!="boolean")throw Error(`Invalid tools config at "providers.${e}.enabled": expected a boolean.`);if("settings"in r&&r.settings!==void 0&&!Dl(r.settings))throw Error(`Invalid tools config at "providers.${e}.settings": expected an object.`);if("provider"in r&&r.provider!==void 0&&!Dl(r.provider))throw Error(`Invalid tools config at "providers.${e}.provider": expected an object.`);return r}function G5(e){if(e==null)return{};if(!Dl(e))throw Error('Invalid tools config at "providers": expected an object keyed by tool id.');let t={};for(let[r,n]of Object.entries(e))t[r]=V5(r,n);return t}function gi(e){if(!e||e.length===0)return[];let t=new Set;for(let r of e){if(typeof r!="string")throw Error("Invalid tools config: tool list entries must be strings.");let n=r.trim();n&&t.add(n)}return Array.from(t)}function Rx(e){return e?gi(e.split(",").map(t=>t.trim()).filter(Boolean)):[]}function Y5(e,t){if(e!=null){if(e==="on"||e==="off")return e;throw Error(`Invalid tools config at "${t}": expected "on" or "off", got ${JSON.stringify(e)}.`)}}function C0(e){if(e!=null&&!Dl(e))throw Error('Invalid tools config: expected an object with "policy", "placement", and "providers".');let t=W5(e?.policy),r=q5(e?.placement),n=G5(e?.providers),i=Y5(e?.pnpEnforcement,"pnpEnforcement"),o={policy:{allowed:gi(va(t?.allowed,"policy.allowed")),blocked:gi(va(t?.blocked,"policy.blocked"))},placement:{section:gi(va(r?.section,"placement.section")).length?gi(va(r?.section,"placement.section")):[...zg.section],item:gi(va(r?.item,"placement.item")).length?gi(va(r?.item,"placement.item")):[...zg.item],passage:gi(va(r?.passage,"placement.passage")).length?gi(va(r?.passage,"placement.passage")):[...zg.passage]},providers:n};return i&&(o.pnpEnforcement=i),o}function V1(e){return typeof e.href=="string"}function K5(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.id!="string"||t.id.trim().length===0||typeof t.label!="string"||t.label.trim().length===0||t.ariaLabel!==void 0&&typeof t.ariaLabel!="string"||t.icon!==void 0&&typeof t.icon!="string"||t.tooltip!==void 0&&typeof t.tooltip!="string"||t.active!==void 0&&typeof t.active!="boolean"||t.disabled!==void 0&&typeof t.disabled!="boolean")return!1;let r=typeof t.href=="string",n=typeof t.onClick=="function";return r===n?!1:r?!0:n}function G1(e){return typeof e=="string"&&e.trimStart().startsWith("<svg")}function Y1(e){return typeof e=="string"&&e.trimStart().startsWith("http")}var X5={calculator:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm0 2v4h10V4H7Zm0 6v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Z" fill="currentColor"/></svg>',"volume-up":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 3.23v2.06A7.002 7.002 0 0 1 19 12a7 7 0 0 1-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77Zm-2 17.75V3L7 8H3v8h4l5 5Zm4.5-9a4.5 4.5 0 0 0-2.5-4.03v8.05A4.5 4.5 0 0 0 16.5 12Z" fill="currentColor"/></svg>',swatch:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 3a9 9 0 1 0 9 9c0-.55-.45-1-1-1h-2.5a1.5 1.5 0 0 1 0-3H20a1 1 0 0 0 1-1 8.99 8.99 0 0 0-9-4Zm-5.5 9A1.5 1.5 0 1 1 8 13.5 1.5 1.5 0 0 1 6.5 12Zm3-4A1.5 1.5 0 1 1 11 9.5 1.5 1.5 0 0 1 9.5 8Zm5 0A1.5 1.5 0 1 1 16 9.5 1.5 1.5 0 0 1 14.5 8Z" fill="currentColor"/></svg>',"chart-bar":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4.75 5a.76.76 0 0 1 .75.75v11c0 .438.313.75.75.75h13a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-13C5 19 4 18 4 16.75v-11A.74.74 0 0 1 4.75 5ZM8 8.25a.74.74 0 0 1 .75-.75h6.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-6.5A.722.722 0 0 1 8 8.25Zm.75 2.25h4.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-4.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Zm0 3h8.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-8.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Z" fill="currentColor"/></svg>',beaker:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 21c-.85 0-1.454-.38-1.813-1.137-.358-.759-.27-1.463.263-2.113L9 11V5H8a.968.968 0 0 1-.713-.287A.968.968 0 0 1 7 4c0-.283.096-.52.287-.712A.968.968 0 0 1 8 3h8c.283 0 .52.096.712.288.192.191.288.429.288.712s-.096.52-.288.713A.968.968 0 0 1 16 5h-1v6l5.55 6.75c.533.65.62 1.354.262 2.113C20.454 20.62 19.85 21 19 21H5Zm2-3h10l-3.4-4h-3.2L7 18Zm-2 1h14l-6-7.3V5h-2v6.7L5 19Z" fill="currentColor"/></svg>',protractor:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m6.75 21-.25-2.2 2.85-7.85a3.95 3.95 0 0 0 1.75.95l-2.75 7.55L6.75 21Zm10.5 0-1.6-1.55-2.75-7.55a3.948 3.948 0 0 0 1.75-.95l2.85 7.85-.25 2.2ZM12 11a2.893 2.893 0 0 1-2.125-.875A2.893 2.893 0 0 1 9 8c0-.65.188-1.23.563-1.737A2.935 2.935 0 0 1 11 5.2V3h2v2.2c.583.2 1.063.554 1.438 1.063C14.812 6.77 15 7.35 15 8c0 .833-.292 1.542-.875 2.125A2.893 2.893 0 0 1 12 11Zm0-2c.283 0 .52-.096.713-.287A.967.967 0 0 0 13 8a.967.967 0 0 0-.287-.713A.968.968 0 0 0 12 7a.968.968 0 0 0-.713.287A.967.967 0 0 0 11 8c0 .283.096.52.287.713.192.191.43.287.713.287Z" fill="currentColor"/></svg>',"bars-3":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.85 15c.517 0 .98-.15 1.388-.45.408-.3.695-.692.862-1.175l.375-1.15c.267-.8.2-1.537-.2-2.213C8.875 9.337 8.3 9 7.55 9H4.025l.475 3.925c.083.583.346 1.075.787 1.475.442.4.963.6 1.563.6Zm10.3 0c.6 0 1.12-.2 1.563-.6.441-.4.704-.892.787-1.475L19.975 9h-3.5c-.75 0-1.325.342-1.725 1.025-.4.683-.467 1.425-.2 2.225l.35 1.125c.167.483.454.875.862 1.175.409.3.871.45 1.388.45Zm-10.3 2c-1.1 0-2.063-.363-2.887-1.088a4.198 4.198 0 0 1-1.438-2.737L2 9H1V7h6.55c.733 0 1.404.18 2.013.537A3.906 3.906 0 0 1 11 9h2.025c.35-.617.83-1.104 1.438-1.463A3.892 3.892 0 0 1 16.474 7H23v2h-1l-.525 4.175a4.198 4.198 0 0 1-1.438 2.737A4.238 4.238 0 0 1 17.15 17c-.95 0-1.804-.27-2.562-.813A4.234 4.234 0 0 1 13 14.026l-.375-1.125a21.35 21.35 0 0 1-.1-.363 4.926 4.926 0 0 1-.1-.537h-.85c-.033.2-.067.363-.1.488a21.35 21.35 0 0 1-.1.362L11 14a4.3 4.3 0 0 1-1.588 2.175A4.258 4.258 0 0 1 6.85 17Z" fill="currentColor"/></svg>',ruler:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m8.8 10.95 2.15-2.175-1.4-1.425-1.1 1.1-1.4-1.4 1.075-1.1L7 4.825 4.825 7 8.8 10.95Zm8.2 8.225L19.175 17l-1.125-1.125-1.1 1.075-1.4-1.4 1.075-1.1-1.425-1.4-2.15 2.15L17 19.175ZM7.25 21H3v-4.25l4.375-4.375L2 7l5-5 5.4 5.4 3.775-3.8c.2-.2.425-.35.675-.45a2.068 2.068 0 0 1 1.55 0c.25.1.475.25.675.45L20.4 4.95c.2.2.35.425.45.675.1.25.15.508.15.775a1.975 1.975 0 0 1-.6 1.425l-3.775 3.8L22 17l-5 5-5.375-5.375L7.25 21ZM5 19h1.4l9.8-9.775L14.775 7.8 5 17.6V19Z" fill="currentColor"/></svg>',"book-open":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 6.25a6.6 6.6 0 0 0-2.3-1.32A8.6 8.6 0 0 0 7 4.5c-.63 0-1.25.06-1.85.18-.6.12-1.19.3-1.76.54a1.5 1.5 0 0 0-.93 1.4v10.1c0 .52.26.98.68 1.24.42.26.92.28 1.35.06.36-.18.75-.31 1.18-.4.42-.09.86-.13 1.33-.13.78 0 1.53.14 2.24.42.7.28 1.35.7 1.93 1.24l.83-.75.83.75c.58-.54 1.22-.96 1.93-1.24a6.1 6.1 0 0 1 2.24-.42c.47 0 .91.04 1.33.13.43.09.82.22 1.18.4.43.22.93.2 1.35-.06.42-.26.68-.72.68-1.24V6.62c0-.6-.36-1.15-.93-1.4a9.3 9.3 0 0 0-1.76-.54A9.8 9.8 0 0 0 17 4.5a8.6 8.6 0 0 0-2.7.43A6.6 6.6 0 0 0 12 6.25Zm1 10.06V8.02c.55-.5 1.16-.88 1.84-1.13A6 6 0 0 1 17 6.5c.45 0 .89.04 1.32.11.43.08.85.19 1.26.34v9.24a8.2 8.2 0 0 0-1.28-.24A10 10 0 0 0 17 15.85c-.72 0-1.42.09-2.09.26a7.7 7.7 0 0 0-1.91.8Zm-2 0a7.7 7.7 0 0 0-1.91-.8 8.4 8.4 0 0 0-2.09-.26c-.44 0-.87.02-1.3.07-.43.05-.86.13-1.28.24V6.95c.41-.15.83-.26 1.26-.34A7.7 7.7 0 0 1 7 6.5c.76 0 1.48.13 2.16.39.68.25 1.29.63 1.84 1.13Z" fill="currentColor"/></svg>',photo:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 21c-.55 0-1.02-.2-1.41-.59A1.93 1.93 0 0 1 2 19V5c0-.55.2-1.02.59-1.41A1.93 1.93 0 0 1 4 3h16c.55 0 1.02.2 1.41.59.39.39.59.86.59 1.41v14c0 .55-.2 1.02-.59 1.41-.39.39-.86.59-1.41.59H4Zm0-2h16V5H4v14Zm1.5-2.5h13l-4.1-5.47-3.4 4.47-2.5-3.25L5.5 16.5ZM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z" fill="currentColor"/></svg>'};function J5(e){return X5[e]||null}function Q5(){let e=null;return(t,r)=>{if(!t)return e=null,null;let n=t.visibleTools.map(i=>({toolId:i.toolId,required:i.required,alwaysAvailable:i.alwaysAvailable}));return e?.renderVersion===r&&fu(e.tools,n)?e.tools:(e={renderVersion:r,tools:n},n)}}var Z5=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},mh=xi('<span class="item-toolbar__element-host svelte-1c13522"></span>'),eD=xi('<span class="item-toolbar__nds-button-zoom svelte-1c13522"><nds-icon-button></nds-icon-button></span>',2),gh=xi('<span aria-hidden="true"></span>'),K1=xi('<img class="item-toolbar__icon-image svelte-1c13522" alt=""/>'),X1=xi('<i aria-hidden="true"></i>'),tD=xi("<a><!></a>"),rD=xi('<button type="button"><!></button>'),J1=xi('<span class="item-toolbar__controls-host svelte-1c13522"></span>'),nD=xi("<div></div>"),iD=xi('<div><div class="item-toolbar__tools-row svelte-1c13522"><!> <!> <!></div> <!></div>'),oD={hash:"svelte-1c13522",code:`.item-toolbar.svelte-1c13522 {display:flex;flex-direction:column;align-items:flex-end;min-width:0;max-width:100%;gap:0;--pie-toolbar-tools-row-height: 2rem;--pie-tts-controls-row-height: 2.875rem;}.item-toolbar__tools-row.svelte-1c13522 {display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:0.5rem;max-width:100%;min-height:var(--pie-toolbar-tools-row-height);}
6
+
7
+ /* A granted section tool must stay reachable even when there isn't room for
8
+ every button: scroll the row rather than clipping items past the edge,
9
+ which left them impossible to focus, tab to, or click. \`min-width: 0\`
10
+ beats the flex default (\`auto\`, i.e. never shrink below content), which
11
+ would otherwise keep the row at full content width and make overflow-x
12
+ moot. Item and passage rows wrap without an overflow clip so an inline
13
+ reading-controls panel can still extend outside the row. */.item-toolbar[data-level="section"].svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522) {flex-wrap:nowrap;justify-content:flex-start;
14
+ /* Keep the focus outline inside the scrolling box on both axes. */padding:4px;scroll-padding:4px;box-sizing:border-box;overflow-x:auto;max-width:100%;min-width:0;}.item-toolbar__controls-row.svelte-1c13522 {display:flex;align-items:center;justify-content:flex-end;width:100%;min-height:0;height:auto;}.item-toolbar__controls-row--reserve.svelte-1c13522 {min-height:var(--pie-tts-controls-row-height);height:var(--pie-tts-controls-row-height);}.item-toolbar__controls-row--active.svelte-1c13522 {min-height:var(--pie-tts-controls-row-height);height:var(--pie-tts-controls-row-height);}.item-toolbar__controls-row--align-start.svelte-1c13522 {justify-content:flex-start;}.item-toolbar__controls-host.svelte-1c13522 {display:inline-flex;align-items:center;justify-content:flex-end;width:100%;}.item-toolbar--top.svelte-1c13522,
15
+ .item-toolbar--bottom.svelte-1c13522 {align-items:flex-end;}.item-toolbar--left.svelte-1c13522,
16
+ .item-toolbar--right.svelte-1c13522 {align-items:stretch;}.item-toolbar--left.svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522),
17
+ .item-toolbar--right.svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522) {flex-direction:column;align-items:center;justify-content:flex-start;flex-wrap:nowrap;}.item-toolbar--left.svelte-1c13522 .item-toolbar__controls-row:where(.svelte-1c13522),
18
+ .item-toolbar--right.svelte-1c13522 .item-toolbar__controls-row:where(.svelte-1c13522) {justify-content:flex-start;width:auto;min-height:0;height:auto;}.item-toolbar__button.svelte-1c13522 {display:flex;flex-shrink:0;align-items:center;justify-content:center;width:2rem;height:2rem;padding:0.25rem;border:1px solid var(--pie-button-border, var(--pie-border, #ccc));border-radius:0.25rem;background-color:var(--pie-button-bg, var(--pie-background, white));color:var(--pie-button-color, var(--pie-text, #333));cursor:pointer;transition:all 0.15s ease;text-decoration:none;}
19
+
20
+ /* Drive the vendored NDS icon button's outer size via its own \`--height-32\`
21
+ custom property so its light-DOM inner button matches the toolbar's
22
+ md/sm/lg dimensions (32 / 44 / 40 px) without a layout shift. The glyph
23
+ keeps the NDS-native icon size (we render size="small"), so it isn't
24
+ oversized. */.item-toolbar__nds-button-zoom.svelte-1c13522 {display:inline-flex;flex-shrink:0;}.item-toolbar.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {
25
+ /* Host-settable button size per toolbar size (drives the NDS outer button
26
+ via its own --height-32). */--height-32: var(--pie-calculator-button-size, 2rem);
27
+ /* Host-settable accent for the calculator button: the NDS tertiary glyph
28
+ colour derives from --color-interactive-blue, remapped here to a
29
+ themeable variable. --pie-calculator-button-color is package-private, so
30
+ nothing sets it and the default is what ships: it now resolves through
31
+ --pie-button-color (DaisyUI base-content) instead of holding the Figma
32
+ blue on every theme, with the literal as the no-theme last resort.
33
+ Not --pie-primary or --pie-tertiary: both are \`direct\` mappings of
34
+ DaisyUI slots chosen to pair with their own -content colour, so a glyph
35
+ taken from either sits at 1.37:1 against the page under \`pastel\` and 11
36
+ of the 35 shipped themes fall under SC 1.4.11's 3:1. */--color-interactive-blue: var(--pie-calculator-button-color, var(--pie-button-color, var(--pie-text, #222)));
37
+ /* NDS palette bridge — keep in sync with the copies in tool-tts-inline
38
+ and section-player SectionItemsPane (asserted by
39
+ scripts/check-theme-tokens.mjs). The vendored button paints its fill,
40
+ its on-accent glyph, its hover ring and its focus ring from the NDS
41
+ design-system palette, which no PIE theme sets, so a tertiary button
42
+ kept a #f3f5f7 pill on every page — and once the glyph followed the
43
+ theme, a light glyph landed on that light pill. */--color-new-gray: var(--pie-background-dark, #f3f5f7);--color-primary-white: var(--pie-white, #ffffff);--color-primary-black: var(--pie-text, #000000);--color-focus-blue: var(--pie-button-focus-outline, #2b87ff);}.item-toolbar--sm.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {--height-32: var(--pie-calculator-button-size-sm, 2.75rem);}.item-toolbar--lg.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {--height-32: var(--pie-calculator-button-size-lg, 2.5rem);}.item-toolbar__element-host.svelte-1c13522 {display:contents;}.item-toolbar--sm.svelte-1c13522 .item-toolbar__button:where(.svelte-1c13522) {width:2.75rem;height:2.75rem;}.item-toolbar--sm.svelte-1c13522 {--pie-toolbar-tools-row-height: 2.75rem;--pie-tts-controls-row-height: 3.625rem;}.item-toolbar--lg.svelte-1c13522 .item-toolbar__button:where(.svelte-1c13522) {width:2.5rem;height:2.5rem;}.item-toolbar--lg.svelte-1c13522 {--pie-toolbar-tools-row-height: 2.5rem;--pie-tts-controls-row-height: 3.375rem;}.item-toolbar__button.svelte-1c13522:hover:not(:disabled) {background-color:var(--pie-button-hover-bg, var(--pie-secondary-background, #f5f5f5));border-color:var(--pie-button-hover-border, var(--pie-button-border, var(--pie-border, #ccc)));color:var(--pie-button-hover-color, var(--pie-button-color, var(--pie-text, #333)));transform:translateY(-1px);box-shadow:0 2px 4px color-mix(in srgb, var(--pie-black, #000) 10%, transparent);}.item-toolbar__button.svelte-1c13522:active:not(:disabled) {transform:translateY(0);box-shadow:none;}.item-toolbar__button--active.svelte-1c13522 {background-color:var(--pie-primary, #1976d2);color:var(--pie-white, #fff);border-color:var(--pie-primary, #1976d2);}.item-toolbar__button--active.svelte-1c13522:hover:not(:disabled) {background-color:var(--pie-primary-dark, #1565c0);}.item-toolbar__button.svelte-1c13522:focus-visible {outline:2px solid var(--pie-button-focus-outline, var(--pie-primary, #1976d2));outline-offset:2px;}.item-toolbar__button.svelte-1c13522:disabled {opacity:0.5;cursor:not-allowed;}.item-toolbar__button.svelte-1c13522 svg {width:100%;height:100%;}.item-toolbar__icon-image.svelte-1c13522 {width:100%;height:100%;object-fit:contain;}`};function sD(e,t){Ef(t,!0),m0(e,oD);let r=typeof window<"u",n=["/_fa-pro/fontawesome.min.css","/_fa-pro/light.min.css"],i="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.2/css/all.min.css",o="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap",s=/font.?awesome|fa-?pro/i,a=O=>{if(document.querySelector(`link[href="${O}"]`))return;let ee=document.createElement("link");ee.rel="stylesheet",ee.href=O,ee.addEventListener("error",()=>{ee.dataset.pieLoadFailed=""},{once:!0}),document.head.appendChild(ee)},l=!1,c=()=>{if(!(!r||l)&&(l=!0,!document.querySelector('link[href*="Roboto"]')&&a(o),!Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).some(O=>s.test(O.href)))){a(i);for(let O of n)a(O)}},u="__pieFaToolbarShadowInstalled",d=O=>{let ee=O.getRootNode();if(!(ee instanceof ShadowRoot))return;let X=ee;if(X[u])return;X[u]=!0;let he=new Set,gt=Ie=>{if(!Ie||he.has(Ie))return;he.add(Ie);let et=document.createElement("link");et.rel="stylesheet",et.href=Ie,ee.appendChild(et)},kr=Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).filter(Ie=>s.test(Ie.href));for(let Ie of kr){if("pieLoadFailed"in Ie.dataset)continue;if(Ie.sheet){gt(Ie.href);continue}let et=jr=>{Ie.removeEventListener("load",et),Ie.removeEventListener("error",et),jr.type==="load"&&gt(Ie.href)};Ie.addEventListener("load",et),Ie.addEventListener("error",et)}},f=O=>(c(),d(O),{}),h=(O,ee)=>{let X=ee,he=()=>{let kr=O.querySelector("button");kr&&kr.setAttribute("aria-pressed",X?"true":"false")};he();let gt=new MutationObserver(he);return gt.observe(O,{childList:!0,subtree:!0}),{update(kr){X=kr,he()},destroy(){gt.disconnect()}}},g=O=>O.faIconName||null,m=new Iy,v=Lr(Ea({})),b=dt(t,"level",7,"item"),I=dt(t,"scopeId",7,""),C=dt(t,"itemId",7,""),x=dt(t,"sectionId",7,""),$=dt(t,"catalogId",7,""),P=dt(t,"tools",7,""),L=dt(t,"contentKind",7,"assessment-item"),J=dt(t,"position",7,"bottom"),V=dt(t,"scopeElement",7,null),Y=dt(t,"toolRegistry",7,null),Pe=dt(t,"item",7,null),M=dt(t,"hostButtons",23,()=>[]),H=dt(t,"class",7,""),ne=dt(t,"size",7,"md"),ae=dt(t,"language",7,""),ye=Lr(null),te=Lr(null),z=Xe(()=>y(te)?.ndsIcons===!0),A=Xe(()=>Ba(y(te))),K=Xe(()=>ae()||y(te)?.contentLanguage||void 0),Q=Lr(null),_=Lr(0),B=Lr(0),U=Lr(0),fe=Lr(0);Ot(()=>{if(y(ye))return LL(y(ye),O=>{Ut(te,O,!0)})}),Ot(()=>{if(y(ye))return NL(y(ye),O=>{Ut(Q,O,!0)})}),Ot(()=>{let O=y(te)?.toolkitCoordinator;if(!O||typeof O.onPolicyChange!="function")return;let ee=O.onPolicyChange(X=>{Ut(B,y(B)+1),X?.reason!=="item-settings"&&Ut(U,y(U)+1)});return()=>{try{ee?.()}catch{}}}),Ot(()=>{let O=y(te)?.toolkitCoordinator;if(!O||typeof O.onToolContextResolverChange!="function")return;let ee=O.onToolContextResolverChange(()=>{Ut(fe,y(fe)+1)});return()=>{try{ee?.()}catch{}}});let W=Xe(()=>y(te)?.toolCoordinator),se=Xe(()=>y(te)?.ttsService),_e=Xe(()=>y(te)?.elementToolStateStore),Ue=Xe(()=>y(te)?.assessmentId??""),it=Xe(()=>C()||y(Q)?.itemId||""),le=Xe(()=>y(Q)?.canonicalItemId||y(it)),de=Xe(()=>x()||y(te)?.sectionId||""),Ne=Xe(()=>L()||y(Q)?.contentKind||(b()==="section"?"section":"assessment-item")),Ae=Xe(()=>b()&&b()!=="item"?b():y(Ne)==="rubric-block-stimulus"?"passage":"item"),ce=Xe(()=>I()?I():y(Ae)==="section"?y(de)||y(te)?.sectionId||"default-section":y(Ae)==="assessment"?y(te)?.assessmentId||"default-assessment":y(le)||y(it)||"default-item"),ie=Xe(()=>$()||y(ce)),De=Xe(()=>Pe()||y(Q)?.item||null),Je=Xe(()=>Y()?Y():(y(B),y(te)?.toolkitCoordinator?.getToolRegistry?.()||m)),At=Xe(()=>Rx(P())),pt=Xe(()=>y(Je).normalizeToolIds(y(At)).filter(Boolean)),Et=Xe(()=>y(Ae)==="section"?"section":y(Ae)==="passage"||y(Ne)==="rubric-block-stimulus"?"passage":"item"),Re=Xe(()=>{y(B);let O=y(te)?.toolkitCoordinator;return!O||typeof O.decideToolPolicy!="function"?null:O.decideToolPolicy({level:y(Et),scope:{level:y(Ae),scopeId:y(ce),assessmentId:y(te)?.assessmentId,sectionId:y(de)||void 0,itemId:y(it)||void 0,canonicalItemId:y(le)||void 0,contentKind:y(Ne)}})}),Ze=Q5(),Ye=Xe(()=>Ze(y(Re),y(U))),yt=Xe(()=>{let O=ee=>Array.from(new Set(ee));return y(Ye)?O(y(Je).normalizeToolIds(y(Ye).map(ee=>ee.toolId)).filter(Boolean)):O(y(pt))});Ot(()=>{if(!y(Re)||y(yt).length===0||y(Je).getAllTools().length>0)return;let O=y(ye)?.ownerDocument,ee=y(yt).join(", "),X=setTimeout(()=>{Vd(O,"toolbarWithoutRegistry",`[pie-item-toolbar] Policy places ${ee} on this toolbar, but its tool registry is still empty after ${du/1e3} s, so it renders no buttons. Pass a toolRegistry to <pie-assessment-toolkit> or its coordinator; @pie-players/pie-default-tool-loaders builds the stock one. Reported once per page.`)},du);return()=>clearTimeout(X)});let re=Xe(()=>{let O=new Set;if(!y(Ye))return O;for(let ee of y(Ye))if(!(!ee.required&&!ee.alwaysAvailable))for(let X of y(Je).normalizeToolIds([ee.toolId]).filter(Boolean))O.add(X);return O}),Qe=Xe(()=>{if(y(Ae)==="section"||y(Ae)==="assessment")return!0;let O=y(De)?.config;return!!(y(De)&&O&&typeof O=="object")}),lt=Xe(()=>{y(B);let O=y(te)?.toolkitCoordinator;return!O||typeof O.getPolicyInputs!="function"?null:O.getPolicyInputs()}),zt=Xe(()=>y(lt)?.assessment??null),Vt=Xe(()=>({id:y(le)})),ur=Xe(()=>y(Ae)==="section"?{level:"section",assessment:y(zt)||{},section:{}}:y(Ae)==="assessment"?{level:"assessment",assessment:y(zt)||{}}:!y(Qe)||!y(De)?null:y(Ae)==="passage"?{level:"passage",assessment:y(zt)||{},itemRef:y(Vt),passage:y(De)}:{level:"item",assessment:y(zt)||{},itemRef:y(Vt),item:y(De)}),st=Xe(()=>y(ur)?y(ur):{level:"item",assessment:y(zt)||{},itemRef:y(Vt),item:y(De)||{id:y(le),config:{}}}),Rt=Xe(()=>{if(y(Ae)!=="item"&&y(Ae)!=="passage")return[];if(!y(Qe)||!y(De))return[];let O=y(De)?.config?.models;return(Array.isArray(O)?O:O&&typeof O=="object"?Object.values(O):[]).filter(ee=>ee&&typeof ee=="object"&&typeof ee.id=="string").map(ee=>({level:"element",assessment:y(zt)||{},itemRef:y(Vt),item:y(De),elementId:ee.id}))});function bt(O){return N5(O,y(Ae),y(ce))}let ft=null;function me(O,ee){let X=bt(ee);return O.getToolState(X)||(O.registerTool(X,ee),ft?.coordinator!==O&&(ft={coordinator:O,ids:new Set}),ft.ids.add(X)),X}Ot(()=>(y(W),y(Ae),y(ce),()=>{let O=ft;if(ft=null,!!O)for(let ee of O.ids)O.coordinator.releaseTool(ee)}));function Nt(O){return!y(_e)||!y(Ue)||!y(de)||!y(le)?null:y(_e).getGlobalElementId(y(Ue),y(de),y(le),O)}function tr(){return V()?V():y(Q)?.scopeElement||null}function mt(){let O=y(W)||null;return{scope:{level:y(Ae),scopeId:y(ce),assessmentId:y(te)?.assessmentId,sectionId:y(de),itemId:y(it),canonicalItemId:y(le),contentKind:y(Ne)},itemId:y(ce),catalogId:y(ie),language:y(K),i18n:y(A),ui:{size:ne()},getScopeElement:tr,getGlobalElementId:Nt,toolCoordinator:O,toolkitCoordinator:y(te)?.toolkitCoordinator||null,ttsService:y(se)||null,elementToolStateStore:y(_e)||null,toggleTool:ee=>{O&&O.toggleTool(me(O,ee))},isToolVisible:ee=>O?.isToolVisible(bt(ee))??!1,subscribeVisibility:O?ee=>O.subscribe(ee):null}}let vr=Xe(mt),dr=Xe(()=>{y(fe);let O=y(te)?.toolkitCoordinator;if(!O||typeof O.hasToolContextResolver!="function"||typeof O.resolveToolContext!="function")return{};let ee={};for(let X of y(yt)){if(!y(Je).get(X)?.supportedLevels.includes(y(Ae))||!O.hasToolContextResolver(X))continue;let he=O.resolveToolContext({toolId:X,context:y(st),toolbarContext:y(vr)});he&&(ee[X]=he)}return ee}),Ir=Xe(()=>{let O=y(yt).filter(Ie=>{let et=y(Je).get(Ie);return et?et.supportedLevels.includes(y(Ae)):!1}),ee=Object.values(y(dr)),X=new Set(ee.map(Ie=>Ie.toolId)),he=new Set(ee.filter(Ie=>Ie.visible).map(Ie=>Ie.toolId)),gt=O.filter(Ie=>!X.has(Ie));if(y(Ae)==="section")return gt.forEach(Ie=>he.add(Ie)),Array.from(he);if(!y(Qe))return gt.forEach(Ie=>he.add(Ie)),Array.from(he);if(!y(ur)&&y(Rt).length===0)return gt.forEach(Ie=>he.add(Ie)),Array.from(he);gt.filter(Ie=>y(re).has(Ie)).forEach(Ie=>he.add(Ie)),y(ur)&&y(Je).filterVisibleInContext(gt,y(ur)).forEach(Ie=>he.add(Ie.toolId));for(let Ie of y(Rt))y(Je).filterVisibleInContext(gt,Ie).forEach(et=>he.add(et.toolId));let kr=y(ur)?[y(ur),...y(Rt)]:y(Rt);for(let Ie of Array.from(he))X.has(Ie)||y(Je).isApplicableToAnyContext(Ie,kr)||he.delete(Ie);return Array.from(he)}),Qt=Lr(null),Nr=Xe(()=>{let O=y(Qt)?.registry===y(Je)?y(Qt).toolIds:null,ee=y(Je).filterToolIdsByActivation(y(Ir),"toolbar-toggle");return O?ee.filter(X=>!O.has(X)):ee});function on(O,ee){let X=y(te)?.toolkitCoordinator;if(typeof X?.reportToolModuleFailure=="function"){X.reportToolModuleFailure(O,ee);return}console.error(`[ItemToolBar] Tool "${O}" failed to load:`,ee)}Ot(()=>{if(!r)return;let O=y(Je),ee=!1;return O.ensureToolModulesLoaded(y(Nr)).then(X=>{if(X.size>0){let he=y(Qt)?.registry===O?y(Qt).toolIds:[];Ut(Qt,{registry:O,toolIds:new Set([...he,...X.keys()])},!0);for(let[gt,kr]of X)on(gt,kr)}ee||Ut(_,y(_)+1)}),()=>{ee=!0}});let Or=Xe(()=>({...mt(),getResolvedToolContext:O=>y(dr)[O]??null,getToolRenderParams:O=>{let ee=y(dr)[O]?.params??null,X=yr.get(O);return X?{...ee??{},...X}:ee}})),yr=new Map,fn=0,or=Xe(()=>{if(!r)return[];y(_);let O=[];for(let ee of y(Nr)){let X=y(Je).renderForToolbar(ee,y(st),y(Or));X&&O.push(X)}return O}),j=Xe(()=>{if(!Array.isArray(M()))return[];let O=[];return M().forEach((ee,X)=>{if(K5(ee)){O.push(ee);return}console.warn(`[ItemToolBar] Ignoring invalid host button at index ${X}. Expected { id, label, href | onClick } with valid types.`)}),O}),ke=Xe(()=>y(or).filter(O=>!!O.button).map(O=>{let ee=O.button;return{id:O.toolId,label:ee.label,ariaLabel:ee.ariaLabel||ee.label,icon:ee.icon,faIconName:ee.faIconName,tooltip:ee.tooltip||ee.label,disabled:ee.disabled,active:y(v)[O.toolId]??ee.active??!1,onClick:()=>{ee.onClick(),Vn()}}})),Fe=Xe(()=>[...y(ke),...y(j)]),Ve=Xe(()=>{let O={};for(let ee of y(or))O[ee.toolId]=y(v)[ee.toolId]??ee.button?.active??!1;return O}),Ft=Xe(()=>y(or).flatMap(O=>(O.elements||[]).filter(ee=>ee.mount==="before-buttons").filter(ee=>!!ee.element).map((ee,X)=>({key:`before-${O.toolId}-${X}`,toolId:O.toolId,entry:ee})))),Pr=Xe(()=>y(or).flatMap(O=>(O.elements||[]).filter(ee=>ee.mount==="after-buttons").filter(ee=>!!ee.element).map((ee,X)=>({key:`after-${O.toolId}-${X}`,toolId:O.toolId,entry:ee})))),en=Xe(()=>y(or).flatMap(O=>(O.elements||[]).filter(ee=>ee.mount==="controls-row").filter(ee=>!!ee.element).map((ee,X)=>({key:`controls-row-${O.toolId}-${X}`,toolId:O.toolId,entry:ee})))),En=Xe(()=>y(or).flatMap(O=>(O.elements||[]).map(ee=>({toolId:O.toolId,hint:ee.layoutHints?.controlsRow})).filter(ee=>!!ee.hint))),ri=Xe(()=>y(or).flatMap(O=>(O.elements||[]).map(ee=>({toolId:O.toolId,hint:ee.layoutHints?.headerOverlay})).filter(ee=>!!ee.hint))),ko=Xe(()=>y(En).some(O=>O.hint?.reserveSpace===!0)),ge=Xe(()=>y(En).some(O=>O.hint?.showWhenToolActive===!0&&(y(Ve)[O.toolId]??!1))),fr=Xe(()=>J()==="left"||J()==="right"),Nn=Xe(()=>y(ri).some(O=>O.hint?.showWhenToolActive===!0&&(y(Ve)[O.toolId]??!1))),_r=Xe(()=>y(en).length>0||y(ko)||y(ge));function Ji(){if(!y(ye))return null;let O=y(ye).getRootNode();return O instanceof ShadowRoot?O.host:null}Ot(()=>{let O=Ji();if(!O)return;let ee=y(ri).length>0,X=y(Nn);return O.setAttribute("data-pie-header-overlay",ee?"true":"false"),O.setAttribute("data-pie-header-overlay-active",X?"true":"false"),()=>{O.removeAttribute("data-pie-header-overlay"),O.removeAttribute("data-pie-header-overlay-active")}}),Ot(()=>{!r||!y(z)||y(Fe).some(O=>!!g(O))&&c()});function ni(O){return O.id in y(v)?y(v)[O.id]===!0:O.active===!0}function Os(O){return J5(O)}function Vn(){let O={};for(let ee of y(or))ee.sync?.(),ee.button&&(O[ee.toolId]=ee.button.active??!1);Ut(v,O,!0)}Ot(()=>{let O=[];Vn();for(let ee of y(or))if(ee.subscribeActive){let X=!1,he=ee.subscribeActive(gt=>{queueMicrotask(()=>{X||(Ut(v,{...y(v),[ee.toolId]:gt},!0),ee.sync?.())})});O.push(()=>{X=!0,he()})}return()=>{O.forEach(ee=>ee())}}),Ot(()=>{let O=y(te)?.toolkitCoordinator;if(typeof O?.registerToolRequestTarget!="function")return;let ee=y(Et);return O.registerToolRequestTarget({level:ee,get scopeId(){return y(ce)},hostsTool:X=>y(Nr).includes(X),open:(X,he)=>{if(!y(W)||!y(Nr).includes(X))return;he&&Object.keys(he).length>0&&(fn+=1,yr.set(X,{...he,toolRequestId:fn}));let gt=me(y(W),X);y(W).showTool(gt),queueMicrotask(()=>Vn())}})}),Ot(()=>{if(!y(Or).subscribeVisibility)return;let O=!1,ee=y(Or).subscribeVisibility(()=>{queueMicrotask(()=>{O||Vn()})});return()=>{O=!0,ee?.()}}),Ot(()=>{let O=y(Or).toolkitCoordinator;if(typeof O?.subscribeTelemetry!="function")return;let ee=!1,X=O.subscribeTelemetry(({eventName:he,payload:gt})=>{he==="pie-toolkit-tool-config-updated"&&(gt?.toolId&&!y(Nr).includes(gt.toolId)||queueMicrotask(()=>{ee||(Ut(_,y(_)+1),Vn())}))});return()=>{ee=!0,X?.()}});let ua="[data-pie-tool-overlay-boundary]";function ns(O,ee){if(ee.container!=="content-boundary")return O;let X=O;for(;X;){if(X instanceof HTMLElement&&X.matches(ua))return X;if(X instanceof HTMLElement&&X.parentElement){X=X.parentElement;continue}let he=X.getRootNode();X=he instanceof ShadowRoot?he.host:null}return O}function Qi(O,ee){let X=ee,he=null,gt=O,kr=et=>{if(!et)return;let jr=et.__pieToolElementUnmount;typeof jr=="function"&&jr()},Ie=et=>{he!==et&&(he&&(kr(he),he.parentNode===gt&&gt.removeChild(he)),he=et,he&&(gt=ns(O,X),he.parentNode&&he.parentNode!==gt&&he.parentNode.removeChild(he),gt.appendChild(he)))};return Ie(ee.element),{update(et){X=et,Ie(et.element)},destroy(){Ie(null)}}}function Zi(O,ee){let X=ee,he=null,gt=null,kr=[],Ie=null,et=null,jr=null,$t=null,$e=null,Ar=null,Kr=null,br=!1,Xr=!1,wr=()=>X.mounted.entry.shell?.pageTabOrder===!0,Cr=()=>X.mounted.entry.shell?.ndsHeaderControls===!0,Dt=null,Mt=null,Hr=UA({onMove:pe=>$A(pe),onEnd:()=>{Mt=null}}),zr=0,Pt=0,hr=0,Ur=0,Gn=0,xr=0,gn=0,qn=0,S=null,Z=[],oe=0,we=0,qe=X.mounted.entry.shell?.initialWidth??720,We=X.mounted.entry.shell?.initialHeight??560,ot=qe,Rr=We,qr=!1,Br=null,Gt=null,Fr=!1,sr=pe=>{if(!pe)return;let Ke=pe.__pieToolElementUnmount;typeof Ke=="function"&&Ke()},k=()=>{let pe=X.mounted.entry.shell;return pe?{toolId:X.mounted.toolId,toolbarContext:y(Or),shellConfig:pe}:null},F=pe=>{let Ke=y(Je).get(X.mounted.toolId),wt=k();!Ke?.onHostedMount||!wt||Ke.onHostedMount(pe,wt)},Oe=()=>{let pe=y(Je).get(X.mounted.toolId),Ke=k();!pe?.onHostedResize||!Ke||pe.onHostedResize({width:qe,height:We},X.mounted.entry.element,Ke)},je=()=>{let pe=y(Je).get(X.mounted.toolId),Ke=k();!pe?.onHostedUnmount||!Ke||pe.onHostedUnmount(X.mounted.entry.element,Ke)},Se=(pe,Ke,wt)=>Math.max(Ke,Math.min(pe,wt)),E=()=>{let pe=X.mounted.entry.shell;return{minWidth:pe?.minWidth??320,minHeight:pe?.minHeight??240,maxWidth:pe?.maxWidth??window.innerWidth,maxHeight:pe?.maxHeight??window.innerHeight}},ue=()=>{let pe=X.mounted.entry.shell?.minWidth,Ke=typeof pe=="number"&&pe>0&&qe<pe,wt=Ke?`${pe}px`:"";Dt&&(Dt.style.minWidth=wt),Ie&&(Ie.style.minWidth="0"),et&&(et.style.minWidth="0",et.style.overflowX=Ke?"auto":"hidden")},Le=()=>X.mounted.entry.shell?.content?.overflowY==="auto"?"auto":"hidden",Ge=()=>{if(!Ie)return 0;let pe=Ie.getBoundingClientRect().height;return pe>0?pe:Ie.offsetHeight||0},ut=()=>{if(!et)return;let pe=X.mounted.entry.shell;if(et.style.overflowY=Le(),!!Dt){if(pe?.content?.preserveMinHeight===!0){let Ke=Ge(),wt=pe.minHeight??240,tt=Math.max(0,wt-Ke),Te=Math.max(0,We-Ke),kt=Math.max(Te,tt);Dt.style.height=`${kt}px`,Dt.style.minHeight="0",Dt.style.flex=`0 0 ${kt}px`;return}Dt.style.height="100%",Dt.style.minHeight="0",Dt.style.flex="1 1 auto"}},Ht=()=>{let pe=X.mounted.entry.shell,Ke=pe?.initialWidth??720,wt=pe?.initialHeight??560;Ke===ot&&wt===Rr||(ot=Ke,Rr=wt,!qr&&(qe=Ke,We=wt,eo()))},_t=()=>{let{minWidth:pe,minHeight:Ke,maxWidth:wt,maxHeight:tt}=E(),Te=Math.min(pe,window.innerWidth),kt=Math.min(Ke,window.innerHeight);qe=Se(qe,Te,Math.max(Te,Math.min(wt,window.innerWidth))),We=Se(We,kt,Math.max(kt,Math.min(tt,window.innerHeight))),oe=Se(oe,0,Math.max(0,window.innerWidth-qe)),we=Se(we,0,Math.max(0,window.innerHeight-We)),Ns(),ue(),ut(),Oe()},rr=(pe,Ke)=>{qr=!0,oe+=pe,we+=Ke,_t()},Wn=(pe,Ke)=>{qr=!0,qe+=pe,We+=Ke,_t()},Yn=(pe,Ke,wt,tt="fa-regular")=>{let Te=document.createElement("nds-icon-button");if(Te.setAttribute("variant","tertiary"),Te.setAttribute("size","small"),Te.setAttribute("type","circle"),Te.setAttribute("icon-name",Ke),Te.setAttribute("button-aria-label",pe),Te.title=pe,Te.addEventListener("click",kt=>{kt.stopPropagation(),wt(),Ds()}),tt!=="fa-light"){let kt=an=>{an.classList.remove("fa-light"),an.classList.add(tt)},jt=Te.querySelector("i.fa-light");if(jt)kt(jt);else{let an=new MutationObserver(()=>{let Dn=Te.querySelector("i.fa-light");Dn&&(kt(Dn),an.disconnect())});an.observe(Te,{childList:!0,subtree:!0})}}return Te},qa=(pe,Ke,wt)=>{let tt=document.createElement("button");return tt.type="button",tt.className="pie-tool-shell__control",tt.setAttribute("aria-label",pe),tt.title=pe,tt.textContent=Ke,tt.style.border="1px solid transparent",tt.style.background="color-mix(in srgb, var(--pie-white, #fff) 10%, transparent)",tt.style.color="inherit",tt.style.cursor="pointer",tt.style.display="inline-flex",tt.style.alignItems="center",tt.style.justifyContent="center",tt.style.width="28px",tt.style.height="28px",tt.style.padding="0",tt.style.fontSize="14px",tt.style.fontWeight="700",tt.style.borderRadius="8px",tt.style.lineHeight="1",tt.onclick=Te=>{Te.stopPropagation(),wt(),Ds()},tt.onfocus=()=>{tt.style.outline="2px solid var(--pie-button-focus-outline, var(--pie-primary, #4A90E2))",tt.style.outlineOffset="2px"},tt.onblur=()=>{tt.style.outline="none",tt.style.outlineOffset="0"},tt},Ns=()=>{he&&(he.style.left=`${oe}px`,he.style.top=`${we}px`,he.style.width=`${qe}px`,he.style.height=`${We}px`,he.style.display=X.active?"flex":"none")},da=()=>{jr&&(jr.textContent=X.mounted.entry.shell?.title||X.mounted.toolId);for(let{el:pe,key:Ke}of kr){let wt=X.i18n.t(Ke);pe.tagName==="NDS-ICON-BUTTON"?pe.setAttribute("button-aria-label",wt):pe.setAttribute("aria-label",wt),pe.title&&(pe.title=wt)}},sn=()=>{if(!et)return;let pe=X.mounted.entry.element;pe.style.display="block",pe.style.width="100%",pe.style.height="100%",pe.style.flex="1 1 auto",pe.style.minHeight="0",Dt&&Dt!==pe&&(Dt.parentNode===et&&(sr(Dt),et.removeChild(Dt)),Dt=null),pe.parentNode&&pe.parentNode!==et&&pe.parentNode.removeChild(pe),pe.parentNode!==et&&et.appendChild(pe),Dt=pe,ue(),ut(),F(pe)},Ds=()=>{y(W)&&he&&y(W).bringToFront(he)},Pi=()=>{if(!he||!y(W)||!X.active)return;let pe=bt(X.mounted.toolId);y(W).getToolState(pe)?.element!==he&&y(W).updateToolElement(pe,he)},eo=()=>{let{innerWidth:pe,innerHeight:Ke}=window,wt=X.mounted.entry.shell,tt=wt?.initialAlign??"center",Te=wt?.initialMargin??16,kt=Te+60;switch(tt){case"top-left":oe=Te,we=kt;break;case"top-right":oe=Math.max(0,pe-qe-Te),we=kt;break;case"bottom-left":oe=Te,we=Math.max(0,Ke-We-kt);break;case"bottom-right":oe=Math.max(0,pe-qe-Te),we=Math.max(0,Ke-We-kt);break;default:oe=Math.max(0,Math.round((pe-qe)/2)),we=Math.max(0,Math.round((Ke-We)/2))}_t()},bc=()=>{let pe=Gt;pe&&queueMicrotask(()=>{if(pe.isConnected)try{pe.focus()}catch{}})},Yf=()=>{if(typeof document>"u")return null;let pe=document.activeElement;for(;pe;){let Ke=pe.shadowRoot;if(Ke&&Ke.activeElement&&Ke.activeElement!==pe)pe=Ke.activeElement;else break}return pe??null},wc=()=>{if(!he||Br)return;let pe=Yf();!Gt&&pe&&!he.contains(pe)&&(Gt=pe),wr()&&!Xr&&(document.addEventListener("keydown",dg,!0),Xr=!0),Br=GA(he,{initialFocus:$e,onEscape:()=>{fg()},wrap:!wr(),onTabExit:wr()?(Ke,wt)=>{if(Ke==="backward"){if(Gt?.isConnected){wt.preventDefault();try{Gt.focus()}catch{}}return}let tt=ug();if(tt){wt.preventDefault();try{tt.focus()}catch{}}}:void 0})},ug=()=>{let pe=y(Or).getScopeElement?.()??null;if(!pe)return null;let Ke=tt=>!!(y(ye)&&y(ye).contains(tt)||he&&he.contains(tt)),wt=tt=>{if(tt instanceof HTMLElement){if(Ke(tt))return null;if(tt.matches?.(WA)&&qA(tt))return tt}let Te=tt.shadowRoot;if(Te)for(let kt=0;kt<Te.children.length;kt++){let jt=wt(Te.children[kt]);if(jt)return jt}for(let kt=0;kt<tt.children.length;kt++){let jt=wt(tt.children[kt]);if(jt)return jt}return null};return wt(pe)},_A=()=>he?VA(he).filter(pe=>pe!==Ar&&pe!==Kr):[],dg=pe=>{if(pe.key!=="Tab"||!he||!X.active)return;let Ke=Yf();if(!Ke||he.contains(Ke))return;let wt=_A();if(wt.length!==0){if(pe.shiftKey){if(Ke!==ug())return;pe.preventDefault();try{wt[wt.length-1].focus()}catch{}return}if(Ke===Gt){pe.preventDefault();try{wt[0].focus()}catch{}}}},Ew=()=>{if(Xr&&(document.removeEventListener("keydown",dg,!0),Xr=!1),!Br)return;let pe=Br;Br=null;try{pe()}catch{}bc()},fg=()=>{y(Or).toggleTool(X.mounted.toolId),Vn()},Cw=pe=>{X.mounted.entry.shell?.draggable&&(pe.target.closest("button")||!he||Hr.begin(pe,he)&&(Mt="drag",qr=!0,zr=pe.clientX-oe,Pt=pe.clientY-we,he.setPointerCapture(pe.pointerId),Ds()))},AA=pe=>Ke=>{!he||!X.mounted.entry.shell?.resizable||(Ke.stopPropagation(),Hr.begin(Ke,he)&&(Mt="resize",qr=!0,S=pe,hr=qe,Ur=We,Gn=Ke.clientX,xr=Ke.clientY,gn=oe,qn=we,he.setPointerCapture(Ke.pointerId),Ds()))},$A=pe=>{if(he){if(Mt==="drag"){pe.preventDefault();let Ke=Math.max(0,window.innerWidth-qe),wt=Math.max(0,window.innerHeight-We);oe=Se(pe.clientX-zr,0,Ke),we=Se(pe.clientY-Pt,0,wt),Ns();return}if(Mt==="resize"){pe.preventDefault();let Ke=X.mounted.entry.shell,wt=Ke?.minWidth??320,tt=Ke?.minHeight??240,Te=Math.min(wt,window.innerWidth),kt=Math.min(tt,window.innerHeight),jt=Ke?.maxWidth??window.innerWidth,an=Ke?.maxHeight??window.innerHeight,Dn=pe.clientX-Gn,_i=pe.clientY-xr;if(S==="se")qe=Se(hr+Dn,Te,Math.max(Te,Math.min(jt,window.innerWidth-oe))),We=Se(Ur+_i,kt,Math.max(kt,Math.min(an,window.innerHeight-we)));else if(S==="sw"){let ii=gn+hr,To=Se(hr-Dn,Te,Math.min(jt,ii));oe=ii-To,qe=To,We=Se(Ur+_i,kt,Math.max(kt,Math.min(an,window.innerHeight-we)))}else if(S==="ne"){let ii=qn+Ur;qe=Se(hr+Dn,Te,Math.max(Te,Math.min(jt,window.innerWidth-oe)));let To=Se(Ur-_i,kt,Math.min(an,ii));we=ii-To,We=To}else if(S==="nw"){let ii=gn+hr,To=qn+Ur,Cn=Se(hr-Dn,Te,Math.min(jt,ii));oe=ii-Cn,qe=Cn;let Bu=Se(Ur-_i,kt,Math.min(an,To));we=To-Bu,We=Bu}Ns(),ue(),ut(),Oe()}}},xw=()=>{_t()};if(r&&X.mounted.entry.shell){let pe=X.mounted.entry.shell?.ndsHeaderControls===!0&&y(z);pe&&c(),he=document.createElement("div"),he.className="pie-tool-shell",he.setAttribute("data-pie-tool-shell",X.mounted.toolId),he.style.position="fixed",he.style.zIndex=String(Kp.TOOL),he.style.background="var(--pie-background, #fff)",he.style.border="1px solid var(--pie-border-light, #d1d5db)",he.style.borderRadius="12px",he.style.boxShadow="0 10px 40px color-mix(in srgb, var(--pie-black, #000) 25%, transparent)",he.style.setProperty("--color-interactive-blue","var(--pie-calculator-button-color, var(--pie-button-color, var(--pie-text, #222)))"),he.style.setProperty("--color-new-gray","var(--pie-background-dark, #f3f5f7)"),he.style.setProperty("--color-primary-white","var(--pie-white, #ffffff)"),he.style.setProperty("--color-primary-black","var(--pie-text, #000000)"),he.style.setProperty("--color-focus-blue","var(--pie-button-focus-outline, #2b87ff)"),he.style.overflow="visible",he.style.display=X.active?"flex":"none",he.style.flexDirection="column",he.style.userSelect="none",he.style.webkitUserSelect="none",he.style.touchAction="none",he.setAttribute("draggable","false"),he.addEventListener("dragstart",Te=>Te.preventDefault()),Ie=document.createElement("div"),Ie.className="pie-tool-shell__header",Ie.style.display="flex",Ie.style.flexWrap="wrap",Ie.style.alignItems="center",Ie.style.justifyContent="space-between",Ie.style.gap="6px",Ie.style.padding=Cr()?"12px 12px 12px 28px":"10px 12px",Cr()&&(Ie.style.minHeight="48px"),Cr()?(Ie.style.background="var(--pie-section-player-card-header-background, var(--pie-button-active-bg, #f3f4f6))",Ie.style.color="var(--pie-text, #111827)",Ie.style.borderBottom="1px solid var(--pie-border-light, #e5e7eb)"):(Ie.style.background="var(--pie-primary-dark, #2c3e50)",Ie.style.color="var(--pie-white, #fff)"),Ie.style.cursor=X.mounted.entry.shell.draggable===!1?"default":"move",Ie.style.flex="0 0 auto",Ie.style.borderRadius="12px 12px 0 0",Ie.style.overflow="hidden",Ie.style.userSelect="none",Ie.style.webkitUserSelect="none",Ie.style.touchAction="none",Ie.setAttribute("draggable","false"),Ie.addEventListener("dragstart",Te=>Te.preventDefault()),jr=document.createElement("span"),jr.className="pie-tool-shell__title",jr.style.minWidth="0",jr.style.overflowWrap="anywhere",jr.textContent=X.mounted.entry.shell.title||X.mounted.toolId,Ie.appendChild(jr),$t=document.createElement("div"),$t.className="pie-tool-shell__controls",$t.style.display="inline-flex",$t.style.flexWrap="wrap",$t.style.minWidth="0",$t.style.alignItems="center",$t.style.gap=Cr()?"6px":"4px";let Ke=X.mounted.entry.shell,wt=(Te,kt,jt,an,Dn="fa-regular")=>{if(!$t)return;let _i=X.i18n.t(Te),ii=pe?Yn(_i,jt,an,Dn):qa(_i,kt,an);kr.push({el:ii,key:Te}),$t.appendChild(ii)};if(Ke?.draggable!==!1&&(wt("toolkit.window.moveLeftA11y","←","chevron-left",()=>rr(-24,0)),wt("toolkit.window.moveRightA11y","→","chevron-right",()=>rr(24,0)),wt("toolkit.window.moveUpA11y","↑","chevron-up",()=>rr(0,-24)),wt("toolkit.window.moveDownA11y","↓","chevron-down",()=>rr(0,24))),Ke?.resizable!==!1&&(wt("toolkit.window.shrinkA11y","−","magnifying-glass-minus",()=>Wn(-40,-40)),wt("toolkit.window.growA11y","+","magnifying-glass-plus",()=>Wn(40,40))),!Cr()){let Te=qa(X.i18n.t("toolkit.window.centerA11y"),"◎",eo);kr.push({el:Te,key:"toolkit.window.centerA11y"}),$t.appendChild(Te)}let tt=null;if(Cr()?(tt=document.createElement("div"),tt.className="pie-tool-shell__header-right",tt.style.display="inline-flex",tt.style.flexWrap="wrap",tt.style.maxWidth="100%",tt.style.justifyContent="flex-end",tt.style.alignItems="center",tt.style.gap="6px",tt.appendChild($t),Ie.appendChild(tt)):Ie.appendChild($t),pe)$e=Yn(X.i18n.t("toolkit.window.closeA11y"),"xmark",fg,"fa-regular"),kr.push({el:$e,key:"toolkit.window.closeA11y"}),$e.style.display=X.mounted.entry.shell.closeable===!1?"none":"inline-block";else{let Te=document.createElement("button");Te.type="button",Te.className="pie-tool-shell__close",Te.setAttribute("aria-label",X.i18n.t("toolkit.window.closeA11y")),kr.push({el:Te,key:"toolkit.window.closeA11y"});let kt="http://www.w3.org/2000/svg",jt=document.createElementNS(kt,"svg");jt.setAttribute("xmlns",kt),jt.setAttribute("viewBox","0 0 16 16"),jt.setAttribute("aria-hidden","true");let an=document.createElementNS(kt,"path");an.setAttribute("d","M3.5 3.5L12.5 12.5M12.5 3.5L3.5 12.5"),an.setAttribute("stroke","currentColor"),an.setAttribute("stroke-width","1.8"),an.setAttribute("stroke-linecap","round"),jt.appendChild(an),Te.appendChild(jt);let Dn=jt.style;Dn.width="16px",Dn.height="16px",Dn.display="block",Dn.flexShrink="0",Dn.pointerEvents="none";let _i="color-mix(in srgb, var(--pie-white, #fff) 8%, transparent)",ii="color-mix(in srgb, var(--pie-white, #fff) 18%, transparent)";Te.style.border="1px solid transparent",Te.style.background=_i,Te.style.color="inherit",Te.style.cursor="pointer",Te.style.display="inline-flex",Te.style.alignItems="center",Te.style.justifyItems="center",Te.style.width="28px",Te.style.height="28px",Te.style.padding="0",Te.style.borderRadius="8px",Te.style.lineHeight="0",Te.style.transition="background-color 0.15s ease, border-color 0.15s ease",Te.style.display=X.mounted.entry.shell.closeable===!1?"none":"inline-flex",Te.onmouseenter=()=>{Te.style.background=ii},Te.onmouseleave=()=>{Te.style.background=_i},Te.onfocus=()=>{Te.style.outline="2px solid var(--pie-button-focus-outline, var(--pie-primary, #4A90E2))",Te.style.outlineOffset="2px"},Te.onblur=()=>{Te.style.outline="none",Te.style.outlineOffset="0"},Te.onclick=fg,$e=Te}if(tt?tt.appendChild($e):Ie.appendChild($e),Ie.tabIndex=0,Ie.onkeydown=Te=>{if(Te.key==="Home"){Te.preventDefault(),eo();return}let kt=X.mounted.entry.shell;if(Te.shiftKey&&kt?.resizable!==!1){if(Te.key==="ArrowRight"||Te.key==="ArrowDown"){Te.preventDefault(),Wn(40,40);return}if(Te.key==="ArrowLeft"||Te.key==="ArrowUp"){Te.preventDefault(),Wn(-40,-40);return}}kt?.draggable!==!1&&(Te.key==="ArrowLeft"?(Te.preventDefault(),rr(-24,0)):Te.key==="ArrowRight"?(Te.preventDefault(),rr(24,0)):Te.key==="ArrowUp"?(Te.preventDefault(),rr(0,-24)):Te.key==="ArrowDown"&&(Te.preventDefault(),rr(0,24)))},et=document.createElement("div"),et.className="pie-tool-shell__content",et.style.position="relative",et.style.width="100%",et.style.flex="1 1 auto",et.style.minHeight="0",et.style.overflowX="hidden",et.style.overflowY=Le(),et.style.borderRadius="0 0 12px 12px",Cr()){let Te=kt=>{let jt=document.createElement("div");return jt.tabIndex=0,jt.setAttribute("aria-hidden","true"),jt.setAttribute("data-pie-tool-shell-focus-guard",kt),jt.style.position="absolute",jt.style.width="1px",jt.style.height="1px",jt.style.padding="0",jt.style.margin="-1px",jt.style.overflow="hidden",jt.style.clipPath="inset(50%)",jt.style.whiteSpace="nowrap",jt.style.border="0",jt};Ar=Te("start"),Kr=Te("end"),Ar.addEventListener("focus",kt=>{if(!br){br=!0;try{if(kt.stopPropagation(),Gt?.isConnected)try{Gt.focus()}catch{}}finally{queueMicrotask(()=>{br=!1})}}}),Kr.addEventListener("focus",kt=>{if(!br){br=!0;try{kt.stopPropagation();let jt=ug();if(jt)try{jt.focus()}catch{}}finally{queueMicrotask(()=>{br=!1})}}}),he.appendChild(Ar)}if(he.appendChild(Ie),he.appendChild(et),Cr()&&Kr&&he.appendChild(Kr),X.mounted.entry.shell.resizable!==!1){let Te=(kt,jt,an,Dn,_i,ii,To)=>{let Cn=document.createElement("div");Cn.className="pie-tool-shell__resize",Cn.style.position="absolute",Cn.style.width="24px",Cn.style.height="24px",Cn.style.cursor=ii,Cn.style.zIndex="10",Cn.style.touchAction="none",Cn.setAttribute("draggable","false"),jt!==null&&(Cn.style.top=jt),an!==null&&(Cn.style.right=an),Dn!==null&&(Cn.style.bottom=Dn),_i!==null&&(Cn.style.left=_i),To!==null&&(Cn.style.background=`linear-gradient(${To}, transparent 0%, transparent 40%, rgba(0,0,0,0.35) 40%, rgba(0,0,0,0.35) 60%, transparent 60%, transparent 100%)`);let Bu=AA(kt);Cn.addEventListener("pointerdown",Bu),he.appendChild(Cn),Z.push({el:Cn,handler:Bu})};Te("se",null,"0","0",null,"nwse-resize",null),Te("nw","0",null,null,"0","nwse-resize","135deg"),Te("ne","0","0",null,null,"nesw-resize",null),Te("sw",null,null,"0","0","nesw-resize",null)}Ie.addEventListener("pointerdown",Cw),he.addEventListener("pointerdown",Ds),window.addEventListener("resize",xw),document.body.appendChild(he),gt=new Ql(he,{context:v0,initialValue:X.runtime}),gt.connect(),eo(),Ns(),Pi(),da(),sn(),Oe(),X.active&&wc(),Fr=X.active}return{update(pe){if(X=pe,!he||!et||!jr||!$e)return;gt?.setValue(X.runtime),da(),Ht();let Ke=$e.tagName.toLowerCase()==="nds-icon-button"?"inline-block":"inline-flex";$e.style.display=X.mounted.entry.shell?.closeable===!1?"none":Ke,Ns(),Pi(),sn(),Oe(),!Fr&&X.active?wc():Fr&&!X.active&&(Ew(),Gt=null),Fr=X.active},destroy(){je(),gt?.disconnect(),gt=null,kr.length=0,Br&&Ew(),Xr&&(document.removeEventListener("keydown",dg,!0),Xr=!1);for(let{el:pe,handler:Ke}of Z)pe.removeEventListener("pointerdown",Ke);Gt=null,Z.length=0,Ie&&(Ie.removeEventListener("pointerdown",Cw),Ie.onkeydown=null),Hr.release(),he&&he.removeEventListener("pointerdown",Ds),window.removeEventListener("resize",xw),Dt&&et&&Dt.parentNode===et&&(sr(Dt),et.removeChild(Dt)),Dt=null,he&&he.parentElement&&he.remove()}}}var Ls={get level(){return b()},set level(O){b(O),ct()},get scopeId(){return I()},set scopeId(O){I(O),ct()},get itemId(){return C()},set itemId(O){C(O),ct()},get sectionId(){return x()},set sectionId(O){x(O),ct()},get catalogId(){return $()},set catalogId(O){$(O),ct()},get tools(){return P()},set tools(O){P(O),ct()},get contentKind(){return L()},set contentKind(O){L(O),ct()},get position(){return J()},set position(O){J(O),ct()},get scopeElement(){return V()},set scopeElement(O){V(O),ct()},get toolRegistry(){return Y()},set toolRegistry(O){Y(O),ct()},get item(){return Pe()},set item(O){Pe(O),ct()},get hostButtons(){return M()},set hostButtons(O){M(O),ct()},get class(){return H()},set class(O){H(O),ct()},get size(){return ne()},set size(O){ne(O),ct()},get language(){return ae()},set language(O){ae(O),ct()}},is=Mi(),Ri=oi(is),Un=O=>{var ee=iD();let X;var he=fl(ee),gt=fl(he);lh(gt,17,()=>y(Ft),$t=>$t.key,($t,$e)=>{var Ar=Mi(),Kr=oi(Ar),br=wr=>{var Cr=Mi(),Dt=oi(Cr);Ag(Dt,()=>y(z),Mt=>{var Hr=mh();ga(Hr,(zr,Pt)=>Zi?.(zr,Pt),()=>({mounted:y($e),active:y(Ve)[y($e).toolId]??!1,runtime:y(te),i18n:y(A)})),Zt(Mt,Hr)}),Zt(wr,Cr)},Xr=wr=>{var Cr=mh();ga(Cr,(Dt,Mt)=>Qi?.(Dt,Mt),()=>y($e).entry),Zt(wr,Cr)};Oi(Kr,wr=>{y($e).entry.shell?wr(br):wr(Xr,-1)}),Zt($t,Ar)});var kr=Ll(gt,2);lh(kr,17,()=>y(Fe),$t=>$t.id,($t,$e,Ar,Kr)=>{let br=Xe(()=>y(z)&&!V1(y($e))?g(y($e)):null);var Xr=Mi(),wr=oi(Xr),Cr=zr=>{var Pt=eD(),hr=fl(Pt);Ja(hr,1,"item-toolbar__nds-button svelte-1c13522"),jn(hr,"type","circle"),jn(hr,"size","small"),jn(hr,"variant","tertiary"),nn(()=>jn(hr,"icon-name",y(br))),nn(()=>jn(hr,"button-aria-label",y($e).ariaLabel||y($e).label)),nn(()=>jn(hr,"title",y($e).tooltip||y($e).label)),nn(()=>jn(hr,"disabled",y($e).disabled)),ga(hr,Ur=>f?.(Ur)),ga(hr,(Ur,Gn)=>h?.(Ur,Gn),()=>ni(y($e))),ro(Pt),ih("click",hr,function(...Ur){y($e).onClick?.apply(this,Ur)}),Zt(zr,Pt)},Dt=zr=>{var Pt=tD();let hr;var Ur=fl(Pt),Gn=xr=>{var gn=Mi(),qn=oi(gn),S=We=>{var ot=gh();ch(ot,()=>Kf(y($e).icon),!0),ro(ot),Zt(We,ot)},Z=Xe(()=>G1(y($e).icon)),oe=We=>{var ot=K1();nn(()=>pi(ot,"src",y($e).icon)),Zt(We,ot)},we=Xe(()=>Y1(y($e).icon)),qe=We=>{let ot=Xe(()=>Os(y($e).icon));var Rr=Mi(),qr=oi(Rr),Br=Fr=>{var sr=gh();ch(sr,()=>Kf(y(ot)),!0),ro(sr),Zt(Fr,sr)},Gt=Fr=>{var sr=X1();nn(()=>Ja(sr,1,`icon icon-${y($e).icon}`,"svelte-1c13522")),Zt(Fr,sr)};Oi(qr,Fr=>{y(ot)?Fr(Br):Fr(Gt,-1)}),Zt(We,Rr)};Oi(qn,We=>{y(Z)?We(S):y(we)?We(oe,1):We(qe,-1)}),Zt(xr,gn)};Oi(Ur,xr=>{y($e).icon&&xr(Gn)}),ro(Pt),nn(xr=>{hr=Ja(Pt,1,"item-toolbar__button svelte-1c13522",null,hr,{"item-toolbar__button--active":xr}),pi(Pt,"href",y($e).disabled?void 0:y($e).href),pi(Pt,"target",y($e).target),pi(Pt,"rel",y($e).rel),pi(Pt,"aria-label",y($e).ariaLabel||y($e).label),pi(Pt,"title",y($e).tooltip||y($e).label),pi(Pt,"aria-disabled",y($e).disabled?"true":void 0)},[()=>ni(y($e))]),ih("click",Pt,xr=>{y($e).disabled&&xr.preventDefault()}),Zt(zr,Pt)},Mt=Xe(()=>V1(y($e))),Hr=zr=>{var Pt=rD();let hr;var Ur=fl(Pt),Gn=xr=>{var gn=Mi(),qn=oi(gn),S=We=>{var ot=gh();ch(ot,()=>Kf(y($e).icon),!0),ro(ot),Zt(We,ot)},Z=Xe(()=>G1(y($e).icon)),oe=We=>{var ot=K1();nn(()=>pi(ot,"src",y($e).icon)),Zt(We,ot)},we=Xe(()=>Y1(y($e).icon)),qe=We=>{let ot=Xe(()=>Os(y($e).icon));var Rr=Mi(),qr=oi(Rr),Br=Fr=>{var sr=gh();ch(sr,()=>Kf(y(ot)),!0),ro(sr),Zt(Fr,sr)},Gt=Fr=>{var sr=X1();nn(()=>Ja(sr,1,`icon icon-${y($e).icon}`,"svelte-1c13522")),Zt(Fr,sr)};Oi(qr,Fr=>{y(ot)?Fr(Br):Fr(Gt,-1)}),Zt(We,Rr)};Oi(qn,We=>{y(Z)?We(S):y(we)?We(oe,1):We(qe,-1)}),Zt(xr,gn)};Oi(Ur,xr=>{y($e).icon&&xr(Gn)}),ro(Pt),nn((xr,gn)=>{hr=Ja(Pt,1,"item-toolbar__button svelte-1c13522",null,hr,{"item-toolbar__button--active":xr}),pi(Pt,"aria-label",y($e).ariaLabel||y($e).label),pi(Pt,"aria-pressed",gn),pi(Pt,"title",y($e).tooltip||y($e).label),Pt.disabled=y($e).disabled},[()=>ni(y($e)),()=>ni(y($e))]),ih("click",Pt,function(...xr){y($e).onClick?.apply(this,xr)}),Zt(zr,Pt)};Oi(wr,zr=>{y(br)?zr(Cr):y(Mt)?zr(Dt,1):zr(Hr,-1)}),Zt($t,Xr)});var Ie=Ll(kr,2);lh(Ie,17,()=>y(Pr),$t=>$t.key,($t,$e)=>{var Ar=Mi(),Kr=oi(Ar),br=wr=>{var Cr=Mi(),Dt=oi(Cr);Ag(Dt,()=>y(z),Mt=>{var Hr=mh();ga(Hr,(zr,Pt)=>Zi?.(zr,Pt),()=>({mounted:y($e),active:y(Ve)[y($e).toolId]??!1,runtime:y(te),i18n:y(A)})),Zt(Mt,Hr)}),Zt(wr,Cr)},Xr=wr=>{var Cr=mh();ga(Cr,(Dt,Mt)=>Qi?.(Dt,Mt),()=>y($e).entry),Zt(wr,Cr)};Oi(Kr,wr=>{y($e).entry.shell?wr(br):wr(Xr,-1)}),Zt($t,Ar)}),ro(he);var et=Ll(he,2),jr=$t=>{var $e=nD();let Ar;lh($e,21,()=>y(en),Kr=>Kr.key,(Kr,br)=>{var Xr=Mi(),wr=oi(Xr),Cr=Mt=>{var Hr=Mi(),zr=oi(Hr);Ag(zr,()=>y(z),Pt=>{var hr=J1();ga(hr,(Ur,Gn)=>Zi?.(Ur,Gn),()=>({mounted:y(br),active:y(Ve)[y(br).toolId]??!1,runtime:y(te),i18n:y(A)})),Zt(Pt,hr)}),Zt(Mt,Hr)},Dt=Mt=>{var Hr=J1();ga(Hr,(zr,Pt)=>Qi?.(zr,Pt),()=>y(br).entry),Zt(Mt,Hr)};Oi(wr,Mt=>{y(br).entry.shell?Mt(Cr):Mt(Dt,-1)}),Zt(Kr,Xr)}),ro($e),nn(()=>Ar=Ja($e,1,"item-toolbar__controls-row svelte-1c13522",null,Ar,{"item-toolbar__controls-row--reserve":y(ko),"item-toolbar__controls-row--active":y(ge),"item-toolbar__controls-row--align-start":y(fr)})),Zt($t,$e)};Oi(et,$t=>{y(_r)&&$t(jr)}),ro(ee),g0(ee,$t=>Ut(ye,$t),()=>y(ye)),nn(()=>{X=Ja(ee,1,`item-toolbar ${H()??""} item-toolbar--${ne()??""}`,"svelte-1c13522",X,{"item-toolbar--top":J()==="top","item-toolbar--right":J()==="right","item-toolbar--bottom":J()==="bottom","item-toolbar--left":J()==="left","item-toolbar--header-overlay-active":y(Nn)}),pi(ee,"data-content-kind",y(Ne)),pi(ee,"data-level",y(Ae))}),ih("focusin",he,$t=>{y(Ae)==="section"&&$t.target instanceof HTMLElement&&$t.target.scrollIntoView({block:"nearest",inline:"nearest"})}),Zt(O,ee)};return Oi(Ri,O=>{r&&O(Un)}),Zt(e,is),Cf(Ls)}nL(["focusin","click"]);Z5("pie-item-toolbar",zm(sD,{level:{attribute:"level",type:"String"},scopeId:{attribute:"scope-id",type:"String"},itemId:{attribute:"item-id",type:"String"},sectionId:{attribute:"section-id",type:"String"},catalogId:{attribute:"catalog-id",type:"String"},tools:{attribute:"tools",type:"String"},contentKind:{attribute:"content-kind",type:"String"},position:{attribute:"position",type:"String"},size:{attribute:"size",type:"String"},language:{attribute:"language",type:"String"},scopeElement:{type:"Object"},toolRegistry:{type:"Object"},item:{type:"Object"},hostButtons:{type:"Object"},class:{}},[],[],{mode:"open"}));var Q1="pie-register",aD="pie-unregister",lD="pie-item-session-changed",cD="item-session-changed",Px="pie-content-loaded",uD="pie-item-player-error",dD="pie-formative-action",fD="pie-media-time-source";function hD(e,t){return _x(e,t,new WeakMap)}function _x(e,t,r){if(Object.is(e,t))return!0;const n=Array.isArray(e);if(n!==Array.isArray(t)||!n&&(!Z1(e)||!Z1(t)))return!1;const i=e,o=t;if(n&&e.length!==t.length)return!1;let s=r.get(i);if(s?.has(o))return!0;s||(s=new Set,r.set(i,s)),s.add(o);const a=new Set([...Object.keys(i),...Object.keys(o)]);for(const l of a)if(!_x(i[l],o[l],r))return!1;return!0}function Z1(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pD(e,t){return e.kind===t.kind&&e.host===t.host&&e.itemId===t.itemId&&e.canonicalItemId===t.canonicalItemId&&e.contentKind===t.contentKind&&hD(e.settings,t.settings)}function eS(e){return Rv(e.item,e.kind)}function Ax(e,t){return e.isConnected||!t?e:t.eventTarget}function Bg(e,t,r){const n={kind:t.kind,itemId:t.itemId,canonicalItemId:t.canonicalItemId,contentKind:t.contentKind,item:t.item,...t.settings?{settings:t.settings}:{},element:t.host,...r?{runtimeId:r.runtimeId}:{}};Vl(Ax(t.host,r),e,n)}function mD(){let e=null,t=null,r;function n(){const o=e;if(!o)return;const s=r;e=null,t=null,r=void 0,Bg(aD,o,s)}function i(o,s){if(!o){n();return}if(e&&r?.runtimeId!==s?.runtimeId&&n(),e&&pD(e,o)){if(e.item===o.item)return;const a=eS(o);if(a!==null&&a===t){e=o;return}e=o,t=a,Bg(Q1,o,s);return}e=o,t=eS(o),r=s,Bg(Q1,o,s)}return{sync:i,retire:n}}var gD=50;function tS(e,t,r){const n=new Ql(e,{context:t,initialValue:r});return n.connect(),{provider:n,value:r}}function rS(e,t,r){r(e.value,t)||(e.value=t,e.provider.setValue(t))}var vD=(e,t,r)=>{if(e===t)return!0;if(!e||!t||e.id!==t.id)return!1;const n=Rv(e,r);return n!==null&&n===Rv(t,r)},yD=(e,t)=>e.kind===t.kind&&e.itemId===t.itemId&&e.canonicalItemId===t.canonicalItemId&&e.contentKind===t.contentKind&&e.regionPolicy===t.regionPolicy&&e.scopeElement===t.scopeElement&&vD(e.item,t.item,e.kind),bD=(e,t)=>e.scopeElement===t.scopeElement&&e.ttsHighlightTargetResolver===t.ttsHighlightTargetResolver,vh=(e,t,r)=>{e.getAttribute(t)!==r&&e.setAttribute(t,r)};function wD(){const e=mD(),t=Date.now();let r=null,n=null,i=null,o=null,s=null,a=null,l=[],c=null;const u=()=>{s!==null&&e.sync(a,s)};function d(m,v){if(m==="pie-content-loaded"&&(c=v),r&&s!==null){Vl(Ax(r,s),m,{...v,runtimeId:s.runtimeId});return}l.push({type:m,detail:v}),l.length>gD&&l.shift()}function f(m){if(m.runtimeId===s?.runtimeId)return;const v=s!==null;s={runtimeId:m.runtimeId,eventTarget:m.eventTarget},u();const b=l;l=[];for(const I of b)d(I.type,I.detail);v&&c&&d(Px,c)}function h(){for(const m of[n,i])m?.provider.disconnect();o?.(),o=null,s=null,l=[],c=null,a=null,n=null,i=null,r=null}function g(m){if(!m){e.sync(null),h();return}m.host!==r&&h(),r=m.host;const v=m.canonicalItemId||m.itemId,b=m.regionPolicy||"default",I=m.scopeElement||m.host,C={kind:m.kind,itemId:m.itemId,canonicalItemId:v,contentKind:m.contentKind,regionPolicy:b,scopeElement:I,item:m.item??null,contextVersion:t};n?rS(n,C,yD):n=tS(r,MA,C);const x={scopeElement:I,ttsHighlightTargetResolver:m.ttsHighlightTargetResolver??null};i?rS(i,x,bD):i=tS(r,NA,x),vh(r,"data-item-id",m.itemId),vh(r,"data-canonical-item-id",v),vh(r,"data-pie-shell-root",m.kind),vh(r,"data-region-policy",b);const $=a;a=m.itemId?{kind:m.kind,host:r,itemId:m.itemId,canonicalItemId:v,contentKind:m.contentKind,item:m.item??null,settings:m.settings??null}:null,$&&($.itemId!==a?.itemId||$.canonicalItemId!==a?.canonicalItemId)&&(c=null),o??(o=DA(r,f)),u()}return{publish:g,retire:e.retire,disconnect:h,send:d}}function SD(e){const t=e&&typeof e=="object"?{...e}:e;t&&typeof t=="object"&&(delete t.timestamp,delete t.sourceRuntimeId);try{return JSON.stringify(t)}catch{return String(t)}}var ID=e=>!!(e&&typeof e=="object"&&e.sessionCommitReason);function kD(e){const{host:t,kind:r,identity:n,mode:i,send:o}=e,s=ei(t.localName||"pie-shell",()=>!1);let a="";const l=f=>{const{itemId:h,canonicalItemId:g}=n();if(!h)return;o(lD,{itemId:h,session:f});const m=Kb({itemId:h,sessionDetail:f});if(m.intent==="metadata-only"||!m.session)return;const v={itemId:h,canonicalItemId:g||h,session:m.session,...m.sessionCommitReason?{sessionCommitReason:m.sessionCommitReason}:{}};Vl(t,cD,v)},c=f=>{if(i()!=="section"||(f.stopPropagation(),r!=="item"))return;const h=f.detail,g=SD(h);!ID(h)&&g===a||(a=g,l(h))},u=f=>{i()==="section"&&f.stopPropagation();const{itemId:h,canonicalItemId:g,contentKind:m}=n();if(!h)return;const v={itemId:h,canonicalItemId:g||h,contentKind:m,detail:f.detail};o(Px,v)},d=f=>{i()==="section"&&f.stopPropagation();const{itemId:h,canonicalItemId:g,contentKind:m}=n();if(!h)return;const v={itemId:h,canonicalItemId:g||h,contentKind:m,error:f.detail};o(uD,v)};return t.addEventListener("session-changed",c),t.addEventListener("load-complete",u),t.addEventListener("player-error",d),{disconnect:()=>{try{r==="item"&&i()==="section"&&Sf(t,{reason:"teardown",logger:s})}finally{t.removeEventListener("session-changed",c),t.removeEventListener("load-complete",u),t.removeEventListener("player-error",d)}}}}var x0=(e,t)=>{const r=t?.toolTagMap?.[e];if(r===void 0&&!e.includes("-"))throw new Error(`No element tag is mapped for tool "${e}". Install a tag map on the registry via setComponentOverrides({ toolTagMap }) — for the packaged capabilities, PACKAGED_TOOL_TAG_MAP from "@pie-players/pie-default-tool-loaders".`);return bm(r??e,`tool component tag for "${e}"`)},TD=e=>document.createElement(e),$f=(e,t,r,n)=>{const i=x0(e,n),o=n?.toolComponentFactories?.[e];return o?o({toolId:e,tagName:i,context:t,toolbarContext:r}):TD(i)},nS=1e4;function iS(e,t,r){if(!e)return;const n=Symbol.for(`pie.assessmentToolkit.warned.${t}`),i=e;i[n]||(i[n]=!0,console.warn(r))}function ED(e,t){return CD(e.name,e.nameKey,t)}function CD(e,t,r){if(!t||!r)return e;const n=XA(t);if(r.hasKey)return r.hasKey(n)?r.t(n):e;const i=r.t(n);return i===t?e:i}var xD=["assessment","section","item","passage","rubric","element"];function Qh(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`Invalid tool registration: "${t}" must be a non-empty string.`)}var RD=[{pattern:/<script\b/i,reason:"contains a <script> tag"},{pattern:/\son[a-z]+\s*=/i,reason:"contains an inline event handler (on*=) attribute"},{pattern:/javascript:/i,reason:"contains a javascript: URL"},{pattern:/<foreignObject\b/i,reason:"contains a <foreignObject> element"}];function PD(e,t,r){const n=t.trimStart(),i=n.toLowerCase().startsWith("<svg"),o=/^https?:/i.test(n);if(/^data:/i.test(n))throw new Error(`Invalid tool registration "${e}": "${r}" may not be a data: URL.`);if(!(!i&&!o)){for(const{pattern:s,reason:a}of RD)if(s.test(t))throw new Error(`Invalid tool registration "${e}": "${r}" ${a}. Inline SVG icons must not include scriptable content.`)}}function oS(e){Qh(e.toolId,"toolId"),Qh(e.name,"name"),Qh(e.description,"description");const t=e.activation==="region";if((!t||e.icon!==void 0)&&typeof e.icon!="string"&&typeof e.icon!="function")throw new Error(`Invalid tool registration "${e.toolId}": "icon" must be a string or function.`);if(typeof e.icon=="string"&&PD(e.toolId,e.icon,"icon"),!Array.isArray(e.supportedLevels)||e.supportedLevels.length===0)throw new Error(`Invalid tool registration "${e.toolId}": "supportedLevels" must be a non-empty array.`);const r=e.supportedLevels.find(n=>!xD.includes(n));if(r)throw new Error(`Invalid tool registration "${e.toolId}": unsupported level "${r}".`);if(e.activation!==void 0&&e.activation!=="toolbar-toggle"&&e.activation!=="selection-gateway"&&e.activation!=="region")throw new Error(`Invalid tool registration "${e.toolId}": unsupported activation "${String(e.activation)}".`);if(e.surfaces!==void 0&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>typeof n!="string"||n.trim().length===0)))throw new Error(`Invalid tool registration "${e.toolId}": "surfaces" must be an array of non-empty strings.`);if(t&&!e.surfaces?.length)throw new Error(`Invalid tool registration "${e.toolId}": region tools must declare at least one host surface in "surfaces".`);if(t&&typeof e.renderSurface!="function")throw new Error(`Invalid tool registration "${e.toolId}": region tools must implement "renderSurface".`);if(e.resolvesWithoutGrant!==void 0&&typeof e.resolvesWithoutGrant!="boolean")throw new Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" must be a boolean.`);if(e.resolvesWithoutGrant&&!e.requiresAuthoredContent)throw new Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" requires "requiresAuthoredContent".`);if(e.renderSurface!==void 0&&typeof e.renderSurface!="function")throw new Error(`Invalid tool registration "${e.toolId}": "renderSurface" must be a function.`);if(e.renderSurface&&!e.surfaces?.length)throw new Error(`Invalid tool registration "${e.toolId}": "renderSurface" requires at least one entry in "surfaces".`);if(e.singletonScope!==void 0&&e.singletonScope!=="section")throw new Error(`Invalid tool registration "${e.toolId}": unsupported singletonScope "${String(e.singletonScope)}".`);if(e.activation==="selection-gateway"&&e.singletonScope!=="section")throw new Error(`Invalid tool registration "${e.toolId}": selection-gateway tools must declare singletonScope "section".`);if(e.activation!=="region"&&typeof e.isVisibleInContext!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function.`);if(e.isVisibleInContext!==void 0&&typeof e.isVisibleInContext!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function when present.`);if(e.isApplicableToContent!==void 0&&typeof e.isApplicableToContent!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isApplicableToContent" must be a function when present.`);if(e.requiresAuthoredContent!==void 0&&(typeof e.requiresAuthoredContent!="object"||e.requiresAuthoredContent===null||typeof e.requiresAuthoredContent.resolve!="function"))throw new Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" must be an object with a "resolve" function.`);if(e.renderToolbar!==void 0){if(typeof e.renderToolbar!="function")throw new Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}else if(!t)throw new Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}var _D=class{constructor(){T(this,"tools",new Map),T(this,"componentOverrides",{}),T(this,"watchedUndefinedToolElements",new Set),T(this,"moduleLoaders",new Map),T(this,"loadedToolModules",new Set),T(this,"warnedLoaderReplacements",new Set),T(this,"warnedUnregisteredAllowedTools",new Set),T(this,"moduleLoadPromises",new Map),T(this,"changeListeners",new Set)}emitChange(e){for(const t of this.changeListeners)try{t(e)}catch(r){console.warn("[ToolRegistry] change listener failed:",r)}}onRegistryChange(e){this.changeListeners.add(e);let t=!0;return()=>{t&&(t=!1,this.changeListeners.delete(e))}}normalizeToolId(e){return e.trim()}normalizeToolIds(e){return e.map(t=>this.normalizeToolId(t))}register(e){if(oS(e),this.tools.has(e.toolId))throw new Error(`Tool '${e.toolId}' is already registered`);this.tools.set(e.toolId,e),this.emitChange({kind:"register",toolIds:[e.toolId]})}override(e){if(oS(e),!this.tools.has(e.toolId))throw new Error(`Cannot override non-existent tool '${e.toolId}'`);this.tools.set(e.toolId,e),this.emitChange({kind:"override",toolIds:[e.toolId]})}unregister(e){this.tools.has(e)&&(this.tools.delete(e),this.emitChange({kind:"unregister",toolIds:[e]}))}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getAllToolIds(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}getToolsByLevel(e){return this.getAllTools().filter(t=>t.supportedLevels.includes(e))}getToolActivation(e){return this.get(e)?.activation||"toolbar-toggle"}getToolSingletonScope(e){return this.get(e)?.singletonScope||null}getToolsBySurface(e){return e?this.getAllTools().filter(t=>typeof t.renderSurface=="function"&&t.surfaces?.includes(e)):[]}getContentDependentSupportIds(){return this.getAllTools().filter(e=>e.requiresAuthoredContent).map(e=>e.toolId).sort()}filterToolIdsByActivation(e,t){return e.filter(r=>this.getToolActivation(r)===t)}filterVisibleInContext(e,t){const r=[];for(const n of e){const i=this.get(n);if(!i){this.warnedUnregisteredAllowedTools.has(n)||(this.warnedUnregisteredAllowedTools.add(n),console.warn(`Tool '${n}' is allowed but not registered`));continue}if(i.supportedLevels.includes(t.level))try{i.isVisibleInContext?.(t)&&r.push(i)}catch(o){console.error(`Error evaluating visibility for tool '${n}':`,o)}}return r}isApplicableToAnyContext(e,t){const r=this.get(e);return!r?.isApplicableToContent||t.length===0?!0:t.some(n=>{try{return r.isApplicableToContent?.(n)??!0}catch(i){return console.error(`Error evaluating applicability for tool '${e}':`,i),!0}})}getToolMetadata(){return this.getAllTools().map(e=>({toolId:e.toolId,name:e.name,description:e.description,supportedLevels:e.supportedLevels,activation:e.activation||"toolbar-toggle",singletonScope:e.singletonScope||null,surfaces:e.surfaces||[],requiresAuthoredContent:!!e.requiresAuthoredContent,contentDependencyDescription:e.requiresAuthoredContent?.description??null}))}clear(){const e=this.getAllToolIds();e.length!==0&&(this.tools.clear(),this.emitChange({kind:"clear",toolIds:e}))}setComponentOverrides(e){this.componentOverrides!==e&&(this.componentOverrides=e,this.emitChange({kind:"component-overrides",toolIds:[]}))}setToolModuleLoaders(e){const t=Object.entries(e).filter(n=>n[1]!==void 0);for(const[n,i]of t)if(Qh(n,"tool module loader id"),typeof i!="function")throw new Error(`Invalid tool module loader for "${n}": expected a function.`);const r=[];for(const[n,i]of t)if(this.moduleLoaders.get(n)!==i){if(this.loadedToolModules.has(n)||this.moduleLoadPromises.has(n)){this.warnLoaderReplacedAfterLoad(n);continue}this.moduleLoaders.set(n,i),r.push(n)}r.length>0&&this.emitChange({kind:"module-loaders",toolIds:r})}warnLoaderReplacedAfterLoad(e){this.warnedLoaderReplacements.has(e)||(this.warnedLoaderReplacements.add(e),console.warn(`[ToolRegistry] Ignored a new module loader for "${e}": its module already loaded, so the elements it defines stay in place. Register loaders before the tool first renders.`))}async ensureToolModuleLoaded(e){if(this.loadedToolModules.has(e))return;const t=this.moduleLoadPromises.get(e);if(t){await t;return}const r=this.moduleLoaders.get(e);if(!r){this.watchUndefinedToolElement(e);return}const n=(async()=>{await r(),this.loadedToolModules.add(e),this.warnIfLoadedToolElementUndefined(e)})();this.moduleLoadPromises.set(e,n);try{await n}finally{this.moduleLoadPromises.delete(e)}}undefinedToolElementTag(e){if(typeof customElements>"u"||typeof document>"u")return null;const t=this.componentOverrides;if(t.toolComponentFactories?.[e])return null;let r;try{r=x0(e,t)}catch{return null}return customElements.get(r)?null:r}warnIfLoadedToolElementUndefined(e){const t=this.undefinedToolElementTag(e);t&&iS(document,`loadedToolElementUndefined.${e}.${t}`,`[ToolRegistry] Tool "${e}" renders <${t}>, but its module loader finished without defining it, so the tool renders blank. The tag map and the loader disagree: map "${e}" to the tag its loader defines, or register a loader that defines <${t}>. Reported once per page.`)}watchUndefinedToolElement(e){if(this.watchedUndefinedToolElements.has(e))return;const t=this.undefinedToolElementTag(e);if(!t)return;this.watchedUndefinedToolElements.add(e);const r=document,n=setTimeout(()=>{customElements.get(t)||iS(r,`undefinedToolElement.${e}`,`[ToolRegistry] Tool "${e}" renders <${t}>, which is still undefined after ${nS/1e3} s, and its registry has no module loader for it. Pass toolModuleLoaders to createPackagedToolRegistry (DEFAULT_TOOL_MODULE_LOADERS from @pie-players/pie-default-tool-loaders loads the stock tools), register one with setToolModuleLoaders, or import the tool's package before it renders. Reported once per page.`)},nS);customElements.whenDefined(t).then(()=>clearTimeout(n))}async ensureToolModulesLoaded(e){const t=await Promise.allSettled(e.map(n=>this.ensureToolModuleLoaded(n))),r=new Map;return t.forEach((n,i)=>{n.status==="rejected"&&r.set(e[i],n.reason)}),r}isToolModuleLoaded(e){return this.loadedToolModules.has(e)}renderForToolbar(e,t,r){const n=this.get(e);if(!n)throw new Error(`Tool '${e}' is not registered`);if(typeof n.renderToolbar!="function")throw new Error(`Tool '${e}' has activation "${n.activation||"toolbar-toggle"}" and renders into a host surface, not a toolbar. Remove it from toolbar placement.`);const i={...r,componentOverrides:{...this.componentOverrides||{},...r.componentOverrides||{}}};return n.renderToolbar(t,i)}renderForSurface(e,t){const r=this.get(e);if(!r)throw new Error(`Tool '${e}' is not registered`);if(typeof r.renderSurface!="function")throw new Error(`Tool '${e}' does not render into a host surface. Surface capabilities declare "surfaces" and implement "renderSurface".`);return r.renderSurface({...t,componentOverrides:{...this.componentOverrides||{},...t.componentOverrides||{}}})}};function $x(e){return e.level==="item"}function AD(e){return e.level==="passage"}function $D(e){return e.level==="rubric"}function Mx(e){return e.level==="element"}var MD=e=>e.replace(/<[^>]*>/g," ").trim();function Fg(e){return Array.isArray(e)?e:e&&typeof e=="object"?Object.values(e):[]}function Hg(e,t){if(!(!e||typeof e!="object")){for(const r of Object.values(e))if(typeof r=="string"&&t(r),Array.isArray(r)){for(const n of r)if(n&&typeof n=="object")for(const i of Object.values(n))typeof i=="string"&&t(i)}}}function sS(e,t){if(!(!e||typeof e!="object"))for(const r of Object.values(e))typeof r=="string"&&t(r)}function Ox(e,t){const r=[],n=o=>{r.push(t(o))},i=()=>r.filter(Boolean).join(" ").trim();if(Mx(e)){const o=e.item.config;if(!o)return"";const s=o.elements?.[e.elementId];return typeof s=="string"&&n(s),Hg(Fg(o.models).find(a=>!!a&&typeof a=="object"&&a.id===e.elementId),n),i()}if($x(e)){const o=e.item?.config;if(!o)return"";typeof o.markup=="string"&&n(o.markup),sS(o.elements,n);for(const s of Fg(o.models))Hg(s,n);return i()}if(AD(e)){const o=e.passage?.config;if(!o)return"";for(const s of["markup","content","prompt"]){const a=o[s];typeof a=="string"&&n(a)}sS(o.elements,n);for(const s of Fg(o.models))Hg(s,n);return i()}if($D(e)){const o=e.rubricBlock;return o.passage?.config?t(o.passage.config.markup||""):t(o.content||"")}return""}function R0(e){return Ox(e,MD)}function OD(e){return Ox(e,t=>t)}var LD=new Set(["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr"]),ND=/\b[A-Z][A-Za-z]*\d*(?:[A-Z][A-Za-z]*\d*)*\b/g,Ug=/([A-Z][a-z]?)(\d*)/g;function DD(e){for(const t of e.match(ND)??[]){Ug.lastIndex=0;let r=0,n=!1,i=0,o=!0,s=Ug.exec(t);for(;s!==null&&s[0]!=="";){if(!LD.has(s[1])){o=!1;break}r+=1,s[2]&&(n=!0),i+=s[0].length,s=Ug.exec(t)}if(o&&i===t.length&&(r>1||n))return!0}return!1}function Gm(e){const t=OD(e);if([/<math[>\s]/i,/\\\[([^\]]+)\\\]/,/\$\$[^$]+\$\$/,/\\\(/].some(n=>n.test(t)))return!0;const r=R0(e);return[/[≤≥≠±×÷∑∫√∞π]/,/\d+\s*[+\-*/×÷=]\s*\d+/,/\d\s*[<>]\s*\d/,/\b\d+\s*\/\s*\d+\b/,/\b\d+(?:\.\d+)?\s*%/,/\^\s*\d/].some(n=>n.test(r))}var aS=new Set(["multiple-choice","inline-choice","select-text","ebsr"]),jD=e=>e.toLowerCase().replace(/--version-[0-9a-z-]+$/,"").replace(/^pie-(element-)?/,"");function lS(e,t){if(aS.has(jD(e)))return!0;if(!t||typeof t!="object")return!1;const r=t,n=r[e]??r[e.replace(/--version-[0-9A-Za-z-]+$/,"")];if(typeof n!="string")return!1;const i=n.match(/^@pie-element\/([^@]+)/)?.[1];return!!i&&aS.has(i)}function cS(e){if(Mx(e)){const t=e.item.config;if(!t?.models)return!1;const r=(Array.isArray(t.models)?t.models:Object.values(t.models)).find(n=>n&&typeof n=="object"&&n.id===e.elementId);return r?lS(r.element||"",t.elements):!1}if($x(e)){const t=e.item.config,r=t?.models;return(Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]).some(n=>{if(!n||typeof n!="object")return!1;const i=n.element||"";return i?lS(i,t?.elements):Array.isArray(n.choices)&&n.choices.length>0})}return!1}function Mf(e){return R0(e).trim().length>=10}function zD(e){const t=R0(e);return DD(t)||/[A-Z][a-z]?[\u2080-\u2089]/.test(t)?!0:[/chemistry|chemical|molecule|compound|periodic\s+table/i,/\bchemical\s+element\b|\belement\s+symbol\b/i,/biology|organism|\bDNA\b|\bRNA\b|protein|photosynthesis|ecosystem/i,/physics|\bforce\b|\benergy\b|velocity|acceleration|momentum/i].some(r=>r.test(t))}function P0(e){return{kind:e.kind,severity:e.severity??"error",source:e.source,message:e.message,details:[...e.details||[]],recoverable:e.recoverable===!0,scope:e.scope??"runtime",cause:e.cause}}var BD=/^[a-z][a-z0-9+.-]*:/i,FD=new Set(["http:","https:","data:","blob:"]);function HD(e){return e!==void 0&&e!==1}function UD(e){if(typeof e!="string")return!1;const t=e.trim();if(!t)return!1;if(t.startsWith("//")||!BD.test(t))return!0;const r=t.slice(0,t.indexOf(":")+1).toLowerCase();return FD.has(r)}function qD(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(!UD(n.src))continue;const i={src:n.src.trim()};typeof n.type=="string"&&n.type.trim()&&(i.type=n.type.trim()),Number.isFinite(n.width)&&(i.width=n.width),Number.isFinite(n.height)&&(i.height=n.height),!t.some(o=>o.src===i.src)&&t.push(i)}return t}function Lx(e){if(!e||typeof e!="object")return;const t=e,r=Number(t.startSeconds);if(!Number.isFinite(r)||r<0)return;const n=Number(t.endSeconds);return!Number.isFinite(n)||n<=r?{startSeconds:r}:{startSeconds:r,endSeconds:n}}function WD(e){if(typeof e=="string")return e.trim()||void 0}var VD=100,GD=1;function YD(e,t,r){if(!t)return()=>{};const{startSeconds:n,endSeconds:i}=t;let o;n>0&&(o=()=>{e.currentTime<n&&(e.currentTime=n)},e.readyState>=GD?o():e.addEventListener("loadedmetadata",o));let s,a;return i!==void 0&&(s=()=>{e.currentTime>=i&&r()},e.addEventListener("timeupdate",s),a=setInterval(()=>{e.paused||s?.()},VD)),()=>{o&&e.removeEventListener("loadedmetadata",o),s&&e.removeEventListener("timeupdate",s),a!==void 0&&clearInterval(a)}}function KD(e,t){if(!t||e.includes("#"))return e;const r=t.endSeconds!==void 0?`,${t.endSeconds}`:"";return`${e}#t=${t.startSeconds}${r}`}var XD=e=>e.trim().replace(/\s+/g," "),JD=new Set(["computer-read-aloud","all"]),gK=new Set([...JD,"screen-reader"]),QD=/^\s*<speak[\s/>]/i,ZD=e=>QD.test(e),ej=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),uS=new Set(["audio","phoneme"]),Nx=e=>e.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),Zh=(e,t,r)=>{for(let n=0;n<t.length;n++)e.push({char:t[n],rawOffset:r===null?null:r+n})},tj=(e,t,r)=>{const n=t.slice(r).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);return n?(Zh(e,Nx(n[0]),r),n[0].length):0},dS=e=>{e.push({char:" ",rawOffset:null})},rj=e=>{const t=new Map,r=[];let n=!0;for(const i of e){if(/\s/.test(i.char)){!n&&r.length>0&&(r.push(" "),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1)),n=!0;continue}r.push(i.char),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1),n=!1}for(;r.length>0&&r[r.length-1]===" ";)r.pop();for(const[i,o]of t)o>=r.length&&t.delete(i);return{text:r.join(""),rawToSpokenOffsetMap:t}},nj=e=>e.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||"",ij=(e,t)=>{const r=new RegExp(`${t}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),n=e.match(r);return Nx(n?.[2]??n?.[3]??"")||null},oj=e=>{const t=[];let r=!1,n=!1,i=0;for(;i<e.length;){const s=e[i];if(s!=="<"){if(s==="&"){const f=tj(t,e,i);if(f>0){i+=f;continue}}Zh(t,s,i),i++;continue}const a=e.indexOf(">",i+1);if(a<0){Zh(t,s,i),i++;continue}n=!0;const l=e.slice(i,a+1),c=nj(l),u=/^<\s*\//.test(l),d=/\/\s*>$/.test(l);if(!u&&c==="sub"){const f=ij(l,"alias");if(!f){r=!0,i=a+1;continue}Zh(t,f,null);const h=e.toLowerCase().indexOf("</sub>",a+1);i=h>=0?h+6:a+1;continue}if(!u&&c==="break"){dS(t),i=a+1;continue}if(!u&&uS.has(c)&&(r=!0,d)){i=a+1;continue}c&&!ej.has(c)&&!uS.has(c)&&c!=="break"&&c!=="sub"&&(r=!0),!u&&(c==="p"||c==="s")&&dS(t),i=a+1}const o=rj(t);return{spokenText:XD(o.text),rawToSpokenOffsetMap:o.rawToSpokenOffsetMap,unsupportedSemantic:r,hasMarkup:n}},sj=(e,t)=>{const r=t?.useSentenceSegmenter!==!1;try{if(!r)throw new Error("Segmenter disabled by policy");const s=globalThis.Intl?.Segmenter;if(typeof s=="function"){const a=new s(t?.locale,{granularity:"sentence"}),l=Array.from(a.segment(e)).map(c=>({text:c.segment,offset:c.index})).filter(c=>c.text.trim().length>0);if(l.length>0)return l}}catch{}const n=e.match(/[^.!?]+(?:[.!?]+|$)/g)||[e],i=[];let o=0;for(const s of n){const a=e.indexOf(s,o);a!==-1&&(i.push({text:s,offset:a}),o=a+s.length)}return i.length>0?i:[{text:e,offset:0}]},fS=ei("browser-tts-provider",xu),hS=5e3,Dx=2e3,pS=e=>{if(!ZD(e))return{text:e,sourceOffset:i=>i};const{spokenText:t,rawToSpokenOffsetMap:r}=oj(e),n=[];for(const[i,o]of r){const s=n[o];(s===void 0||i<s)&&(n[o]=i)}return{text:t,sourceOffset:i=>{for(let o=i;o>=0;o--){const s=n[o];if(s!==void 0)return s}return 0}}},ky=e=>String(e||"").trim().toLowerCase(),aj=()=>{const e=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return ky(e||"en-US")},lj=(e,t)=>{const r=ky(t)||aj(),n=r.split("-")[0]||"en",i=ky(e.lang);return i===r||i.startsWith(`${n}-`)},cj=(e,t,r)=>{if(t)return e.find(o=>o.voiceURI===t)||e.find(o=>o.name===t)||null;const n=o=>lj(o,r),i=[o=>o.localService&&n(o),o=>o.default&&n(o),o=>n(o),o=>o.localService,o=>o.default];for(const o of i){const s=e.find(o);if(s)return s}return e[0]||null},uj=(e,t,r=()=>!0)=>{if(e.getVoices().length>0)return Promise.resolve(!0);const n=typeof e.addEventListener=="function"&&typeof e.removeEventListener=="function";return!n&&!("onvoiceschanged"in e)?Promise.resolve(!1):new Promise(i=>{const o=n?null:e.onvoiceschanged;let s=!1;const a=f=>{s||(s=!0,clearTimeout(d),n?e.removeEventListener("voiceschanged",c):e.onvoiceschanged===u&&(e.onvoiceschanged=o),i(f))},l=()=>{r()?e.getVoices().length>0&&a(!0):a(!1)},c=()=>l(),u=f=>{try{o?.call(e,f)}finally{l()}},d=setTimeout(()=>a(!1),t);n?e.addEventListener("voiceschanged",c):e.onvoiceschanged=u,l()})},dj=e=>!e.default,fj=class{constructor(){T(this,"providerId","browser"),T(this,"providerName","Browser Speech Synthesis"),T(this,"version","1.0.0")}async initialize(e){if(typeof window>"u")throw new Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw new Error("Browser does not support Speech Synthesis API");return typeof e.voice=="string"&&e.voice.trim()&&await uj(window.speechSynthesis,Dx),new hj(e)}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,defaultHighlightMode:"sentence",supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}},hj=class{constructor(e){T(this,"utterance",null),T(this,"config",null),T(this,"_isPlaying",!1),T(this,"_isPaused",!1),T(this,"speakRunId",0),T(this,"activeRunId",null),T(this,"releasePauseHold",null),T(this,"settlePendingChunk",null),T(this,"settlePendingGap",null),T(this,"onPlaybackStart",void 0),T(this,"onWordBoundary",void 0),this.config=e}async waitWhilePaused(e){for(;this._isPaused&&e===this.speakRunId;)await new Promise(t=>{this.releasePauseHold=t});return e===this.speakRunId}releaseHold(){const e=this.releasePauseHold;this.releasePauseHold=null,e?.()}resolveBrowserVoice(){const e=typeof this.config?.voice=="string"?this.config.voice.trim():"",t=speechSynthesis.getVoices();if(e&&t.length===0)throw new Error(`Configured browser voice "${e}" could not be resolved because the browser did not publish its voice inventory within ${Dx/1e3} seconds.`);const r=cj(t,e||void 0,this.getContentLocale());if(e&&!r)throw new Error(`Configured browser voice "${e}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return r}async speak(e){if(!this.config)throw new Error("TTS not initialized");this.stop();const t=this.speakRunId;this.activeRunId=t;try{const r=this.resolveBrowserVoice(),n=pS(e),i=this.splitIntoChunks(n.text);for(const o of i)if(this._isPaused&&!await this.waitWhilePaused(t)||!await this.speakChunk(o.text,o.offset,t,r,n.sourceOffset))break}finally{this.activeRunId===t&&(this.activeRunId=null)}}async speakSegments(e){if(!this.config)throw new Error("TTS not initialized");this.stop();const t=this.speakRunId;this.activeRunId=t;try{const r=this.resolveBrowserVoice();for(const n of e){if(t!==this.speakRunId)break;const i=pS(n.text),o=this.splitIntoChunks(i.text);for(const a of o)if(this._isPaused&&!await this.waitWhilePaused(t)||!await this.speakChunk(a.text,a.offset,t,r,l=>n.startOffset+i.sourceOffset(l)))break;const s=Math.max(0,Number(n.pauseMsAfter||0));if(s>0&&t===this.speakRunId&&!await this.waitForPause(s,t))break}}finally{this.activeRunId===t&&(this.activeRunId=null)}}async waitForPause(e,t){return await new Promise(r=>{const n=()=>{clearTimeout(i),this.settlePendingGap===n&&(this.settlePendingGap=null),r()},i=setTimeout(n,e);this.settlePendingGap=n}),t===this.speakRunId}splitIntoChunks(e){if(e.length<=260)return[{text:e,offset:0}];const r=this.segmentSentences(e),n=[];let i="",o=0;for(const s of r){const a=s.text.trim();if(!a)continue;const l=s.text.search(/\S/),c=s.offset+(l===-1?0:l);if(!i){i=a,o=c;continue}const u=`${i} ${a}`;u.length<=260?i=u:(n.push({text:i,offset:o}),i=a,o=c)}return i&&n.push({text:i,offset:o}),n.length?n:[{text:e,offset:0}]}getContentLocale(){const e=this.config?.providerOptions?.contentLanguage;return typeof e=="string"&&e.trim()?e.trim():void 0}getSegmentationPolicy(){const e=this.config?.providerOptions||{},t=e.segmenter||{},r=t.mode!=="regexOnly";return{useSentenceSegmenter:r,useWordSegmenter:r,locale:typeof t.locale=="string"&&t.locale.trim().length>0?t.locale:typeof e.locale=="string"&&e.locale.trim().length>0?e.locale:void 0}}segmentSentences(e){const t=this.getSegmentationPolicy();return sj(e,{locale:t.locale,useSentenceSegmenter:t.useSentenceSegmenter})}inferWordLength(e,t){const r=Math.max(0,Math.min(t,Math.max(0,e.length-1)));return e.slice(r).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(e,t,r,n,i){return new Promise((o,s)=>{if(r!==this.speakRunId){o(!1);return}const a=new SpeechSynthesisUtterance(e);this.utterance=a;const l=this.getContentLocale();l&&(a.lang=l),n&&dj(n)&&(a.voice=n),this.config?.rate&&(a.rate=this.config.rate),this.config?.pitch&&(a.pitch=this.config.pitch);let c=!1,u=!1,d=null,f=null;const h=()=>{this.utterance===a&&(this.utterance=null)},g=()=>{d!==null&&(clearTimeout(d),d=null)},m=()=>{a.onstart=null,a.onend=null,a.onerror=null,a.onpause=null,a.onresume=null,a.onboundary=null},v=(I,C)=>{u||(u=!0,g(),m(),h(),f&&this.settlePendingChunk===f&&(this.settlePendingChunk=null),r===this.speakRunId&&(this._isPlaying=!1),C?s(C):o(I))},b=I=>new Error(I==="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 ${hS/1e3} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);f=()=>v(!1),this.settlePendingChunk=f,a.onstart=()=>{if(r!==this.speakRunId){v(!1);return}c=!0,g(),this._isPlaying=!0,this._isPaused&&speechSynthesis.pause();try{this.onPlaybackStart?.()}catch(I){console.error("Browser TTS playback-start callback failed",I)}},a.onend=()=>{if(r!==this.speakRunId){v(!1);return}if(!c){v(!1,b("ended"));return}v(!0)},a.onerror=I=>{if(r!==this.speakRunId){v(!1);return}if(I.error==="interrupted"||I.error==="canceled"){v(!1);return}v(!1,new Error(`Speech synthesis error: ${I.error}`))},a.onpause=()=>{r===this.speakRunId&&(this._isPaused=!0)},a.onresume=()=>{r===this.speakRunId&&(this._isPaused=!1)},a.onboundary=I=>{if(r!==this.speakRunId||(fS.debug(`boundary event: ${I.name}, charIndex ${I.charIndex}, charLength ${I.charLength}`),I.name!=="word"||!this.onWordBoundary))return;const C=Math.max(0,Math.min(I.charIndex,Math.max(0,e.length-1))),x=Number(I.charLength||0),$=this.inferWordLength(e,C),P=Number.isFinite(x)&&x>0&&x<=80&&C+x<=e.length?x:$,L=e.substring(C,Math.min(e.length,C+P)).trim(),J=t+C,V=i(J),Y=i(J+P-1)+1-V;fS.debug(`word boundary "${L}" at ${V}`),this.onWordBoundary(L,V,Y)},d=setTimeout(()=>{u||c||r!==this.speakRunId||(v(!1,b("timedOut")),speechSynthesis.cancel())},hS);try{speechSynthesis.speak(a)}catch(I){v(!1,I instanceof Error?I:new Error("Browser speech synthesis failed to queue speech"))}})}pause(){this._isPaused||(this._isPlaying?(speechSynthesis.pause(),this._isPaused=!0):this.activeRunId===this.speakRunId&&(this._isPaused=!0))}resume(){this._isPaused&&(this._isPaused=!1,this._isPlaying&&speechSynthesis.resume(),this.releaseHold())}stop(){const e=this.utterance,t=this._isPlaying||e!==null;this.speakRunId+=1,this.activeRunId=null,this.settlePendingChunk?.(),this.settlePendingGap?.(),t&&speechSynthesis.cancel(),this.utterance=null,this._isPlaying=!1,this._isPaused=!1,this.releaseHold()}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(e){this.config||(this.config={}),e.rate!==void 0&&(this.config.rate=e.rate),e.pitch!==void 0&&(this.config.pitch=e.pitch),e.voice!==void 0&&(this.config.voice=e.voice),e.providerOptions!==void 0&&(this.config.providerOptions={...this.config.providerOptions||{},...e.providerOptions||{}})}},yh=ei("tts-tool-provider",xu);function pj(e,t){return{providerId:e.providerId,providerName:e.providerName,version:e.version,initialize:r=>{const n=r,i={...n,...t,headers:{...n.headers,...t.headers},providerOptions:{...n.providerOptions,...t.providerOptions}};return e.initialize(i)},getCapabilities:()=>e.getCapabilities(),destroy:()=>e.destroy()}}var mj=class{async emitTelemetry(e,t){try{await this.config?.onTelemetry?.(e,t)}catch(r){console.warn("[TTSToolProvider] telemetry callback failed:",r)}}constructor(e="browser",t={}){T(this,"providerName","Text-to-Speech"),T(this,"category","tts"),T(this,"version","1.0"),T(this,"requiresAuth",void 0),T(this,"backend",void 0),T(this,"ttsProvider",null),T(this,"config",null),T(this,"loadServerProvider",void 0),this.backend=e,this.requiresAuth=e!=="browser",this.loadServerProvider=t.loadServerProvider}async initialize(e){if(this.ttsProvider){console.warn("[TTSToolProvider] Already initialized, skipping reinitialization");return}switch(this.config=e,this.backend){case"browser":await this._initializeBrowserTTS(e);break;case"server":await this._initializeServerTTS(e);break;default:throw new Error(`[TTSToolProvider] Unknown backend: ${this.backend}`)}yh.debug(`initialized (backend: ${this.backend})`)}async _initializeBrowserTTS(e){if(typeof window>"u"||!("speechSynthesis"in window))throw new Error("[TTSToolProvider] Browser TTS not supported (Web Speech API not available)");this.ttsProvider=new fj,yh.debug("browser TTS initialized (Web Speech API)")}async _initializeServerTTS(e){if(!e.apiEndpoint)throw new Error("[TTSToolProvider] apiEndpoint required for server-based TTS backends");const t=this.loadServerProvider;if(!t)throw new Error("[TTSToolProvider] server-based TTS backends need the loadServerProvider option");const r=e.provider||this.backend,n=Date.now();await this.emitTelemetry("pie-tool-library-load-start",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:r});const i=await(async()=>{try{const a=await t();return await this.emitTelemetry("pie-tool-library-load-success",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:r,duration:Date.now()-n}),a}catch(a){throw await this.emitTelemetry("pie-tool-library-load-error",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:r,duration:Date.now()-n,errorType:"ToolLibraryLoadError",message:a instanceof Error?a.message:String(a)}),a}})(),{onTelemetry:o,...s}=e;this.ttsProvider=pj(new i,s),yh.debug(`server TTS initialized (provider: ${r})`)}async createInstance(e){if(!this.ttsProvider)throw new Error("[TTSToolProvider] Provider not initialized. Call initialize() first.");return this.ttsProvider}getCapabilities(){const e=this.backend==="browser",t=this.ttsProvider?.getCapabilities();return{supportsOffline:e,requiresAuth:!e,maxInstances:1,features:{wordBoundary:t?.supportsWordBoundary??!1,pause:t?.supportsPause??!1,resume:t?.supportsResume??!1,rateControl:t?.supportsRateControl??!1,pitchControl:t?.supportsPitchControl??!1,voiceSelection:t?.supportsVoiceSelection??!1}}}isReady(){return this.ttsProvider!==null}destroy(){this.ttsProvider&&(this.ttsProvider.destroy(),this.ttsProvider=null),this.config=null,yh.debug("destroyed")}};function gj(e){return e?.rule==="host-blocked"||e?.rule==="host-allowlist"}var vj=1;function jx(){return new Date().toISOString()}function yj(e){const t=jx();return{version:vj,testAttemptSessionIdentifier:e.testAttemptSessionIdentifier,assessmentId:e.assessmentId,startedAt:t,updatedAt:t,navigationState:{currentItemIndex:-1,visitedItemIdentifiers:[]},realization:{seed:e.seed,itemIdentifiers:e.itemIdentifiers},itemSessions:{}}}function bj(e,t){if(!t)return e;const r=new Set(e.navigationState.visitedItemIdentifiers||[]);return r.add(t),{...e,navigationState:{...e.navigationState,visitedItemIdentifiers:Array.from(r)}}}function wj(e,t){return{...e,navigationState:{...e.navigationState,currentItemIndex:t.currentItemIndex,currentSectionIdentifier:t.currentSectionIdentifier}}}function Sj(e,t){const{itemIdentifier:r,pieSessionId:n,isCompleted:i}=t;if(!r||!n)return e;const o=jx(),s=e.itemSessions[r],a=s&&s.pieSessionId&&s.pieSessionId!==n?s.attemptCount+1:s?s.attemptCount:1,l=!!(i??s?.isCompleted),c={itemIdentifier:r,pieSessionId:n,attemptCount:a,isCompleted:l,startedAt:s?.startedAt||o,updatedAt:o,completedAt:l?s?.completedAt||o:void 0,session:t.session??s?.session};return{...e,itemSessions:{...e.itemSessions,[r]:c}}}function Ty(e){return Object.entries(e.itemSessions).reduce((t,[r,n])=>(n.session&&(t[r]=n.session),t),{})}var bh={enabled:!1,maxTries:1,feedback:"correctness",revealOn:"on-try"};function mS(e){if(e==="unlimited")return"unlimited";if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.trunc(e);return t>=1?t:void 0}function gS(e){return e==="none"||e==="correctness"||e==="solution"?e:void 0}function vS(e){return e==="on-try"||e==="on-final-try"?e:void 0}function Ij(e,t){const r=typeof t?.enabled=="boolean"?t.enabled:typeof e?.enabled=="boolean"?e.enabled:bh.enabled,n=mS(t?.maxTries)??mS(e?.maxTries)??bh.maxTries,i=gS(t?.feedback)??gS(e?.feedback)??bh.feedback,o=vS(t?.revealOn)??vS(e?.revealOn)??bh.revealOn;return{enabled:r,maxTries:n,feedback:i,revealOn:o==="on-final-try"&&n==="unlimited"?"on-try":o}}function kj(e){const t={};for(const r of e.items)r?.identifier&&(t[r.identifier]=Ij(e.sectionPolicy,r.policy));return t}function Tj(e){return Object.values(e).some(t=>t.enabled)}var Ej=1e-9;function Cj(e){return!!e&&typeof e.score=="number"&&Number.isFinite(e.score)}function yS(e){const t=e.max;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}function bS(e){const t=e.filter(r=>!!r&&typeof r=="object");return t.length>0?t:void 0}function xj(e,t){return t<=0?"unknown":e+Ej>=t?"correct":e<=0?"incorrect":"partial"}function Rj(e){const t=Array.isArray(e)?e:[],r=t.filter(Cj),n=t.length;if(r.length===0)return{correctness:"unknown",scoredElementCount:0,totalElementCount:n,elementOutcomes:bS(t)};let i,o;if(r.length===1){const a=r[0];o=yS(a),i=a.score}else o=1,i=r.reduce((a,l)=>a+l.score/yS(l),0)/r.length;const s=Math.min(Math.max(i,0),o);return{correctness:xj(s,o),points:s,max:o,scoredElementCount:r.length,totalElementCount:n,elementOutcomes:bS(t)}}function zx(e){return{version:1,itemIdentifier:e,tryCount:0,revealed:!1}}function _0(e,t){return e.maxTries==="unlimited"?"unlimited":Math.max(0,e.maxTries-t)}function A0(e){return e==="unlimited"||e>0}function Pj(e,t){return e.feedback==="none"?!1:e.revealOn==="on-try"||e.maxTries==="unlimited"?!0:t>=e.maxTries}function _j(e){const t=e.state??zx(e.itemIdentifier);if(!e.policy.enabled)return t;const r=_0(e.policy,t.tryCount);if(t.revealed||!A0(r))return t;const n=t.tryCount+1;return{...t,version:1,itemIdentifier:e.itemIdentifier,tryCount:n,revealed:Pj(e.policy,n),lastOutcome:e.outcome,firstCorrectTry:t.firstCorrectTry??(e.outcome.correctness==="correct"?n:void 0)}}function Aj(e){const t=e.state;return!t||!e.policy.enabled||!t.revealed||!A0(_0(e.policy,t.tryCount))?t:{...t,revealed:!1,revealOverride:void 0}}function $j(e){const t=e.state??zx(e.itemIdentifier);return!e.policy.enabled||t.revealed&&t.revealOverride===e.feedback?t:{...t,revealed:!0,revealOverride:e.feedback}}function Mj(e){const t=e.state;return!t||!e.policy.enabled||!t.revealed&&!t.revealOverride?t:{...t,revealed:!1,revealOverride:void 0}}function Oj(e,t,r){const n=r??e.feedback;if(!(!t||n==="none"))return{mode:"evaluate",role:n==="solution"?"instructor":"student"}}function Lj(e){const{policy:t}=e,r=e.state?.tryCount??0,n=e.state?.revealed===!0,i=_0(t,r),o=t.enabled&&A0(i);return{enabled:t.enabled,tryCount:r,triesRemaining:i,canCheck:o&&!n,canRetry:o&&n,revealed:n,envOverride:t.enabled?Oj(t,n,e.state?.revealOverride):void 0,lastOutcome:e.state?.lastOutcome}}function Nj(e){const t=e.itemIdentifiers??[],r=t.length;let n=0,i=0,o=0,s=0;for(const l of t){const c=e.states?.[l];c&&(c.tryCount>0&&(o+=1),c.lastOutcome?.correctness==="unknown"&&(n+=1),typeof c.firstCorrectTry=="number"&&(i+=1,s+=c.firstCorrectTry))}const a=Math.max(0,r-n);return{version:1,totalItems:r,scorableItems:a,masteredItems:i,triedItems:o,averageTriesToMastery:i>0?s/i:void 0,complete:a>0&&i===a}}var Dj=["correct","partial","incorrect","unknown"];function Ey(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Xp(e){const t=Ey(e);if(t===void 0)return;const r=Math.trunc(t);return r>=0?r:void 0}function jj(e){if(!e||typeof e!="object")return;const t=e,r=Dj.find(n=>n===t.correctness);if(r)return{correctness:r,points:Ey(t.points),max:Ey(t.max),scoredElementCount:Xp(t.scoredElementCount)??0,totalElementCount:Xp(t.totalElementCount)??0,elementOutcomes:zj(t.elementOutcomes)}}function zj(e){if(!Array.isArray(e))return;const t=e.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r));return t.length>0?t:void 0}function Bj(e){return e==="correctness"||e==="solution"||e==="none"?e:void 0}function Fj(e,t){if(!t||typeof t!="object")return null;const r=t;if(r.version!==1)return null;const n=Xp(r.tryCount);if(n===void 0)return null;const i=Xp(r.firstCorrectTry);return{version:1,itemIdentifier:e,tryCount:n,revealed:r.revealed===!0,lastOutcome:jj(r.lastOutcome),firstCorrectTry:i!==void 0&&i>=1?i:void 0,revealOverride:Bj(r.revealOverride)}}function Hj(e){return{version:1,items:{...e}}}function Uj(e){const{slice:t}=e;if(!t||typeof t!="object")return null;const r=t;if(r.version!==1||!r.items||typeof r.items!="object")return null;const n=new Set(e.allowedItemIdentifiers??[]),i={};for(const[o,s]of Object.entries(r.items)){if(!n.has(o))continue;const a=Fj(o,s);a&&(i[o]=a)}return i}var qj=Object.freeze({id:"",data:Object.freeze([])}),$0={section:null,assessmentItemRefs:[],passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],currentItemIndex:0,currentItem:null,isPageMode:!1,itemSessionsByItemId:{},testAttemptSession:null,itemViewModels:[],formative:null};function Bx(e,t){return M0(e,t)?.canonicalItemId||""}function Wj(e,t){return M0(e,t)?.settings??null}function Fx(e,t){return M0(e,t)?.session}function Vj(e,t){return Fx(e,t)||qj}function M0(e,t){const r=t.id||"";if(r)return e.itemViewModels.find(n=>n.itemId===r||n.canonicalItemId===r||n.item?.id===r)}if(typeof window<"u"){var wS,SS;((wS=(SS=window).__svelte??(SS.__svelte={})).v??(wS.v=new Set)).add("5")}var nc={},_n=Symbol("uninitialized"),Gj="http://www.w3.org/2000/svg",Yj="http://www.w3.org/1998/Math/MathML",Kj=Array.isArray,Xj=Array.prototype.indexOf,Cy=Array.prototype.includes,Jj=Array.from,Jp=Object.keys,Gd=Object.defineProperty,jl=Object.getOwnPropertyDescriptor,Qj=Object.prototype,Zj=Array.prototype,e3=Object.getPrototypeOf,IS=Object.isExtensible,t3=()=>{};function r3(e){for(var t=0;t<e.length;t++)e[t]()}function Hx(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}var yo=1024,rs=2048,gc=4096,O0=8192,n3=16384,L0=32768,kS=1<<25,N0=65536,Lu=1<<19,i3=1<<20,TS=1<<21,o3=1<<22,Qp=1<<23,Ed=Symbol("$state"),Ux=Symbol("component"),qx=Symbol("legacy props"),s3=Symbol("attributes"),xy=Symbol("class"),a3=Symbol("style"),ep=Symbol("text"),Of=new class extends Error{constructor(...e){super(...e),Ee(this,"name","StaleReactionError"),Ee(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},vK=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function l3(){console.warn("https://svelte.dev/e/derived_inert")}function Lf(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function c3(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var Gr=!1;function Yc(e){Gr=e}var Jr;function bo(e){if(e===null)throw Lf(),nc;return Jr=e}function hu(){return bo(la(Jr))}function ys(e){if(Gr){if(la(Jr)!==null)throw Lf(),nc;Jr=e}}function u3(e=1){if(Gr){for(var t=e,r=Jr;t--;)r=la(r);Jr=r}}function Wx(e=!0){for(var t=0,r=Jr;;){if(r.nodeType===8){var n=r.data;if(n==="]"){if(t===0)return r;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=la(r);e&&r.remove(),r=i}}function d3(e){if(!e||e.nodeType!==8)throw Lf(),nc;return e.data}function Vx(e){return e===this.v}function f3(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function Gx(e){return!f3(e,this.v)}function Yx(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function h3(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function p3(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function m3(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function g3(e){throw new Error("https://svelte.dev/e/effect_orphan")}function v3(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function y3(){throw new Error("https://svelte.dev/e/hydration_failed")}function b3(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function w3(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function S3(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function I3(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function k3(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var Nf=!1,Df=!1,Zr=null;function pu(e){Zr=e}function Ym(e,t=!1,r){Zr={p:Zr,i:!1,c:null,e:null,s:e,x:null,r:Jt,l:Df&&!t?{s:null,u:null,$:[]}:null}}function Km(e){var t=Zr,r=t.e;if(r!==null){t.e=null;for(var n of r)pR(n)}return e!==void 0&&(t.x=e),t.i=!0,Zr=t.p,D0(e)}function D0(e={}){return Gd(e,Ux,{value:!0}),e}function Nu(){return!Df||Zr!==null&&Zr.l===null}var Sl=[];function Kx(){var e=Sl;Sl=[],r3(e)}function ic(e){if(Sl.length===0&&!Cd){var t=Sl;queueMicrotask(()=>{t===Sl&&Kx()})}Sl.push(e)}function T3(){for(;Sl.length>0;)Kx()}var E3=~(rs|gc|yo);function In(e,t){e.f=e.f&E3|t}function j0(e){(e.f&512)!==0||e.deps===null?In(e,yo):In(e,gc)}function Xx(e,t,r){(e.f&2048)!==0?t.add(e):e.f&4096&&r.add(e),In(e,yo)}function Xm(e){var t=pr,r=Jt;wo(null),Rs(null);try{return e()}finally{wo(t),Rs(r)}}function C3(e,t,r,n){const i=Nu()?Yd:Qx;var o=e.filter(h=>!h.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=Jt,l=x3(),c=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(h=>h.promise)):null;function u(h){if((a.f&16384)===0){l();try{n([...s,...h])}catch(g){xs(g,a)}Zp()}}var d=Jx();if(r.length===0){c.then(()=>u([])).finally(d);return}function f(){Promise.all(r.map(h=>R3(h))).then(u).catch(h=>xs(h,a)).finally(d)}c?c.then(()=>{l(),f(),Zp()}):f()}function x3(){var e=Jt,t=pr,r=Zr,n=ir;return function(i=!0){Rs(e),wo(t),pu(r),i&&!(e.f&16384)&&(n?.activate(),n?.apply())}}function Zp(e=!0){Rs(null),wo(null),pu(null),e&&ir?.deactivate()}function Jx(){var e=Jt,t=e.b,r=ir,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}function Yd(e){var t=2|rs;return Jt!==null&&(Jt.f|=Lu),{ctx:Zr,deps:null,effects:null,equals:Vx,f:t,fn:e,reactions:null,rv:0,v:_n,wv:0,parent:Jt,ac:null}}var md=Symbol("obsolete");function R3(e,t,r){let n=Jt;n===null&&h3();var i=void 0,o=jf(_n),s=!pr,a=new Set;return G3(()=>{var l=Jt,c=Hx();i=c.promise;try{Promise.resolve(e()).then(c.resolve,h=>{h!==Of&&c.reject(h)}).finally(Zp)}catch(h){c.reject(h),Zp()}var u=ir;if(s){if((l.f&32768)!==0)var d=Jx();if(n.b?.is_rendered())u.async_deriveds.get(l)?.reject(md);else for(const h of a.values())h.reject(md);a.add(c),u.async_deriveds.set(l,c)}const f=(h,g=void 0)=>{d?.(),a.delete(c),g!==md&&(u.activate(),g?(o.f|=Qp,om(o,g)):(o.f&8388608&&(o.f^=Qp),om(o,h)),u.deactivate())};c.promise.then(f,h=>f(null,h||"unknown"))}),q3(()=>{for(const l of a)l.reject(md)}),new Promise(l=>{function c(u){function d(){u===i?l(o):c(i)}u.then(d,d)}c(i)})}function Ct(e){const t=Yd(e);return IR(t),t}function Qx(e){const t=Yd(e);return t.equals=Gx,t}function P3(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)Ii(t[r])}}function z0(e){var t,r=Jt,n=e.parent;if(!ra&&n!==null&&e.v!==_n&&(n.f&24576)!==0)return l3(),e.v;Rs(n);try{P3(e),t=CR(e)}finally{Rs(r)}return t}function Zx(e){var t=z0(e);if(!e.equals(t)&&(e.wv=TR(),(!ir?.is_fork||e.deps===null)&&(ir!==null?(ir.capture(e,t,!0),Py?.capture(e,t,!0)):e.v=t,e.deps===null))){In(e,yo);return}ra||(li!==null?(F0()||ir?.is_fork)&&li.set(e,t):j0(e))}function _3(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&Xm(()=>{t.ac.abort(Of),t.ac=null}),t.fn!==null&&(t.teardown=t3),Xd(t,0),q0(t))}function eR(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&gu(t)}function tR(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function B0(e,t){tR(e,t),t.add(e)}function Lt(e,t,r){tR(e,t),t.set(e,r)}function Yt(e,t,r){if(typeof e=="function"?e===t:e.has(t))return arguments.length<3?t:r;throw new TypeError("Private element is not present on this object")}function St(e,t,r){return e.set(Yt(e,t),r),r}function G(e,t){return e.get(Yt(e,t))}var rR,Ry=null,zc=null,ir=null,Py=null,li=null,_y=null,Cd=!1,qg=!1,Kd=null,em=null,nR=0,A3=1,Ay=new WeakMap,zl=new WeakMap,Kc=new WeakMap,tm=new WeakMap,wh=new WeakMap,Bc=new WeakMap,ll=new WeakMap,gd=new WeakMap,ms=new WeakMap,ES=new WeakMap,mu=new WeakMap,Js=new WeakMap,Ta=new WeakMap,Wg=new WeakMap,Sh=new WeakMap,Rn=new WeakSet,vc=class iR{constructor(){B0(this,Rn),Ee(this,"id",A3++),Lt(this,Ay,!1),Ee(this,"linked",!0),Lt(this,zl,null),Lt(this,Kc,null),Ee(this,"async_deriveds",new Map),Ee(this,"current",new Map),Ee(this,"previous",new Map),Lt(this,tm,new Set),Lt(this,wh,new Set),Lt(this,Bc,0),Lt(this,ll,new Map),Lt(this,gd,null),Lt(this,ms,[]),Lt(this,ES,[]),Lt(this,mu,new Set),Lt(this,Js,new Set),Lt(this,Ta,new Map),Lt(this,Wg,new Set),Ee(this,"is_fork",!1),Lt(this,Sh,!1),zc===null?Ry=zc=this:(St(Kc,zc,this),St(zl,this,zc)),zc=this}skip_effect(t){G(Ta,this).has(t)||G(Ta,this).set(t,{d:[],m:[]}),G(Wg,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=G(Ta,this).get(t);if(n){G(Ta,this).delete(t);for(var i of n.d)In(i,rs),r(i);for(i of n.m)In(i,gc),r(i)}G(Wg,this).add(t)}capture(t,r,n=!1){t.v!==_n&&!this.previous.has(t)&&this.previous.set(t,t.v),!(t.f&8388608)&&(this.current.set(t,[r,n]),li?.set(t,r)),this.is_fork||(t.v=r)}activate(){ir=this}deactivate(){ir=null,li=null}flush(){try{qg=!0,ir=this,Yt(Rn,this,rm).call(this)}finally{nR=0,_y=null,Kd=null,em=null,qg=!1,ir=null,li=null,Cs.clear()}}discard(){for(const t of G(wh,this))t(this);G(wh,this).clear();for(const t of this.async_deriveds.values())t.reject(md);Yt(Rn,this,nm).call(this),G(gd,this)?.resolve()}register_created_effect(t){G(ES,this).push(t)}increment(t,r){if(St(Bc,this,G(Bc,this)+1),t){let n=G(ll,this).get(r)??0;G(ll,this).set(r,n+1)}}decrement(t,r){if(St(Bc,this,G(Bc,this)-1),t){let n=G(ll,this).get(r)??0;n===1?G(ll,this).delete(r):G(ll,this).set(r,n-1)}G(Sh,this)||(St(Sh,this,!0),ic(()=>{St(Sh,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)G(mu,this).add(n);for(const n of r)G(Js,this).add(n);t.clear(),r.clear()}oncommit(t){G(tm,this).add(t)}ondiscard(t){G(wh,this).add(t)}settled(){return(G(gd,this)??St(gd,this,Hx())).promise}static ensure(){if(ir===null){const t=ir=new iR;!qg&&!Cd&&ic(()=>{G(Ay,t)||t.flush()})}return ir}apply(){if(!Nf||!this.is_fork&&G(zl,this)===null&&G(Kc,this)===null){li=null;return}li=new Map;for(const[r,[n]]of this.current)li.set(r,n);for(let r=Ry;r!==null;r=G(Kc,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(const[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(const[n,i]of r.previous)li.has(n)||li.set(n,i)}}schedule(t){if(_y=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}G(ms,this).push(t)}};rR=vc;function CS(){if(this.is_fork)return!0;for(const r of G(ll,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(G(Ta,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function $3(){var e=[];for(const i of G(ms,this))if(!((i.f&16384)!==0||(i.f&6144)===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&96)!==0){if((n&1024)===0){r=!0;break}t.f^=yo}}r||e.push(t)}return St(ms,this,[]),e}function rm(){St(Ay,this,!0);for(const s of G(mu,this))G(Js,this).delete(s),In(s,rs),this.schedule(s);for(const s of G(Js,this))In(s,gc),this.schedule(s);this.apply();for(var e=Kd=[],t=[],r=em=[];G(ms,this).length>0;){nR++>1e3&&(Yt(Rn,this,nm).call(this),N3());for(const s of Yt(Rn,this,$3).call(this))try{Yt(Rn,this,M3).call(this,s,e,t)}catch(a){throw aR(s),Yt(Rn,this,CS).call(this)||this.discard(),a}}if(ir=null,r.length>0){var n=rR.ensure();for(const s of r)n.schedule(s)}if(Kd=null,em=null,Yt(Rn,this,CS).call(this)){Yt(Rn,this,Ih).call(this,t),Yt(Rn,this,Ih).call(this,e);for(const[s,a]of G(Ta,this))sR(s,a);r.length>0&&Yt(Rn,ir,rm).call(ir);return}const i=Yt(Rn,this,O3).call(this);if(i){Yt(Rn,this,Ih).call(this,t),Yt(Rn,this,Ih).call(this,e),Yt(Rn,i,L3).call(i,this);return}G(mu,this).clear(),G(Js,this).clear();for(const s of G(tm,this))s(this);G(tm,this).clear(),Py=this,xS(t),xS(e),Py=null,G(gd,this)?.resolve();var o=ir;if(G(Bc,this)===0&&(G(ms,this).length===0||o!==null)&&Yt(Rn,this,nm).call(this),G(ms,this).length>0)if(o!==null){for(const s of G(ms,this))G(ms,o).push(s);St(ms,this,[])}else o=this;o!==null&&(Cs.clear(),Yt(Rn,o,rm).call(o))}function M3(e,t,r){e.f^=yo;for(var n=e.first;n!==null;){var i=n.f,o=(i&96)!==0;if(!(o&&(i&1024)!==0||(i&8192)!==0||G(Ta,this).has(n))&&n.fn!==null){o?n.f^=yo:(i&4)!==0?t.push(n):Nf&&(i&16777224)!==0?r.push(n):Bf(n)&&(i&16&&G(Js,this).add(n),gu(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function O3(){for(var e=G(zl,this);e!==null;){if(!e.is_fork){for(const[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=G(zl,e)}return null}function L3(e){for(const[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(const[r,n]of e.async_deriveds){const i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(G(mu,e),G(Js,e));const t=r=>{var n=r.reactions;if(n!==null&&!((r.f&2)!==0&&(r.f&6144)===0))for(const s of n){var i=s.f;if((i&2)!==0)t(s);else{var o=s;i&4194320&&!this.async_deriveds.has(o)&&(G(Js,this).delete(o),In(o,rs),this.schedule(o))}}};for(const r of this.current.keys())t(r);this.oncommit(()=>e.discard()),Yt(Rn,e,nm).call(e),ir=this,Yt(Rn,this,rm).call(this)}function Ih(e){for(var t=0;t<e.length;t+=1)Xx(e[t],G(mu,this),G(Js,this))}function nm(){if(this.linked){var e=G(zl,this),t=G(Kc,this);e===null?Ry=t:St(Kc,e,t),t===null?zc=e:St(zl,t,e),this.linked=!1}}function rt(e){var t=Cd;Cd=!0;try{var r;for(e&&(ir!==null&&!ir.is_fork&&ir.flush(),r=e());;){if(T3(),ir===null)return r;ir.flush()}}finally{Cd=t}}function N3(){try{v3()}catch(e){xs(e,_y)}}var ps=null;function xS(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&24576)===0&&Bf(n)&&(ps=new Set,gu(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&yR(n),ps?.size>0)){Cs.clear();for(const i of ps){if((i.f&24576)!==0)continue;const o=[i];let s=i.parent;for(;s!==null;)ps.has(s)&&(ps.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){const l=o[a];!(l.f&24576)&&gu(l)}}ps.clear()}}ps=null}}function oR(e){ir.schedule(e)}function sR(e,t){if(!((e.f&32)!==0&&(e.f&1024)!==0)){(e.f&2048)!==0?t.d.push(e):e.f&4096&&t.m.push(e),In(e,yo);for(var r=e.first;r!==null;)sR(r,t),r=r.next}}function aR(e){In(e,yo);for(var t=e.first;t!==null;)aR(t),t=t.next}var im=new Set,Cs=new Map,lR=!1;function jf(e,t){return{f:0,v:e,reactions:null,equals:Vx,rv:0,wv:0}}function nr(e,t){const r=jf(e,t);return IR(r),r}function D3(e,t=!1,r=!0){const n=jf(e);if(t||(n.equals=Gx),Df&&r&&Zr!==null&&Zr.l!==null){var i;((i=Zr.l).s??(i.s=[])).push(n)}return n}function He(e,t,r=!1){return pr!==null&&(!jo||pr.f&131072)&&Nu()&&pr.f&4325394&&(Go===null||!Go.has(e))&&I3(),om(e,r?Xc(t):t,em)}var hl=null,$y=0;function om(e,t,r=null){if(!e.equals(t)){ra?Cs.set(e,t):Cs.has(e)||Cs.set(e,e.v);var n=vc.ensure();if(n.capture(e,t),(e.f&2)!==0){const i=e;e.f&2048&&z0(i),li===null&&j0(i)}e.wv=TR(),hl=null,$y=0,cR(e,rs,r),hl=null,Nu()&&Jt!==null&&Jt.f&1024&&!(Jt.f&96)&&(oo===null?X3([e]):oo.push(e)),!n.is_fork&&im.size>0&&!lR&&j3()}return t}function j3(){lR=!1;for(const e of im){e.f&1024&&In(e,gc);let t;try{t=Bf(e)}catch{t=!0}t&&gu(e)}im.clear()}function xd(e){He(e,e.v+1)}function cR(e,t,r){var n=e.reactions;if(n!==null){var i=Nu(),o=n.length;if($y+=o,$y>1e5&&hl===null&&(hl=new Set),hl!==null){if(hl.has(e))return;hl.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Jt)){var c=(l&rs)===0;if(c&&In(a,t),(l&131072)!==0)im.add(a);else if((l&2)!==0){var u=a;li?.delete(u),cR(u,gc,r)}else if(c){var d=a;l&16&&ps!==null&&ps.add(d),r!==null?r.push(d):oR(d)}}}}}function Xc(e){if(typeof e!="object"||e===null||Ed in e||Ux in e)return e;const t=e3(e);if(t!==Qj&&t!==Zj)return e;var r=new Map,n=Kj(e),i=nr(0),o=null,s=Bl,a=l=>{if(Bl===s)return l();var c=pr,u=Bl;wo(null),AS(s);var d=l();return wo(c),AS(u),d};return n&&r.set("length",nr(e.length,o)),new Proxy(e,{defineProperty(l,c,u){(!("value"in u)||u.configurable===!1||u.enumerable===!1||u.writable===!1)&&w3();var d=r.get(c);return d===void 0?a(()=>{var f=nr(u.value,o);return r.set(c,f),f}):He(d,u.value,!0),!0},deleteProperty(l,c){var u=r.get(c);if(u===void 0){if(c in l){const d=a(()=>nr(_n,o));r.set(c,d),xd(i)}}else He(u,_n),xd(i);return!0},get(l,c,u){if(c===Ed)return e;var d=r.get(c),f=c in l;if(d===void 0&&(!f||jl(l,c)?.writable)&&(d=a(()=>nr(Xc(f?l[c]:_n),o)),r.set(c,d)),d!==void 0){var h=R(d);return h===_n?void 0:h}return Reflect.get(l,c,u)},getOwnPropertyDescriptor(l,c){this.has?.(l,c);var u=Reflect.getOwnPropertyDescriptor(l,c),d=r.get(c);if(d!==void 0){var f=R(d);if(f===_n)return;if(u&&"value"in u)u.value=f;else return{enumerable:!0,configurable:!0,value:f,writable:!0}}return u},has(l,c){if(c===Ed)return!0;var u=r.get(c),d=u!==void 0&&u.v!==_n||Reflect.has(l,c);return(u!==void 0||Jt!==null&&(!d||jl(l,c)?.writable))&&(u===void 0&&(u=a(()=>nr(d?Xc(l[c]):_n,o)),r.set(c,u)),R(u)===_n)?!1:d},set(l,c,u,d){var f=r.get(c),h=c in l;if(n&&c==="length")for(var g=u;g<f.v;g+=1){var m=r.get(g+"");m!==void 0?He(m,_n):g in l&&(m=a(()=>nr(_n,o)),r.set(g+"",m))}if(f===void 0)(!h||jl(l,c)?.writable)&&(f=a(()=>nr(void 0,o)),He(f,Xc(u)),r.set(c,f));else{h=f.v!==_n;var v=a(()=>Xc(u));He(f,v)}var b=Reflect.getOwnPropertyDescriptor(l,c);if(b?.set&&b.set.call(d,u),!h){if(n&&typeof c=="string"){var I=r.get("length"),C=Number(c);Number.isInteger(C)&&C>=I.v&&He(I,C+1)}xd(i)}return!0},ownKeys(l){R(i);var c=Reflect.ownKeys(l).filter(f=>{var h=r.get(f);return h===void 0||h.v!==_n});for(var[u,d]of r)d.v!==_n&&!(u in l)&&c.push(u);return c},setPrototypeOf(){S3()}})}var RS,uR,dR,fR;function My(){if(RS===void 0){RS=window,uR=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;dR=jl(t,"firstChild").get,fR=jl(t,"nextSibling").get,IS(e)&&(e[xy]=void 0,e[s3]=null,e[a3]=void 0,e.__e=void 0),IS(r)&&(r[ep]=void 0)}}function oc(e=""){return document.createTextNode(e)}function Ao(e){return dR.call(e)}function la(e){return fR.call(e)}function Ca(e,t){if(!Gr)return Ao(e);var r=Ao(Jr);if(r===null)r=Jr.appendChild(oc());else if(t&&r.nodeType!==3){var n=oc();return r?.before(n),bo(n),n}return t&&hR(r),bo(r),r}function Il(e,t=!1){if(!Gr)return Ao(e);var r=Ca(e,t);return ys(e),r}function Jc(e,t=1,r=!1){let n=Gr?Jr:e;for(var i;t--;)i=n,n=la(n);if(!Gr)return n;if(r){if(n?.nodeType!==3){var o=oc();return n===null?i?.after(o):n.before(o),bo(o),o}hR(n)}return bo(n),n}function z3(e){e.textContent=""}function B3(){return!Nf||ps!==null?!1:(Jt.f&L0)!==0}function Jm(e,t,r){return t==null||t==="http://www.w3.org/1999/xhtml"?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function hR(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function F3(e){var t=Jt;if(t===null)return pr.f|=Qp,e;if((t.f&32768)===0&&(t.f&4)===0)throw e;xs(e,t)}function xs(e,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function H3(e){Jt===null&&(pr===null&&g3(e),m3()),ra&&p3(e)}function U3(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Ms(e,t){var r=Jt;r!==null&&r.f&8192&&(e|=O0);var n={ctx:Zr,deps:null,nodes:null,f:e|rs|512,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};ir?.register_created_effect(n);var i=n;if((e&4)!==0)Kd!==null?Kd.push(n):vc.ensure().schedule(n);else if(t!==null){try{gu(n)}catch(s){throw Ii(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=N0))}if(i!==null&&(i.parent=r,r!==null&&U3(i,r),pr!==null&&(pr.f&2)!==0&&(e&64)===0)){var o=pr;(o.effects??(o.effects=[])).push(i)}return n}function F0(){return pr!==null&&!jo}function q3(e){const t=Ms(8,null);return In(t,yo),t.teardown=e,t}function Vr(e){H3("$effect");var t=Jt.f;if(!pr&&(t&32)!==0&&Zr!==null&&!Zr.i){var r=Zr;(r.e??(r.e=[])).push(e)}else return pR(e)}function pR(e){return Ms(4|i3,e)}function W3(e){vc.ensure();const t=Ms(64|Lu,e);return()=>{Ii(t)}}function V3(e){vc.ensure();const t=Ms(64|Lu,e);return(r={})=>new Promise(n=>{r.outro?zf(t,()=>{Ii(t),n(void 0)}):(Ii(t),n(void 0))})}function mR(e){return Ms(4,e)}function G3(e){return Ms(o3|Lu,e)}function H0(e,t=0){return Ms(8|t,e)}function $o(e,t=[],r=[],n=[]){C3(n,t,r,i=>{Ms(8,()=>{e(...i.map(R))})})}function U0(e,t=0){return Ms(16|t,e)}function ta(e){return Ms(32|Lu,e)}function gR(e){var t=e.teardown;if(t!==null){const r=ra,n=pr;_S(!0),wo(null);try{t.call(null)}catch(i){xs(i,e.parent)}finally{_S(r),wo(n)}}}function q0(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&Xm(()=>{i.abort(Of)});var n=r.next;(r.f&64)!==0?r.parent=null:Ii(r,t),r=n}}function Y3(e){for(var t=e.first;t!==null;){var r=t.next;!(t.f&32)&&Ii(t),t=r}}function Ii(e,t=!0){var r=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(vR(e.nodes.start,e.nodes.end),r=!0),e.f|=kS,q0(e,t&&!r),Xd(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const o of n)o.stop();gR(e),e.f^=kS,e.f|=n3;var i=e.parent;i!==null&&i.first!==null&&yR(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function vR(e,t){for(;e!==null;){var r=e===t?null:la(e);e.remove(),e=r}}function yR(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function zf(e,t,r=!0){var n=[];e.f|=256,bR(e,n,!0);var i=()=>{r&&Ii(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function bR(e,t,r){if((e.f&8192)===0){e.f^=O0;var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(e.f&16)!==0;bR(i,t,s?r:!1)}i=o}}}function PS(e){e.f&=-257,wR(e,!0)}function wR(e,t){if((e.f&256)===0&&(e.f&8192)!==0){e.f^=O0,!(e.f&1024)&&(In(e,rs),vc.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;wR(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(const s of o)(s.is_global||t)&&s.in()}}function SR(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:la(r);t.append(r),r=i}}var K3=null,tp=!1,ra=!1;function _S(e){ra=e}var pr=null,jo=!1;function wo(e){pr=e}var Jt=null;function Rs(e){Jt=e}var Go=null;function IR(e){pr!==null&&(pr.f&2097152||pr.f&2)&&(Go??(Go=new Set)).add(e)}var wi=null,zi=0,oo=null;function X3(e){oo=e}var kR=1,kl=0,Bl=kl;function AS(e){Bl=e}function TR(){return++kR}function Bf(e){var t=e.f;if((t&2048)!==0)return!0;if((t&4096)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(Bf(o)&&Zx(o),o.wv>e.wv)return!0}t&512&&li===null&&In(e,yo)}return!1}function ER(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!Nf&&Go!==null&&Go.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?ER(o,t,!1):t===o&&(r?In(o,rs):o.f&1024&&In(o,gc),oR(o))}}function CR(e){var t=wi,r=zi,n=oo,i=pr,o=Go,s=Zr,a=jo,l=Bl,c=e.f;wi=null,zi=0,oo=null,pr=(c&96)===0?e:null,Go=null,pu(e.ctx),jo=!1,Bl=++kl,e.ac!==null&&(Xm(()=>{e.ac.abort(Of)}),e.ac=null);try{e.f|=TS;var u=e.fn,d=u();e.f|=L0;var f=$S(e);if(Nu()&&oo!==null&&!jo&&f!==null&&(e.f&6146)===0)for(var h=0;h<oo.length;h++)ER(oo[h],e);if(i!==null&&i!==e){if(kl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=kl;if(t!==null)for(const g of t)g.rv=kl;oo!==null&&(n===null?n=oo:n.push(...oo))}return e.f&8388608&&(e.f^=Qp),d}catch(g){return $S(e),F3(g)}finally{e.f^=TS,wi=t,zi=r,oo=n,pr=i,Go=o,pu(s),jo=a,Bl=l}}function $S(e){var t=e.deps,r=ir?.is_fork;if(wi!==null){var n;if(r||Xd(e,zi),t!==null&&zi>0)for(t.length=zi+wi.length,n=0;n<wi.length;n++)t[zi+n]=wi[n];else e.deps=t=wi;if(F0()&&(e.f&512)!==0)for(n=zi;n<t.length;n++){var i;((i=t[n]).reactions??(i.reactions=[])).push(e)}}else!r&&t!==null&&zi<t.length&&(Xd(e,zi),t.length=zi);return t}function J3(e,t){let r=t.reactions;if(r!==null){var n=Xj.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&2)!==0&&(wi===null||!Cy.call(wi,t))){var o=t;o.f&512&&(o.f^=512),o.v!==_n&&j0(o),o.ac!==null&&Xm(()=>{o.ac.abort(Of),o.ac=null,In(o,rs)}),_3(o),Xd(o,0)}}function Xd(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)J3(e,r[n])}function gu(e){var t=e.f;if((t&16384)===0){In(e,yo);var r=Jt,n=tp;Jt=e,tp=(t&96)===0;try{(t&16777232)!==0?Y3(e):q0(e),gR(e);var i=CR(e);e.teardown=typeof i=="function"?i:null,e.wv=kR}finally{tp=n,Jt=r}}}async function Jd(){if(Nf)return new Promise(e=>{requestAnimationFrame(()=>e()),setTimeout(()=>e())});await Promise.resolve(),rt()}function R(e){var t=(e.f&2)!==0;if(K3?.add(e),pr!==null&&!jo&&!(Jt!==null&&(Jt.f&16384)!==0)&&(Go===null||!Go.has(e))){var r=pr.deps;if((pr.f&2097152)!==0)e.rv<kl&&(e.rv=kl,wi===null&&r!==null&&r[zi]===e?zi++:wi===null?wi=[e]:wi.push(e));else{var n;(n=pr).deps??(n.deps=[]),Cy.call(pr.deps,e)||pr.deps.push(e);var i=e.reactions;i===null?e.reactions=[pr]:Cy.call(i,pr)||i.push(pr)}}if(ra&&Cs.has(e))return Cs.get(e);if(t){var o=e;if(ra){var s=o.v;return(!(o.f&1024)&&o.reactions!==null||RR(o))&&(s=z0(o)),Cs.set(o,s),s}var a=(o.f&512)===0&&!jo&&pr!==null&&(tp||(pr.f&512)!==0),l=(o.f&L0)===0;Bf(o)&&(a&&(o.f|=512),Zx(o)),a&&!l&&(eR(o),xR(o))}if(li?.has(e))return li.get(e);if((e.f&8388608)!==0)throw e.v;return e.v}function xR(e){if(e.f|=512,e.deps!==null)for(const t of e.deps)(t.reactions??(t.reactions=[])).push(e),t.f&2&&!(t.f&512)&&(eR(t),xR(t))}function RR(e){if(e.v===_n)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(Cs.has(t)||(t.f&2)!==0&&RR(t))return!0;return!1}function zn(e){var t=jo;try{return jo=!0,e()}finally{jo=t}}var kh=Symbol("events"),Q3=new Set,MS=new Set,Vg=null,Gg=!1;function OS(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;Vg=e,Gg||(Gg=!0,setTimeout(()=>{Gg=!1,Vg=null}));var s=0,a=Vg===e&&e[kh];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[kh]=t;return}var c=i.indexOf(t);if(c===-1)return;l<=c&&(s=l)}if(o=i[s]||e.target,o!==t){Gd(e,"currentTarget",{configurable:!0,get(){return o||r}});var u=pr,d=Jt;wo(null),Rs(null);try{for(var f,h=[];o!==null&&o!==t;){try{var g=o[kh]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(m){f?h.push(m):f=m}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let m of h)queueMicrotask(()=>{throw m});throw f}}finally{e[kh]=t,delete e.currentTarget,wo(u),Rs(d)}}}var Z3=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function e7(e){return Z3?.createHTML(e)??e}function t7(e){var t=Jm("template");return t.innerHTML=e7(e.replaceAll("<!>","<!---->")),t.content}function Fl(e,t){var r=Jt;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function ca(e,t){var r=(t&1)!==0,n=(t&2)!==0,i,o=!e.startsWith("<!>");return()=>{if(Gr)return Fl(Jr,null),Jr;i===void 0&&(i=t7(o?e:"<!>"+e),r||(i=Ao(i)));var s=n||uR?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=Ao(s),l=s.lastChild;Fl(a,l)}else Fl(s,s);return s}}function lo(e,t){if(Gr){var r=Jt;(!(r.f&32768)||r.nodes.end===null)&&(r.nodes.end=Jr),hu();return}e!==null&&e.before(t)}var r7=["touchstart","touchmove"];function n7(e){return r7.includes(e)}function i7(e){let t=0,r=jf(0),n;return()=>{F0()&&(R(r),H0(()=>(t===0&&(n=zn(()=>e(()=>xd(r)))),t+=1,()=>{ic(()=>{t-=1,t===0&&(n?.(),n=void 0,xd(r))})})))}}var o7=N0|Lu;function s7(e,t,r,n){new a7(e,t,r,n)}var Yo=new WeakMap,Oy=new WeakMap,bs=new WeakMap,Qd=new WeakMap,Ui=new WeakMap,Ko=new WeakMap,Gi=new WeakMap,zo=new WeakMap,$a=new WeakMap,Fc=new WeakMap,Hl=new WeakMap,Th=new WeakMap,Ly=new WeakMap,Ny=new WeakMap,Za=new WeakMap,LS=new WeakMap,Mn=new WeakSet,a7=class{constructor(e,t,r,n){B0(this,Mn),Ee(this,"parent",void 0),Ee(this,"is_pending",!1),Ee(this,"transform_error",void 0),Lt(this,Yo,void 0),Lt(this,Oy,Gr?Jr:null),Lt(this,bs,void 0),Lt(this,Qd,void 0),Lt(this,Ui,void 0),Lt(this,Ko,null),Lt(this,Gi,null),Lt(this,zo,null),Lt(this,$a,null),Lt(this,Fc,0),Lt(this,Hl,0),Lt(this,Th,!1),Lt(this,Ly,new Set),Lt(this,Ny,new Set),Lt(this,Za,null),Lt(this,LS,i7(()=>(St(Za,this,jf(G(Fc,this))),()=>{St(Za,this,null)}))),St(Yo,this,e),St(bs,this,t),St(Qd,this,i=>{var o=Jt;o.b=this,o.f|=128,r(i)}),this.parent=Jt.b,this.transform_error=n??this.parent?.transform_error??(i=>i),St(Ui,this,U0(()=>{if(Gr){const i=G(Oy,this);hu();const o=i.data==="[!";if(i.data.startsWith("[?")){const s=JSON.parse(i.data.slice(2));Yt(Mn,this,c7).call(this,s)}else o?Yt(Mn,this,u7).call(this):Yt(Mn,this,l7).call(this)}else Yt(Mn,this,_R).call(this)},o7)),Gr&&St(Yo,this,Jr)}defer_effect(e){Xx(e,G(Ly,this),G(Ny,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!G(bs,this).pending}update_pending_count(e,t){Yt(Mn,this,AR).call(this,e,t),St(Fc,this,G(Fc,this)+e),G(Za,this)&&!G(Th,this)&&(St(Th,this,!0),ic(()=>{St(Th,this,!1),G(Za,this)&&om(G(Za,this),G(Fc,this))}))}get_effect_pending(){return G(LS,this).call(this),R(G(Za,this))}error(e){if(!G(bs,this).onerror&&!G(bs,this).failed)throw e;ir?.is_fork?(G(Ko,this)&&ir.skip_effect(G(Ko,this)),G(Gi,this)&&ir.skip_effect(G(Gi,this)),G(zo,this)&&ir.skip_effect(G(zo,this)),ir.oncommit(()=>{Yt(Mn,this,NS).call(this,e)})):Yt(Mn,this,NS).call(this,e)}};function l7(){try{St(Ko,this,ta(()=>G(Qd,this).call(this,G(Yo,this))))}catch(e){this.error(e)}}function c7(e){const t=G(bs,this).failed,{reset:r,invoke_onerror:n}=Yt(Mn,this,PR).call(this,e);ic(n),t&&St(zo,this,ta(()=>{t(G(Yo,this),()=>e,()=>r)}))}function PR(e){var t=!1,r=!1;const n=()=>{if(t){c3();return}t=!0,r&&k3(),G(zo,this)!==null&&zf(G(zo,this),()=>{St(zo,this,null)}),Yt(Mn,this,W0).call(this,()=>{Yt(Mn,this,_R).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,G(bs,this).onerror?.(e,n),r=!1}catch(i){xs(i,G(Ui,this)&&G(Ui,this).parent)}}}}function u7(){const e=G(bs,this).pending;e&&(this.is_pending=!0,St(Gi,this,ta(()=>e(G(Yo,this)))),ic(()=>{var t=St($a,this,document.createDocumentFragment()),r=oc(),n=!1;if(t.append(r),St(Ko,this,Yt(Mn,this,W0).call(this,()=>{try{return ta(()=>G(Qd,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){xs(o,G(Ui,this).parent)}return null}})),G(Ko,this)===null){St($a,this,null),n&&Yt(Mn,this,sm).call(this,ir);return}G(Hl,this)===0&&(G(Yo,this).before(t),St($a,this,null),zf(G(Gi,this),()=>{St(Gi,this,null)}),Yt(Mn,this,sm).call(this,ir))}))}function _R(){try{if(this.is_pending=this.has_pending_snippet(),St(Hl,this,0),St(Fc,this,0),St(Ko,this,ta(()=>{G(Qd,this).call(this,G(Yo,this))})),G(Hl,this)>0){var e=St($a,this,document.createDocumentFragment());SR(G(Ko,this),e);const t=G(bs,this).pending;St(Gi,this,ta(()=>t(G(Yo,this))))}else Yt(Mn,this,sm).call(this,ir)}catch(t){this.error(t)}}function sm(e){this.is_pending=!1,e.transfer_effects(G(Ly,this),G(Ny,this))}function W0(e){var t=Jt,r=pr,n=Zr;Rs(G(Ui,this)),wo(G(Ui,this)),pu(G(Ui,this).ctx);try{return vc.ensure(),e()}finally{Rs(t),wo(r),pu(n)}}function AR(e,t){if(!this.has_pending_snippet()){if(this.parent){var r;Yt(Mn,r=this.parent,AR).call(r,e,t)}return}St(Hl,this,G(Hl,this)+e),G(Hl,this)===0&&(Yt(Mn,this,sm).call(this,t),G(Gi,this)&&zf(G(Gi,this),()=>{St(Gi,this,null)}),G($a,this)&&(G(Yo,this).before(G($a,this)),St($a,this,null)))}function NS(e){G(Ko,this)&&(Ii(G(Ko,this)),St(Ko,this,null)),G(Gi,this)&&(Ii(G(Gi,this)),St(Gi,this,null)),G(zo,this)&&(Ii(G(zo,this)),St(zo,this,null)),Gr&&(bo(G(Oy,this)),u3(),bo(Wx()));let t=G(bs,this).failed;const r=n=>{const{reset:i,invoke_onerror:o}=Yt(Mn,this,PR).call(this,n);o(),t&&St(zo,this,Yt(Mn,this,W0).call(this,()=>{try{return ta(()=>{var s=Jt;s.b=this,s.f|=128,t(G(Yo,this),()=>n,()=>i)})}catch(s){return xs(s,G(Ui,this).parent),null}}))};ic(()=>{var n;try{n=this.transform_error(e)}catch(i){xs(i,G(Ui,this)&&G(Ui,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>xs(i,G(Ui,this)&&G(Ui,this).parent)):r(n)})}function Tl(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[ep]??(e[ep]=e.nodeValue))&&(e[ep]=r,e.nodeValue=`${r}`)}function $R(e,t){return MR(e,t)}function d7(e,t){My(),t.intro=t.intro??!1;const r=t.target,n=Gr,i=Jr;try{for(var o=Ao(r);o&&(o.nodeType!==8||o.data!=="[");)o=la(o);if(!o)throw nc;Yc(!0),bo(o);const s=MR(e,{...t,anchor:o});return Yc(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
44
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==nc&&console.warn("Failed to hydrate: ",s),t.recover===!1&&y3(),My(),z3(r),Yc(!1),$R(e,t)}finally{Yc(n),bo(i)}}var Eh=new Map;function MR(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){My();var l=void 0,c=V3(()=>{var u=r??t.appendChild(oc());s7(u,{pending:()=>{}},h=>{Ym({});var g=Zr;if(o&&(g.c=o),i&&(n.$$events=i),Gr&&Fl(h,null),l=e(h,n)||D0(),Gr&&(Jt.nodes.end=Jr,Jr===null||Jr.nodeType!==8||Jr.data!=="]"))throw Lf(),nc;Km()},a);var d=new Set,f=h=>{for(var g=0;g<h.length;g++){var m=h[g];if(!d.has(m)){d.add(m);var v=n7(m);for(const C of[t,document]){var b=Eh.get(C);b===void 0&&(b=new Map,Eh.set(C,b));var I=b.get(m);I===void 0?(C.addEventListener(m,OS,{passive:v}),b.set(m,1)):b.set(m,I+1)}}}};return f(Jj(Q3)),MS.add(f),()=>{for(var h of d)for(const v of[t,document]){var g=Eh.get(v),m=g.get(h);--m==0?(v.removeEventListener(h,OS),g.delete(h),g.size===0&&Eh.delete(v)):g.set(h,m)}MS.delete(f),u!==r&&u.parentNode?.removeChild(u)}});return Dy.set(l,c),l}var Dy=new WeakMap;function f7(e,t){const r=Dy.get(e);return r?(Dy.delete(e),r(t)):Promise.resolve()}var Bs=new WeakMap,ya=new WeakMap,xo=new WeakMap,Yu=new WeakMap,Yg=new WeakMap,Kg=new WeakMap,DS=new WeakMap,OR=class{constructor(e,t=!0){Ee(this,"anchor",void 0),Lt(this,Bs,new Map),Lt(this,ya,new Map),Lt(this,xo,new Map),Lt(this,Yu,new Set),Lt(this,Yg,!0),Lt(this,Kg,r=>{if(G(Bs,this).has(r)){var n=G(Bs,this).get(r),i=G(ya,this).get(n);if(i)PS(i),G(Yu,this).delete(n);else{var o=G(xo,this).get(n);o&&(PS(o.effect),G(ya,this).set(n,o.effect),G(xo,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(const[s,a]of G(Bs,this)){if(G(Bs,this).delete(s),s===r)break;const l=G(xo,this).get(a);l&&(Ii(l.effect),G(xo,this).delete(a))}for(const[s,a]of G(ya,this)){if(s===n||G(Yu,this).has(s))continue;const l=()=>{if(Array.from(G(Bs,this).values()).includes(s)){var c=document.createDocumentFragment();SR(a,c),c.append(oc()),G(xo,this).set(s,{effect:a,fragment:c})}else Ii(a);G(Yu,this).delete(s),G(ya,this).delete(s)};G(Yg,this)||!i?(G(Yu,this).add(s),zf(a,l,!1)):l()}}}),Lt(this,DS,r=>{G(Bs,this).delete(r);const n=Array.from(G(Bs,this).values());for(const[i,o]of G(xo,this))n.includes(i)||(Ii(o.effect),G(xo,this).delete(i))}),this.anchor=e,St(Yg,this,t)}ensure(e,t){var r=ir,n=B3();if(t&&!G(ya,this).has(e)&&!G(xo,this).has(e))if(n){var i=document.createDocumentFragment(),o=oc();i.append(o),G(xo,this).set(e,{effect:ta(()=>t(o)),fragment:i})}else G(ya,this).set(e,ta(()=>t(this.anchor)));if(G(Bs,this).set(r,e),n){for(const[s,a]of G(ya,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(const[s,a]of G(xo,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(G(Kg,this)),r.ondiscard(G(DS,this))}else Gr&&(this.anchor=Jr),G(Kg,this).call(this,r)}};function h7(e){Zr===null&&Yx("onMount"),Df&&Zr.l!==null?p7(Zr).m.push(e):Vr(()=>{const t=zn(e);if(typeof t=="function")return t})}function V0(e){Zr===null&&Yx("onDestroy"),h7(()=>()=>zn(e))}function p7(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}function Rd(e,t,r=!1){var n;Gr&&(n=Jr,hu());var i=new OR(e),o=r?N0:0;function s(a,l){if(Gr){var c=d3(n);if(a!==parseInt(c.substring(1))){var u=Wx();bo(u),i.anchor=u,Yc(!1),i.ensure(a,l),Yc(!0);return}}i.ensure(a,l)}U0(()=>{var a=!1;t((l,c=0)=>{a=!0,s(c,l)}),a||s(-1,null)},o)}var m7=Symbol("NaN");function g7(e,t,r){Gr&&hu();var n=new OR(e),i=!Nu();U0(()=>{var o=t();o!==o&&(o=m7),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,r)})}function jS(e,t,r=!1,n=!1,i=!1,o=!1){var s=e,a="";if(r){var l=e;Gr&&(s=bo(Ao(l)))}$o(()=>{var c=Jt;if(a===(a=t()??"")){Gr&&hu();return}if(r&&!Gr){c.nodes=null,l.innerHTML=a,a!==""&&Fl(Ao(l),l.lastChild);return}if(c.nodes!==null&&(vR(c.nodes.start,c.nodes.end),c.nodes=null),a!==""){if(Gr){for(var u=Jr.data,d=hu(),f=d;d!==null&&(d.nodeType!==8||d.data!=="");)f=d,d=la(d);if(d===null)throw Lf(),nc;Fl(Jr,f),s=bo(d);return}var h=Jm(n?"svg":i?"math":"template",n?Gj:i?Yj:void 0);h.innerHTML=a;var g=n||i?h:h.content;if(Fl(Ao(g),g.lastChild),n||i)for(;Ao(g);)s.before(Ao(g));else s.before(g)}})}function G0(e,t){mR(()=>{e=Jt?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){const i=Jm("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function LR(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=LR(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function v7(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=LR(e))&&(n&&(n+=" "),n+=t);return n}function Xg(e){return typeof e=="object"?v7(e):e??""}var zS=[...`
45
+ \r\f \v\uFEFF`];function y7(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||zS.includes(n[s-1]))&&(a===n.length||zS.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function Qc(e,t,r,n,i,o){var s=e[xy];if(Gr||s!==r||s===void 0){var a=y7(r,n,o);(!Gr||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[xy]=r}else if(o&&i!==o)for(var l in o){var c=!!o[l];(i==null||c!==!!i[l])&&e.classList.toggle(l,c)}return o}var NR,Hc=new WeakMap,am=new WeakMap,Jg=new WeakMap,BS=new WeakSet,DR=class{constructor(e){B0(this,BS),Lt(this,Hc,new WeakMap),Lt(this,am,void 0),Lt(this,Jg,void 0),St(Jg,this,e)}observe(e,t){var r=G(Hc,this).get(e)||new Set;return r.add(t),G(Hc,this).set(e,r),Yt(BS,this,b7).call(this).observe(e,G(Jg,this)),()=>{var n=G(Hc,this).get(e);n.delete(t),n.size===0&&(G(Hc,this).delete(e),G(am,this).unobserve(e))}}};NR=DR;function b7(){return G(am,this)??St(am,this,new ResizeObserver(e=>{for(var t of e){NR.entries.set(t.target,t);for(var r of G(Hc,this).get(t.target)||[])r(t)}}))}Ee(DR,"entries",new WeakMap);function Qg(e,t){return e===t||e?.[Ed]===t}function Pd(e=D0(),t,r,n){var i=Zr.r,o=Jt;return mR(()=>{var s,a;return H0(()=>{s=a,a=n?.()||[],zn(()=>{Qg(r(...a),e)||(t(e,...a),s&&Qg(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;const c=()=>{a&&Qg(r(...a),e)&&t(null,...a)},u=l.teardown;l.teardown=()=>{c(),u?.()}}}),e}var Ch=!1;function w7(e){var t=Ch;try{return Ch=!1,[e(),Ch]}finally{Ch=t}}function nt(e,t,r,n){var i=!Df||(r&2)!==0,o=(r&8)!==0,s=(r&16)!==0,a=n,l=!0,c=void 0,u=()=>s&&i?(c??(c=Yd(n)),R(c)):(l&&(l=!1,a=s?zn(n):n),a);let d;if(o){var f=Ed in e||qx in e;d=jl(e,t)?.set??(f&&t in e?x=>e[t]=x:void 0)}var h,g=!1;o?[h,g]=w7(()=>e[t]):h=e[t],h===void 0&&n!==void 0&&(h=u(),d&&(i&&b3(t),d(h)));var m;if(i?m=()=>{var x=e[t];return x===void 0?u():(l=!0,x)}:m=()=>{var x=e[t];return x!==void 0&&(a=void 0),x===void 0?a:x},i&&(r&4)===0)return m;if(d){var v=e.$$legacy;return(function(x,$){return arguments.length>0?((!i||!$||v||g)&&d($?m():x),x):m()})}var b=!1,I=((r&1)!==0?Yd:Qx)(()=>(b=!1,m()));o&&R(I);var C=Jt;return(function(x,$){if(arguments.length>0){const P=$?R(I):i&&o?Xc(x):x;return He(I,P),b=!0,a!==void 0&&(a=P),x}return ra&&b||(C.f&16384)!==0?I.v:R(I)})}function S7(e){return new I7(e)}var el=new WeakMap,as=new WeakMap,I7=class{constructor(e){Lt(this,el,void 0),Lt(this,as,void 0);var t=new Map,r=(i,o)=>{var s=D3(o,!1,!1);return t.set(i,s),s};const n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return R(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===qx?!0:(R(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return He(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});St(as,this,(e.hydrate?d7:$R)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),(!e?.props?.$$host||e.sync===!1)&&rt(),St(el,this,n.$$events);for(const i of Object.keys(G(as,this)))i==="$set"||i==="$destroy"||i==="$on"||Gd(this,i,{get(){return G(as,this)[i]},set(o){G(as,this)[i]=o},enumerable:!0});G(as,this).$set=i=>{Object.assign(n,i)},G(as,this).$destroy=()=>{f7(G(as,this))}}$set(e){G(as,this).$set(e)}$on(e,t){G(el,this)[e]=G(el,this)[e]||[];const r=(...n)=>t.call(this,...n);return G(el,this)[e].push(r),()=>{G(el,this)[e]=G(el,this)[e].filter(n=>n!==r)}}$destroy(){G(as,this).$destroy()}},jR;typeof HTMLElement=="function"&&(jR=class extends HTMLElement{constructor(e,t,r){super(),Ee(this,"$$ctor",void 0),Ee(this,"$$s",void 0),Ee(this,"$$c",void 0),Ee(this,"$$cn",!1),Ee(this,"$$d",{}),Ee(this,"$$r",!1),Ee(this,"$$p_d",{}),Ee(this,"$$l",{}),Ee(this,"$$l_u",new Map),Ee(this,"$$me",void 0),Ee(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){const n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{const o=Jm("slot");n!=="default"&&(o.name=n),lo(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},r=k7(this);for(const n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(const n of this.attributes){const i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=rp(i,n.value,this.$$p_d,"toProp"))}for(const n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=S7({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=W3(()=>{H0(()=>{this.$$r=!0;for(const n of Jp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];const i=rp(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(const n in this.$$l)for(const i of this.$$l[n]){const o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=rp(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return Jp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function rp(e,t,r,n){const i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function k7(e){const t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function Y0(e,t,r,n,i,o){let s=class extends jR{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return Jp(t).map(a=>(t[a].attribute||a).toLowerCase())}};return Jp(t).forEach(a=>{Gd(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=rp(a,l,t),this.$$d[a]=l;var c=this.$$c;c&&(jl(c,a)?.get?c[a]=l:c.$set({[a]:l}))}})}),n.forEach(a=>{Gd(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}function T7(e,t=!1){if(typeof e=="boolean")return e;if(e==null)return t;const r=String(e).trim().toLowerCase();return r===""?t:["false","0","off","no"].includes(r)?!1:["true","1","on","yes"].includes(r)?!0:!!r}function E7(e){return e!==null&&T7(e,!0)}var C7=(e,t)=>{const r=e.$$p_d;return r?Object.entries(r).some(([n,i])=>i.type==="Boolean"&&(i.attribute??n.toLowerCase())===t):!1};function x7(e){const t=e.prototype.attributeChangedCallback;return class extends e{attributeChangedCallback(r,n,i){const o=i!==null&&C7(this,r)&&!E7(i)?null:i;t?.call(this,r,n,o)}}}function R7(e){const t=new Set,r=/<\/?([a-zA-Z][a-zA-Z0-9._-]*)(?=[\t\n\f\r />])/g;let n=null;for(;(n=r.exec(e))!==null;){const i=String(n[1]||"").trim();i&&i.includes("-")&&t.add(i)}return t}var zR=e=>{const t=[],r=[];if(!e||typeof e!="object"||Array.isArray(e))return{valid:!1,errors:["Config must be an object."],warnings:r};const n=e,i=n.markup,o=n.elements,s=n.models;if(typeof i!="string"&&t.push("`markup` must be a string."),(!o||typeof o!="object"||Array.isArray(o))&&t.push("`elements` must be an object."),Array.isArray(s)||t.push("`models` must be an array."),t.length>0)return{valid:!1,errors:t,warnings:r};const a=o,l=s,c=Object.keys(a);for(const[h,g]of Object.entries(a)){if(typeof h!="string"||h.trim().length===0){t.push("`elements` contains an empty tag name.");continue}if(typeof g!="string"||g.trim().length===0){t.push(`Element "${h}" must map to a non-empty package spec.`);continue}try{AT(h,g)}catch{t.push(`Element "${h}" has invalid package spec "${g}".`)}}const u=new Set;for(const[h,g]of l.entries()){const m=g?.element;if(typeof m!="string"||m.trim().length===0){t.push(`Model at index ${h} is missing a valid "element" reference.`);continue}u.add(m),m in a||t.push(`Model element "${m}" is not declared in \`elements\`.`)}const d=R7(i);for(const h of d)h in a||t.push(`Markup tag "${h}" is not declared in \`elements\`.`);const f=new Set([...u,...d]);for(const h of c)f.has(h)||r.push(`Element "${h}" is declared in \`elements\` but not referenced by models or markup.`);return{valid:t.length===0,errors:t,warnings:r}},P7=e=>{const t=zR(e);if(!t.valid)throw new Error(`Invalid PIE config contract: ${t.errors.join(" | ")}`)},_7=e=>{const t=Object.entries(e.config.elements).reduce((a,[l,c])=>{const u=AT(l,c);return{...a,[l]:{versionedName:u,package:c}}},{}),r=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=(a,l,c)=>{const u=new RegExp(`(<\\/?)${r(l)}(?=[\\t\\n\\f\\r />])`,"g");return a.replace(u,(d,f)=>`${f}${c}`)},i=Object.entries(t).reduce((a,[l,{versionedName:c}])=>l!==c?n(a,l,c):a,e.config.markup),o=Object.values(t).reduce((a,{versionedName:l,package:c})=>({...a,[l]:c}),{}),s=e.config.models.map(a=>{const l=a.element,c=t[l];if(c&&c.versionedName!==l)return{...a,element:c.versionedName};if(o[l])return a;const u=Object.entries(t).filter(([d])=>{const{baseName:f,existingEncodedVersion:h}=Od(d);return h!==void 0&&f===l});if(u.length===1){const[,{versionedName:d}]=u[0];return{...a,element:d}}return a});return{...e,config:{...e.config,elements:o,markup:i,models:s}}},Ni=lf("pie-scoring",()=>cf()),BR=(e,t)=>{if(t===Ro.player){Ni.debug(`[findPieController] ℹ️ ${e} delivered as player.js; using server-processed models`);return}const r=wm();Ni.debug(`[findPieController] Looking for controller for: ${e}`),Ni.debug("[findPieController] Registry has entries for:",Object.keys(r));const n=r[e];if(!n){Ni.error(`[findPieController] ❌ No registry entry found for element: ${e}`),Ni.error("[findPieController] Available element names:",Object.keys(r)),Ni.error("[findPieController] Full registry:",r);return}Ni.debug(`[findPieController] Found registry entry for ${e}:`,{package:n.package,tagName:n.tagName,hasController:!!n.controller,controllerKeys:n.controller?Object.keys(n.controller):[],bundleType:n.bundleType});const i=n.controller??void 0;return i?Ni.debug(`[findPieController] ✅ Controller found for ${e} with functions:`,Object.keys(i)):Ni.debug(`[findPieController] ℹ️ No controller for ${e}; its model is used as given`),i},A7=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ").replace(/\r/g,"\\d "),$7=(e,t)=>{const r=A7(t);return e.querySelector(`[id="${r}"]`)||e.querySelector(`[pie-id="${r}"]`)},M7=async(e,t,r,n)=>e.outcome.call(e,t,r,n);async function O7(e,t,r={}){const n=r.container??document,i=r.models??e.models??[],o={...r.env,mode:"evaluate",partialScoring:r.env?.partialScoring},s=await Promise.all(i.map(async a=>{const l=$7(n,a.id);Ni.debug("found pieEl %O for model id %s",l,a.id);const c=$T(t,a.id,a.element);if(l){const u=BR(l.localName,r.bundleType);if(u?.outcome)return{...c,...await M7(u,a,c,o)};Ni.debug("ignore %s (no controller)",l.localName)}else Ni.debug("ignore %s (no element found for %s)",a.id)}));return Ni.debug("scorePieItem result",s),{results:r.includeMissingResults?s:s.filter(Boolean)}}var jy="data-pie-content-styles",FR="--pie-content-styles",L7=new Set(["inherit","initial","revert","revert-layer","unset"]),HR=e=>{const t=e.style?.getPropertyValue(FR).trim().toLowerCase();if(t)return!L7.has(t);const r=e.cssRules;if(!r)return!1;for(const n of Array.from(r))if(HR(n))return!0;return!1},lm="data-pie-content-styles",UR="host",Qm=()=>typeof document<"u"&&!!document.head;function K0(){return Qm()?document.documentElement.getAttribute(lm)===UR:!1}function N7(){return Qm()?getComputedStyle(document.documentElement).getPropertyValue(FR).trim()!==""?!0:qR({excludeInstalled:!1})>0:!1}function D7(e,t){if(!Qm())return"no-document";if(K0())return"opted-out";if(document.querySelector(`style[${jy}]`))return"already-installed";if(WR()>0)return"host-supplied";if(!e)return"no-document";const r=document.createElement("style");return r.setAttribute(jy,t),r.textContent=e,document.head.prepend(r),j7(r),"installed"}var xh=null,j7=e=>{if(xh?.(),typeof MutationObserver>"u")return;const t=()=>{n.disconnect(),document.removeEventListener("load",i,!0),xh===t&&(xh=null)},r=()=>{if(!e.isConnected){t();return}(K0()||WR()>0)&&(e.remove(),t())},n=new MutationObserver(o=>{o.some(s=>s.type==="attributes"||Array.from(s.addedNodes).some(a=>a.nodeName==="STYLE"||a.nodeName==="LINK"))&&r()}),i=o=>{o.target?.nodeName==="LINK"&&r()};n.observe(document.head,{childList:!0}),n.observe(document.documentElement,{attributes:!0,attributeFilter:[lm]}),document.addEventListener("load",i,!0),xh=t},qR=({excludeInstalled:e})=>{const t=e?`:not([${jy}])`:"",r=document.querySelectorAll(`style${t}, link[rel~="stylesheet"]${t}`);let n=0;for(const i of Array.from(r)){let o;try{o=i.sheet?.cssRules}catch{continue}if(o){for(const s of Array.from(o))if(HR(s)){n+=1;break}}}return n},WR=()=>qR({excludeInstalled:!0}),Zg=!1,z7=[];function B7(e){if(!Qm()||Zg)return;const t=()=>{Zg||K0()&&!N7()&&(Zg=!0,console.warn(`[${e}] No PIE content stylesheet found. This document sets ${lm}="${UR}", so ${e} did not install one. Authored content that relies on shared classes (.numbered-paragraph, .p-number, div.passage-title, the kds-* families, answer-eliminator styles) will render unstyled. Either import "@pie-players/pie-theme/components.css" in the host app, or drop the ${lm} attribute to let the player install it.`))};if(typeof requestAnimationFrame!="function"){t();return}requestAnimationFrame(()=>requestAnimationFrame(t)),typeof window<"u"&&document.readyState!=="complete"&&window.addEventListener("load",()=>t(),{once:!0}),typeof setTimeout=="function"&&z7.push(setTimeout(t,1e3))}var F7={"nl-NL":()=>Mr(()=>import("./chunks/nl-NL-8b7e6d4b.js"),[],import.meta.url)},H7=["en-US","nl-NL"];async function U7(e){const t=F7[e];if(!t)throw new Error(`No bundled i18n catalog for locale: ${e}`);return(await t()).default}function Zd(e){return e?e.trim().replace(/_/g,"-").split(/[.@]/)[0].toLowerCase():""}function q7(e){const t=Zd(e);if(!t)return[];const r=t.split("-"),n=[];for(let i=r.length;i>0;i--){const o=r.slice(0,i);o.length>1&&o[o.length-1].length===1||n.push(o.join("-"))}return n}function W7(e,t){for(const r of q7(e)){const n=t.find(i=>Zd(i)===r);if(n!=null)return n}}var V7={common:{close:"Close",cancel:"Cancel",save:"Save",reset:"Reset",retry:"Retry",back:"Back",next:"Next",previous:"Previous",submit:"Submit",continue:"Continue",finish:"Finish",yes:"Yes",no:"No",ok:"OK",any:"Any",off:"Off",auto:"Auto",all:"All",none:"None",loading:"Loading…",error:"Error",settings:"Settings",language:"Language",theme:"Theme",preview:"Preview",author:"Author",unknown:"Unknown",untitled:"Untitled",apply:"Apply",enabled:"Enabled",disabled:"Disabled",closeA11y:"Close",settingsA11y:"Open settings menu"},player:{passage:"Passage",passages:"Passages",question:"Question",questionNumbered:"Question {position}",questions:"Questions",items:"Items",section:"Section",loadingSection:"Loading section content…",sectionLoadError:"Section content could not be loaded.",loadingPassage:"Loading passage content…",configurationError:"Configuration Error",playerError:"Player Error",authoringBackendError:"Authoring Backend Configuration Error",itemLoadError:"Question could not be loaded.",sectionTabsA11y:"Section content tabs",passagesRegionA11y:"Passages",itemsRegionA11y:"Items",sectionToolsA11y:"Section tools",scrollDownA11y:"Scroll down",resizePanels:"Resize panels",resizePassagesAndItemsA11y:"Resize passages and items panels",resizeMediaRegion:"Resize media region",resizeQuestionAndMediaA11y:"Resize question and media panels",resizePassageAndMediaA11y:"Resize passage and media panels",assessment:{sectionPosition:"Section {position} of {total}",noSections:"No sections",loadFailed:"The assessment could not be loaded. Try again.",restoreFailed:"Your saved answers for this section could not be restored. Try again."},formative:{checkAnswer:"Check answer",tryAgain:"Try again",answerRecorded:"Answer recorded.",correct:"Correct.",partlyCorrect:"Partly correct.",notCorrect:"Not correct.",notAutoScored:"Answer recorded. This question is not scored automatically.",checkFailed:"This question could not be checked. Try again.",triesLeft:{one:"{count} try left.",other:"{count} tries left."}},timedMedia:{waitingForMedia:"Questions will appear as the media plays.",questionAvailable:"Question {position} is now available.",playbackPaused:"Playback paused. Answer question {position} to continue.",playbackAdvisory:"Answer question {position} before continuing with the media.",playbackReleased:"Answer accepted. Continue playing the media."}},toolkit:{toolsA11y:"Assessment tools",toolbarInitError:"Unable to initialize assessment toolkit.",settingsTitle:"Settings",closeSettingsA11y:"Close settings",dragPanelA11y:"Drag panel",closePanelA11y:"Close panel",resizeWindow:"Resize window",minimize:"Minimize",maximize:"Maximize",minimizePanelA11y:"Minimize panel",maximizePanelA11y:"Maximize panel",window:{moveLeftA11y:"Move tool left",moveRightA11y:"Move tool right",moveUpA11y:"Move tool up",moveDownA11y:"Move tool down",shrinkA11y:"Shrink tool window",growA11y:"Grow tool window",centerA11y:"Center tool window",closeA11y:"Close tool"},placement:{controlsA11y:"Move and rotate",rotateClockwiseA11y:"Rotate {degrees}° clockwise",rotateCounterclockwiseA11y:"Rotate {degrees}° counterclockwise"},announce:{movedUp:"Moved up to {position}",movedDown:"Moved down to {position}",movedLeft:"Moved left to {position}",movedRight:"Moved right to {position}",rotatedTo:"Rotated to {degrees} degrees"}},tools:{calculator:{name:"Calculator",nameBasic:"Basic Calculator",nameScientific:"Scientific Calculator",nameGraphing:"Graphing Calculator",description:"Multi-type calculator (basic, scientific, graphing)",openedBasic:"Basic calculator opened",openedScientific:"Scientific calculator opened",openedGraphing:"Graphing calculator opened",closedBasic:"Basic calculator closed",closedScientific:"Scientific calculator closed",closedGraphing:"Graphing calculator closed",toolA11y:"Calculator tool",loading:"Loading calculator…",providerUnavailable:"The calculator is unavailable."},graph:{name:"Graph",description:"Coordinate plane",buttonA11y:"Graph, coordinate plane",tooltip:"Graph",toolA11y:"Graph tool — draw points and lines on a coordinate grid",canvasA11y:"Graph canvas — use tools to add points and draw lines",grid:"Grid:",gridOpacityA11y:"Grid opacity",pointA11y:"Graph point {id}",modeSelector:"Selector",modeSelectorHint:"Selector: click and drag points to move them or associated lines.",modePoint:"Point",modePointHint:"Point: click on the grid to add points.",modeLine:"Line",modeLineHint:"Line: click a starting point, then an ending point to draw a line.",modeDelete:"Delete",modeDeleteHint:"Delete: click on a point to delete it and any connected lines."},periodicTable:{name:"Periodic Table",description:"Chemistry periodic table reference",buttonA11y:"Periodic Table, chemistry reference",tooltip:"Periodic Table",toolA11y:"Periodic table — select an element to view its details",elementsA11y:"Periodic table elements",showAllA11y:"Show all elements",allElements:"All Elements",atomicMass:"Atomic Mass",atomicNumber:"Atomic No",electronConfig:"Electron Config",phase:"Phase",filterByA11y:"Filter by {category}",elementA11y:"{name}, Symbol: {symbol}, Atomic number: {number}, Atomic mass: {mass}, Category: {category}",outsideFilterA11y:", outside the current filter",category:{unknown:"Unknown",alkaliMetal:"Alkali Metal",alkalineEarthMetal:"Alkaline Earth Metal",transitionMetal:"Transition Metal",postTransitionMetal:"Post-transition Metal",metalloid:"Metalloid",diatomicNonmetal:"Diatomic Nonmetal",polyatomicNonmetal:"Polyatomic Nonmetal",nobleGas:"Noble Gas",lanthanide:"Lanthanide",actinide:"Actinide"}},ruler:{name:"Ruler",description:"On-screen ruler for measurements",buttonA11y:"Ruler",tooltip:"Ruler",toolA11y:"Draggable and rotatable ruler measurement tool",unitSelectionA11y:"Ruler unit selection",inches:"Inches",centimeters:"Centimeters",inchesInSentence:"inches",centimetersInSentence:"centimeters",switchToInchesA11y:"Switch to inches",switchToCentimetersA11y:"Switch to centimeters",switchedTo:"Switched to {unit}",applicationA11y:"Ruler tool. Use arrow keys to move, Shift+arrows to rotate, PageUp or PageDown for fine rotation, U to toggle units. Current unit: {unit}",imageAlt:"Ruler showing {unit}"},protractor:{name:"Protractor",description:"On-screen protractor for angle measurements",buttonA11y:"Protractor",tooltip:"Protractor",toolA11y:"Protractor tool. Use arrow keys to move, Shift+arrows to rotate, and PageUp or PageDown for fine rotation.",roleA11y:"Draggable and rotatable protractor measurement tool",imageAlt:"Protractor with 180-degree semicircular scale marked from 0 to 180 degrees in both directions, with degree markings every 10 degrees"},dictionary:{name:"Dictionary",description:"Look up word definitions",buttonA11y:"Dictionary, look up word definitions",tooltip:"Dictionary",toolA11y:"Dictionary"},pictureDictionary:{name:"Picture Dictionary",description:"Look up pictures for words",buttonA11y:"Picture Dictionary, look up pictures for words",tooltip:"Picture Dictionary",toolA11y:"Picture Dictionary"},dictionarySpanish:{name:"Spanish Dictionary",description:"Look up word definitions in Spanish",buttonA11y:"Spanish Dictionary, look up word definitions in Spanish",tooltip:"Spanish Dictionary",toolA11y:"Spanish Dictionary"},pictureDictionarySpanish:{name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",buttonA11y:"Spanish Picture Dictionary, look up pictures for words in Spanish",tooltip:"Spanish Picture Dictionary",toolA11y:"Spanish Picture Dictionary"},lineReader:{name:"Line Reader",description:"Reading guide overlay",buttonA11y:"Line Reader, reading guide",tooltip:"Line Reader",roleA11y:"Draggable and resizable reading guide overlay",close:"Close line reader",resizeWindowA11y:"Drag to resize the reading window",resizeFrameA11y:"Drag to resize the frame and window width",windowHeightAnnounce:"Reading window height {pixels} pixels",frameHeightAnnounce:"Frame height {pixels} pixels",widthAnnounce:"Width {pixels} pixels",applicationA11y:"Line Reader tool. A clear reading window inside an obscuring frame. Use arrow keys to move, +/- to resize the reading window, Escape to close. Reading window height: {paneHeight} pixels, Frame height: {frameHeight} pixels",resizeWindowFullA11y:"Resize the reading window. Drag, or use the up and down arrow keys to change its height. Current height {paneHeight} pixels",resizeFrameFullA11y:"Resize the frame. Drag, or use the up and down arrow keys to change the frame height and the left and right arrow keys to change the width. Current frame height {frameHeight} pixels, width {width} pixels"},answerEliminator:{name:"Answer Eliminator",description:"Strike through answer choices",buttonA11y:"Strike Through, eliminate answer choices",tooltip:"Strike Through"},highlighter:{name:"Highlighter",description:"Highlight and annotate text",buttonA11y:"Highlight text",tooltip:"Highlight"},annotationToolbar:{name:"Annotation",description:"Highlight and annotate text",buttonA11y:"Annotate, highlight and mark up text",tooltip:"Annotate",toolbarA11y:"Text annotation toolbar",underline:"Underline",underlineA11y:"Underline selected text",readAloud:"Read Aloud",readAloudA11y:"Read selected text aloud",remove:"Remove",removeA11y:"Remove this annotation",clearAll:"Clear All",clearAllA11y:"Clear all annotations from document",highlightYellowA11y:"Yellow highlight",highlightPinkA11y:"Pink highlight",highlightBlueA11y:"Blue highlight",highlightGreenA11y:"Green highlight"},theme:{name:"Theme",description:"Accessible themes and contrast",buttonA11y:"Theme, change colors and contrast",tooltip:"Theme",selectorA11y:"Theme selector",hint:"Select a theme to improve readability and reduce eye strain.",selectA11y:"Select theme",selectCurrentA11y:"Select theme. Current theme: {name}",optionUnavailableA11y:"{name}, unavailable",unavailableName:"Unavailable theme: {id}",unavailableDescription:"PIE's managed base theme remains active until this theme becomes available again.",unavailableStatus:"The selected theme is unavailable. PIE's managed base theme is active until it becomes available again."},textToSpeech:{name:"Text to Speech",description:"Read content aloud",inline:{controlsA11y:"Reading controls",playbackSpeedA11y:"Playback speed",rewindA11y:"Rewind",fastForwardA11y:"Fast-forward",stopA11y:"Stop reading",initializing:"Initializing text-to-speech",initFailed:"Unable to initialize text-to-speech. Try again.",starting:"Starting reading",started:"Reading started",resumed:"Reading resumed",pausedAnnouncement:"Reading paused",stopped:"Reading stopped",switchedSection:"Reading switched to another section",startFailed:"Unable to start reading",skippedForward:"Skipped forward",skipForwardFailed:"Unable to skip forward",skippedBackward:"Skipped backward",skipBackwardFailed:"Unable to skip backward",speedChangeFailed:"Unable to change playback speed",speedAnnounce:"Playback speed {label}",playA11y:"Play reading",pauseA11y:"Pause reading",resumeA11y:"Resume reading"}},signLanguage:{name:"Sign Language",description:"Signed alternate for authored content",generic:"Sign language",unknown:"Sign language ({code})",ase:"American Sign Language",bfi:"British Sign Language",fsl:"French Sign Language",gss:"Greek Sign Language",mfs:"Mexican Sign Language",signedEnglish:"Signed English",regionA11y:"{language} translation"},audioTranscript:{name:"Audio Transcript",description:"Text transcript of audio content",regionA11y:"Transcript"}},debug:{session:"Session",sessionData:"Session Data",sessionDataPersistent:"PIE Session Data (Persistent)",noItemSessionYet:"No item session data yet. Interact with the item to see updates here.",itemSessionsSnapshot:"Item Sessions Snapshot",sectionControllerUnavailable:"Section controller not available for this section yet.",filteredModel:"Filtered Model",environment:"Environment",events:"Events",controllerEvents:"Controller Events",instrumentation:"Instrumentation",databaseState:"Database state",sessionDb:"Session DB (Server)",noRows:"No rows",noRecords:"No instrumentation records yet.",selectRecord:"Select a record to inspect details.",selectEvent:"Select an event to inspect payload details.",showRawTables:"Show raw tables",showReconstructedSnapshots:"Show reconstructed snapshots",showSectionRequest:"Show section request",showAssessmentRequest:"Show assessment request",liveUpdatesUnsupported:"Live updates are not supported in this browser",liveUpdatesDisconnected:"Live updates disconnected; retrying…",fieldType:"Type:",fieldTarget:"Target:",fieldItem:"Item:",fieldCanonical:"Canonical:",fieldIntent:"Intent:",fieldDuplicates:"Duplicates:",fieldSemanticRepeats:"Semantic Repeats:",dragItemSessionPanelA11y:"Drag item session panel",debuggerTabsA11y:"Debugger tabs",sessionDataJsonA11y:"Session data JSON",environmentJsonA11y:"Environment JSON",filteredModelJsonA11y:"Filtered model JSON",sectionSessionJsonA11y:"Section session snapshot JSON",eventLevelFilterA11y:"Event level filter",controllerEventDetailsA11y:"Controller event details",instrumentationFilterA11y:"Filter instrumentation record type",instrumentationDetailsA11y:"Instrumentation record details",toggleSessionPanelA11y:"Toggle session panel",toggleEventPanelA11y:"Toggle event broadcast panel",toggleDatabasePanelA11y:"Toggle database state panel",toggleInstrumentationPanelA11y:"Toggle instrumentation panel",pnp:{title:"PNP Profile",noAssessmentBound:"No assessment bound",determinationReadOnly:"Determination (read-only)",toolsEditor:"Tools Editor",enforcement:"PNP enforcement",allAvailableTools:"All available tools",clearPlacement:"Clear placement",tool:"Tool",placement:"Placement",provider:"Provider",simulation:"PNP simulation",resolvedTools:"Resolved Tools (toolkit)",provenanceSummary:"Tool Policy Provenance Summary",perToolDecisions:"Per-Tool Decisions",policyDiagnostics:"Policy Diagnostics",profileReadOnly:"PNP Profile (read-only)"},tts:{title:"TTS settings",closeA11y:"Close TTS settings",toolbarLayoutMode:"Toolbar layout mode",reservedRow:"Reserved row",expandingRow:"Expanding row",floatingOverlay:"Floating overlay",leftAlignedControls:"Left-aligned controls",inlineSpeedButtons:"Inline speed buttons",resetToDefaults:"Reset to defaults",mathHighlighting:"Math highlighting",checkingAvailability:"Checking availability…",recheck:"Recheck",voice:"Voice",bestAvailableVoice:"Best available voice (auto)",unnamedVoice:"Unnamed voice",apiEndpoint:"API endpoint",gender:"Gender",any:"Any",male:"Male",female:"Female",neutral:"Neutral",engine:"Engine",neural:"Neural",standard:"Standard",providerDefault:"Provider default",format:"Format",sampleRate:"Sample rate",speechMarks:"Speech marks",word:"Word",wordAndSentence:"Word + sentence",voiceType:"Voice type",wavenetVoiceType:"WaveNet",studioVoiceType:"Studio",plainText:"Plain text",sampleText:"Sample text",resetSample:"Reset sample",providerAvailable:"Provider available.",providerUnavailable:"Provider unavailable.",providerCheckFailed:"Provider availability check failed.",providerNotChecked:"Provider availability has not been checked yet.",webSpeechUnavailable:"Web Speech API is not available in this browser.",browserNoVoices:"Browser text-to-speech is available, but no voices were returned yet.",browserUnavailable:"Browser text-to-speech is not available.",googleUnavailable:"Google Cloud TTS is not available from the configured API.",pollyUnavailable:"AWS Polly is not available from the configured API.",recommendedVoices:"Recommended voices",allVoices:"All available voices",previewVoice:"Preview voice",stopPreview:"Stop preview",applying:"Applying…",ssmlPreviewUnsupported:"SSML preview is not supported in the Browser backend.",pollySsmlHint:"Some Polly neural voices reject certain SSML tags (for example emphasis). Use basic SSML tags if preview fails.",mathHighlightParts:"Highlighting each part of a formula as it is read, falling back to the whole formula when alignment is uncertain.",mathHighlightBlock:"Highlighting each formula as a single block instead of breaking it into parts.",previewFailed:"Failed to play preview audio.",previewNoAudio:"Preview response did not include audio content.",previewEnterText:"Enter preview text before starting playback.",previewUnavailable:"Cannot preview while this service is unavailable.",browserSynthesisUnavailable:"Browser speech synthesis is unavailable.",browserSynthesisEndedEarly:"Browser speech synthesis ended before audio started. Restart the browser and try again.",browserSynthesisQueueFailed:"Browser speech synthesis failed to queue preview audio.",browserPreviewFailed:"Failed to play browser voice preview.",ssmlWordTrackingDisabled:"Google SSML preview preserves authored SSML, so word tracking is disabled.",applyUnavailable:"Cannot apply settings while this service is unavailable.",coordinatorUnavailable:"Toolkit coordinator is not available for text-to-speech updates."}}},ev="en-US",G7=new Set(["ar","ckb","dv","fa","he","iw","ks","ku","nqo","ps","sd","syr","ug","ur","yi"]),Y7=new Set(["zero","one","two","few","many","other"]);function FS(e){if(typeof e!="object"||e===null)return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Y7.has(r))}function HS(e){try{const r=new Intl.Locale(e).textInfo;if(r?.direction==="rtl"||r?.direction==="ltr")return r.direction}catch{}const t=Zd(e).split("-")[0]??"";return G7.has(t)?"rtl":"ltr"}var VR=class np{constructor(t={}){Ee(this,"locale",void 0),Ee(this,"fallbackLocale",void 0),Ee(this,"catalogs",void 0),Ee(this,"customMessages",void 0),Ee(this,"loading",void 0),Ee(this,"listeners",new Set),Ee(this,"config",void 0),this.config={...t},this.fallbackLocale=Rh(t.fallbackLocale)||"en-US",this.catalogs=new Map([[ev,V7]]),this.customMessages={...t.customMessages??{}},this.loading=new Map,this.locale=this.resolveLocaleTag(t.locale)??"en-US"}async initialize(t){if(this.config={...this.config,...t},t.customMessages)for(const[r,n]of Object.entries(t.customMessages))this.addCustomMessages(r,n);await this.setLocale(t.locale??this.locale)}getLocale(){return this.locale}async setLocale(t){const r=this.resolveLocaleTag(t);if(!r){this.locale=Rh(t)||"en-US",this.notify();return}if(!this.catalogs.has(r)){const n=this.loading.get(r);if(n)await n;else{const i=this.loadCatalog(r);this.loading.set(r,i);try{await i}finally{this.loading.delete(r)}}}this.locale=r,this.notify()}t(t,r){const n=this.lookup(t);return n===void 0?(this.config.onMissingKey?.(t,this.locale),t):US(n,r)}plural(t,r){const n=this.lookupNode(t);return n===void 0||!FS(n)?this.t(t,r):US(n[this.selectPluralCategory(r.count)]??n.other,r)}getDirection(){return HS(this.locale)}getAvailableLocales(){return[...new Set([...this.catalogs.keys(),...this.config.availableLocales??[],...Object.keys(this.customMessages)])]}isLocaleLoaded(t){const r=this.resolveLocaleTag(t);return r!==void 0&&this.catalogs.has(r)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}hasKey(t){return this.lookup(t)!==void 0}addCustomMessages(t,r){const n=Rh(t);this.customMessages[n]=GR(this.customMessages[n]??{},r),this.notify()}withLocale(t){const r=this.resolveLocaleTag(t)??Rh(t);if(r===this.locale)return this;const n=new np({...this.config,locale:r});return n.locale=r||"en-US",n.catalogs=this.catalogs,n.customMessages=this.customMessages,n.loading=this.loading,n}formatNumber(t,r){try{return new Intl.NumberFormat(this.locale,r).format(t)}catch{return new Intl.NumberFormat(ev,r).format(t)}}formatDate(t,r){try{return new Intl.DateTimeFormat(this.locale,r).format(t)}catch{return new Intl.DateTimeFormat(ev,r).format(t)}}getBundle(t=this.locale){const r=this.resolveLocaleTag(t);if(!r)return;const n=this.catalogs.get(r);if(n)return{locale:r,translations:n,direction:HS(r)}}resolveLocaleTag(t){if(!t)return;const r=this.getAvailableLocales(),n=W7(t,r);if(n)return n;const i=Zd(t).split("-")[0];if(i)return r.find(o=>Zd(o).split("-")[0]===i)}async loadCatalog(t){const r=this.config.loadCatalog;if(r)try{this.catalogs.set(t,await r(t))}catch(n){throw new Error(`Failed to load i18n catalog for locale: ${t}`,{cause:n})}}lookupNode(t){const r=[this.customMessages[this.locale],this.catalogs.get(this.locale),this.customMessages[this.fallbackLocale],this.catalogs.get(this.fallbackLocale)];for(const n of r){const i=K7(n,t);if(i!==void 0)return i}}lookup(t){const r=this.lookupNode(t);if(typeof r=="string")return r;if(r!==void 0&&FS(r))return r.other}selectPluralCategory(t){let r=np.pluralRules.get(this.locale);if(!r){try{r=new Intl.PluralRules(this.locale)}catch{return t===1?"one":"other"}np.pluralRules.set(this.locale,r)}return r.select(t)}notify(){for(const t of this.listeners)t()}};Ee(VR,"pluralRules",new Map);function Rh(e){return e?e.trim().replace(/_/g,"-"):""}function K7(e,t){if(!e)return;let r=e;for(const n of t.split("."))if(typeof r!="object"||r===null||(r=r[n],r===void 0))return;return r}function US(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>{const i=t[n];return i==null?r:String(i)}):e}function GR(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];i&&typeof i=="object"&&o&&typeof o=="object"?r[n]=GR(o,i):r[n]=i}return r}function X7(e={}){return new VR({loadCatalog:U7,availableLocales:H7,...e})}var J7=`/* Content classes for authored assessment content, installed as a
46
+ document-level stylesheet by every player (see players-shared
47
+ ui/content-styles.ts).
48
+
49
+ A rule applies inside a \`[data-pie-content]\` element only, which each player
50
+ sets on the root it renders content into. Several selectors are bare
51
+ (\`h1\`-\`h6\`, \`table\`, \`th\`, \`.table\`, \`.center\`), and unscoped they restyled
52
+ the host page around the player. \`:where()\` keeps each selector's
53
+ specificity, and a host that renders authored markup itself marks its
54
+ container with the attribute.
55
+
56
+ The exception is a rule whose selector requires a name only authored
57
+ content carries: a KDS class (\`kds-*\`, \`Kds*\`), MathJax output (\`mjx-*\`,
58
+ \`TEX-*\`) or a legacy content class (\`.frac\`, \`.noprint\`, \`.passage-title\`
59
+ and the rest tests/content-styles-confinement.test.ts lists). Those stay
60
+ document-wide, because elements portal menus and popovers holding authored
61
+ markup to \`<body>\`, outside every \`[data-pie-content]\` root: an
62
+ inline-dropdown's choices keep their KDS fractions and MathJax glyph fixes
63
+ there. A rule that requires an authored-colour marker stays document-wide
64
+ for the same reason. The \`:root\` sentinel below and the \`[data-color-scheme]\`
65
+ rule that captures a scheme's ink and page stay unscoped too.
66
+
67
+ Colour values resolve through the canonical --pie-* tokens with the original
68
+ literal kept as the no-theme last resort. The literals came from content
69
+ authored against a white page: \`black\` borders, \`lightgray\` table headers and
70
+ a white loading scrim are invisible or illegible the moment the surface is
71
+ not white, and a host that only swaps the theme cannot reach them. Ink takes
72
+ --pie-text (DaisyUI base-content, the one family guaranteed against the
73
+ surface), page-coloured fills take --pie-white, and one-step-off-the-page
74
+ fills take --pie-background-dark. */
75
+ :where([data-pie-content]) .pie-loading {
76
+ /* The Figma indigo is --pie-primary at 90%, so the ring follows the theme's
77
+ primary instead of pinning MD indigo on every page. */
78
+ --pie-loading-accent: color-mix(
79
+ in srgb,
80
+ var(--pie-primary, #3f51b5) 90%,
81
+ transparent
82
+ );
83
+ position: absolute;
84
+ height: 100%;
85
+ width: 100%;
86
+ background-color: var(--pie-white, #fff);
87
+ bottom: 0;
88
+ left: 0;
89
+ right: 0;
90
+ top: 0;
91
+ z-index: 9999;
92
+ opacity: 0.4;
93
+ }
94
+
95
+ :where([data-pie-content]) .pie-loading.fixed {
96
+ position: fixed;
97
+ }
98
+
99
+ :where([data-pie-content]) .pie-loading:before {
100
+ content: "";
101
+ background-color: rgba(0, 0, 0, 0);
102
+ border: 5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
103
+ opacity: 0.9;
104
+ border-right: 5px solid rgba(0, 0, 0, 0);
105
+ border-left: 5px solid rgba(0, 0, 0, 0);
106
+ border-radius: 50px;
107
+ box-shadow: 0 0 35px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
108
+ width: 50px;
109
+ height: 50px;
110
+ -moz-animation: spinPulse 1s infinite ease-in-out;
111
+ -webkit-animation: spinPulse 1s infinite linear;
112
+ margin: -25px 0 0 -25px;
113
+ position: absolute;
114
+ top: 50%;
115
+ left: 50%;
116
+ }
117
+
118
+ :where([data-pie-content]) .pie-loading:after {
119
+ content: "";
120
+ background-color: rgba(0, 0, 0, 0);
121
+ border: 5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
122
+ opacity: 0.9;
123
+ border-left: 5px solid rgba(0, 0, 0, 0);
124
+ border-right: 5px solid rgba(0, 0, 0, 0);
125
+ border-radius: 50px;
126
+ box-shadow: 0 0 15px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
127
+ width: 30px;
128
+ height: 30px;
129
+ -moz-animation: spinoffPulse 1s infinite linear;
130
+ -webkit-animation: spinoffPulse 1s infinite linear;
131
+ margin: -15px 0 0 -15px;
132
+ position: absolute;
133
+ top: 50%;
134
+ left: 50%;
135
+ }
136
+
137
+ @keyframes spinPulse {
138
+ 0% {
139
+ transform: rotate(160deg);
140
+ opacity: 0;
141
+ box-shadow: 0 0 1px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
142
+ }
143
+ 50% {
144
+ transform: rotate(145deg);
145
+ opacity: 1;
146
+ }
147
+ 100% {
148
+ transform: rotate(-320deg);
149
+ opacity: 0;
150
+ }
151
+ }
152
+
153
+ @keyframes spinoffPulse {
154
+ 0% {
155
+ transform: rotate(0deg);
156
+ }
157
+ 100% {
158
+ transform: rotate(360deg);
159
+ }
160
+ }
161
+
162
+ :where([data-pie-content]) .pie-api-player img {
163
+ max-width: inherit !important;
164
+ max-height: inherit !important;
165
+ }
166
+
167
+ /*
168
+ * PIE-94: horizontal-scroll wrapper for authored images inside passages and
169
+ * item stems. The shared sanitizer (\`sanitizeItemMarkup\` in
170
+ * \`@pie-players/pie-players-shared\`) wraps every \`<img>\` in
171
+ * \`<span class="pie-image-scroll">\` before injection. When the image fits its
172
+ * column the scrollbar stays hidden (overflow-x: auto); when it doesn't, the
173
+ * wrapper — not the passage or section layout — provides the sideways scroll
174
+ * needed to satisfy WCAG 1.4.10 Reflow at 400% zoom.
175
+ *
176
+ * The wrapper is inline-block so an image keeps its place in the line: a block
177
+ * wrapper put every image on a line of its own, stacking a row of picture-graph
178
+ * icons into a column and adding a line to every image choice. Its baseline is
179
+ * its bottom edge, as an inline image's is, so the image sits where it did. An
180
+ * image laid out as a block gets \`pie-image-scroll-block\` from the player, so
181
+ * its wrapper adds no line box below it.
182
+ */
183
+ :where([data-pie-content]) .pie-image-scroll {
184
+ display: inline-block;
185
+ max-width: 100%;
186
+ overflow-x: auto;
187
+ overflow-y: hidden;
188
+ }
189
+
190
+ :where([data-pie-content]) .pie-image-scroll.pie-image-scroll-block {
191
+ display: block;
192
+ }
193
+
194
+ :where([data-pie-content]) .pie-image-scroll > img {
195
+ display: block;
196
+ max-width: none;
197
+ height: auto;
198
+ }
199
+
200
+ :where([data-pie-content]) .pie-image-scroll:focus-visible {
201
+ outline: 2px solid
202
+ var(
203
+ --pie-focus-ring-color,
204
+ var(--pie-focus-outline, var(--pie-button-focus-outline, #1a73e8))
205
+ );
206
+ outline-offset: 2px;
207
+ }
208
+
209
+ /*
210
+ * PIE-558: horizontal-scroll wrapper for authored tables. Mirrors \`.pie-image-scroll\`:
211
+ * the shared sanitizer wraps every \`<table>\` outside a \`pie-*\` custom element
212
+ * in \`<div class="pie-table-scroll">\`. When the table fits its column the
213
+ * scrollbar stays hidden; when it doesn't, the wrapper provides the sideways
214
+ * scroll needed to satisfy WCAG 1.4.10 Reflow at 400% zoom instead of forcing
215
+ * the section layout to scroll horizontally.
216
+ */
217
+ :where([data-pie-content]) .pie-table-scroll {
218
+ display: block;
219
+ max-width: 100%;
220
+ overflow-x: auto;
221
+ overflow-y: hidden;
222
+ }
223
+
224
+ :where([data-pie-content]) .pie-table-scroll > table {
225
+ max-width: none;
226
+ }
227
+
228
+ :where([data-pie-content]) .pie-table-scroll:focus-visible {
229
+ outline: 2px solid
230
+ var(
231
+ --pie-focus-ring-color,
232
+ var(--pie-focus-outline, var(--pie-button-focus-outline, #1a73e8))
233
+ );
234
+ outline-offset: 2px;
235
+ }
236
+
237
+ /* These styles are used in the body content of an item -- they also appear in the item body editor. */
238
+
239
+ .book-title-k5 {
240
+ text-decoration: underline;
241
+ }
242
+
243
+ .book-title {
244
+ font-style: italic;
245
+ }
246
+
247
+ .block-quote {
248
+ font-family: serif;
249
+ margin-left: 20%;
250
+ margin-right: 20%;
251
+ margin-top: 5px;
252
+ margin-bottom: 5px;
253
+ width: 60%;
254
+ border: 1px solid var(--pie-text, black);
255
+ padding: 2px;
256
+ display: block;
257
+ }
258
+
259
+ .text-block {
260
+ font-family: serif;
261
+ margin-left: 20%;
262
+ margin-right: 20%;
263
+ margin-top: 5px;
264
+ margin-bottom: 5px;
265
+ width: 60%;
266
+ border: 1px solid var(--pie-text, black);
267
+ padding: 2px;
268
+ display: block;
269
+ }
270
+
271
+ .short-quote {
272
+ font-weight: bold;
273
+ }
274
+
275
+ span.short-quote:before {
276
+ content: open-quote;
277
+ }
278
+
279
+ span.short-quote:after {
280
+ content: close-quote;
281
+ }
282
+
283
+ .word-callout {
284
+ text-decoration: underline;
285
+ }
286
+
287
+ .relative-emphasis {
288
+ text-transform: uppercase;
289
+ }
290
+
291
+ /* Authored red emphasis. --pie-content-emphasis is mapped from the DaisyUI error
292
+ slot through the legible correction, so it clears 4.5:1 against the page on
293
+ every shipped theme; the \`red\` literal it replaces measures 4:1 on white and
294
+ fails SC 1.4.3 before any theme is involved. */
295
+ .content-emphasis {
296
+ font-weight: bold;
297
+ color: var(--pie-content-emphasis, #b00000);
298
+ }
299
+
300
+ span.passage-title:before {
301
+ content: open-quote;
302
+ }
303
+
304
+ span.passage-title:after {
305
+ content: close-quote;
306
+ }
307
+
308
+ .proper-name {
309
+ font-style: italic;
310
+ }
311
+
312
+ .variable {
313
+ font-style: italic;
314
+ }
315
+
316
+ .equation-block {
317
+ text-align: center;
318
+ margin-left: 20%;
319
+ margin-right: 20%;
320
+ margin-top: 5px;
321
+ margin-bottom: 5px;
322
+ width: 60%;
323
+ padding: 2px;
324
+ display: block;
325
+ }
326
+
327
+ .embedded-error {
328
+ font-style: italic;
329
+ }
330
+
331
+ /*
332
+ * The 20% gutters above are a wide-viewport look. Held at a 320px-equivalent
333
+ * width they leave a ~190px column of very short lines, so they collapse there
334
+ * instead — SC 1.4.10 Reflow.
335
+ */
336
+ @media (max-width: 30rem) {
337
+ .block-quote,
338
+ .text-block,
339
+ .equation-block {
340
+ margin-left: 0;
341
+ margin-right: 0;
342
+ width: auto;
343
+ }
344
+ }
345
+
346
+ /*
347
+ * Presence sentinel. Players install this stylesheet themselves and read this
348
+ * property to detect whether a host that opted out of installation shipped a
349
+ * copy of its own. Not a themeable value — do not consume it for styling.
350
+ */
351
+ :root {
352
+ --pie-content-styles: 1;
353
+ }
354
+
355
+ /* PASSAGES */
356
+
357
+ div.passage-title,
358
+ div.passage-subtitle {
359
+ font-weight: bold;
360
+ text-align: center;
361
+ }
362
+
363
+ div.passage-author {
364
+ text-align: center;
365
+ }
366
+
367
+ .p-number {
368
+ float: left;
369
+ font-size: 0.85em;
370
+ }
371
+
372
+ .numbered-paragraph {
373
+ margin-left: 36px;
374
+ }
375
+
376
+ /* ch5680 - also temporary kds content styles that need to be externalized */
377
+ /* Inspect Styles */
378
+
379
+ @media print {
380
+ .kds-noprint {
381
+ display: none;
382
+ }
383
+
384
+ .noprint {
385
+ display: none;
386
+ }
387
+ }
388
+
389
+ .kds-absolute {
390
+ border-left: 1px solid var(--pie-text, black);
391
+ border-right: 1px solid var(--pie-text, black);
392
+ padding: 0px 0.3em 0px 0.3em;
393
+ }
394
+
395
+ .abs {
396
+ border-left: var(--pie-text, #000000) 1px solid;
397
+ border-right: var(--pie-text, #000000) 1px solid;
398
+ padding: 0px 0.3em 0px 0.3em;
399
+ }
400
+
401
+ .kds-border-1 {
402
+ border: 1px solid var(--pie-text, black);
403
+ }
404
+
405
+ .kds-border-2 {
406
+ border: 2px solid var(--pie-text, black);
407
+ }
408
+
409
+ .kds-center {
410
+ margin: 0px;
411
+ text-align: center;
412
+ }
413
+
414
+ :where([data-pie-content]) .center {
415
+ text-align: center;
416
+ margin: 0;
417
+ }
418
+
419
+ .kds-exponent {
420
+ font-size: 85%;
421
+ margin-left: -0.4em;
422
+ position: relative;
423
+ top: -1.4em;
424
+ }
425
+
426
+ sup.frac {
427
+ position: relative;
428
+ top: -1.4em;
429
+ font-size: 70%;
430
+ margin-left: -0.4em;
431
+ }
432
+
433
+ .kds-fillin {
434
+ border: 1px solid var(--pie-text, black);
435
+ display: inline-block;
436
+ margin: 0em 0.2em;
437
+ padding-left: 1em;
438
+ }
439
+
440
+ .fillin {
441
+ margin: 0em 0.2em;
442
+ padding-left: 1em;
443
+ border: var(--pie-text, #000000) 1px solid;
444
+ display: inline-block;
445
+ }
446
+
447
+ .kds-font-larger {
448
+ font-size: larger;
449
+ }
450
+
451
+ .kds-font-smaller {
452
+ font-size: smaller;
453
+ }
454
+
455
+ table.kds-fraction {
456
+ border: 0px;
457
+ display: inline-block;
458
+ font-size: 85%;
459
+ margin: 0px;
460
+ padding: 0px;
461
+ vertical-align: middle;
462
+ }
463
+
464
+ table.kds-fraction > tbody > tr > td.kds-numerator {
465
+ border-bottom: 1px solid var(--pie-text, black);
466
+ border-left: 0px;
467
+ border-right: 0px;
468
+ border-top: 0px;
469
+ text-align: center;
470
+ }
471
+
472
+ table.kds-fraction > tbody > tr > td.kds-denominator {
473
+ border: 0px;
474
+ text-align: center;
475
+ }
476
+
477
+ table.frac {
478
+ display: inline-block;
479
+ vertical-align: middle;
480
+ font-size: 85%;
481
+ border: 0px;
482
+ margin: 0px;
483
+ padding: 0px;
484
+ }
485
+
486
+ .frac .nu {
487
+ border-left: 0px;
488
+ border-top: 0px;
489
+ border-right: 0px;
490
+ border-bottom: var(--pie-text, #000000) 1px solid;
491
+ text-align: center;
492
+ }
493
+
494
+ .frac .de {
495
+ border: 0px;
496
+ text-align: center;
497
+ }
498
+
499
+ .kds-hanging-indent {
500
+ margin: 0px;
501
+ padding-left: 3em;
502
+ text-indent: -3em;
503
+ }
504
+
505
+ .kds-image-caption {
506
+ font-family: Verdana, Arial, sans-serif;
507
+ text-align: center;
508
+ }
509
+
510
+ .kds-image-left {
511
+ float: left;
512
+ margin-right: 5px;
513
+ }
514
+
515
+ .kds-image-right {
516
+ float: right;
517
+ margin-left: 5px;
518
+ }
519
+
520
+ .kds-indent {
521
+ text-indent: 3em;
522
+ }
523
+
524
+ :where([data-pie-content]) .indent {
525
+ text-indent: 3em;
526
+ }
527
+
528
+ .kds-nowrap {
529
+ display: inline-block;
530
+ white-space: nowrap;
531
+ }
532
+
533
+ .kds-overline {
534
+ text-decoration: overline;
535
+ }
536
+
537
+ .kds-parentheses {
538
+ font-family: "Arial Narrow", Arial, sans-serif;
539
+ font-size: 300%;
540
+ font-weight: normal;
541
+ position: relative;
542
+ top: 8px;
543
+ }
544
+
545
+ b.frac {
546
+ font-weight: normal;
547
+ font-size: 300%;
548
+ font-family: arial narrow;
549
+ position: relative;
550
+ top: +8px;
551
+ }
552
+
553
+ .kds-pi {
554
+ font-family: "Times New Roman", serif;
555
+ font-size: 1.2em;
556
+ }
557
+
558
+ .newradical {
559
+ border-collapse: collapse;
560
+ display: inline-block;
561
+ vertical-align: middle;
562
+ }
563
+
564
+ .newradical td {
565
+ border: 0px;
566
+ padding: 0px;
567
+ vertical-align: top;
568
+ }
569
+
570
+ .newradical td.vinculum {
571
+ border-top: 1px solid var(--pie-text, black);
572
+ padding: 0px;
573
+ vertical-align: top;
574
+ }
575
+
576
+ .newradical div.exp {
577
+ font-size: 0.7em;
578
+ position: relative;
579
+ left: 7px;
580
+ bottom: 5px;
581
+ }
582
+
583
+ .kds-underline {
584
+ text-decoration: underline;
585
+ }
586
+
587
+ :where([data-pie-content]) .under {
588
+ text-decoration: underline;
589
+ }
590
+
591
+ .kds-verdana2t {
592
+ border: 1px solid var(--pie-white, white);
593
+ text-align: left;
594
+ text-decoration: none;
595
+ vertical-align: top;
596
+ }
597
+
598
+ .Verdana2t {
599
+ vertical-align: top;
600
+ text-align: left;
601
+ text-decoration: none;
602
+ border: 1px solid var(--pie-white, white);
603
+ }
604
+
605
+ .kds-whole-number {
606
+ display: inline-block;
607
+ font-size: 120%;
608
+ margin: 0em 0em 0em 0.2em;
609
+ }
610
+
611
+ .whole {
612
+ display: inline-block;
613
+ margin: 0em 0em 0em 0.2em;
614
+ font-size: 120%;
615
+ }
616
+
617
+ table.KdsTable01 {
618
+ border: 1px solid var(--pie-text, black);
619
+ border-collapse: collapse;
620
+ border-spacing: 0px;
621
+ }
622
+
623
+ table.KdsTable01 > tbody > tr > th {
624
+ background-color: var(--pie-background-dark, #d3d3d3);
625
+ border: 1px solid var(--pie-text, black);
626
+ font-weight: normal;
627
+ padding: 2px;
628
+ text-align: center;
629
+ }
630
+
631
+ table.KdsTable01 > tbody > tr > th.bold {
632
+ background-color: var(--pie-background-dark, #d3d3d3);
633
+ border: 1px solid var(--pie-text, black);
634
+ font-weight: bold;
635
+ padding: 2px;
636
+ text-align: center;
637
+ }
638
+
639
+ table.KdsTable01 > tbody > tr > td {
640
+ border: 1px solid var(--pie-text, black);
641
+ padding: 2px;
642
+ text-align: center;
643
+ }
644
+
645
+ table.KdsTable01 > tbody > tr > td.bold {
646
+ border: 1px solid var(--pie-text, black);
647
+ font-weight: bold;
648
+ padding: 2px;
649
+ text-align: center;
650
+ }
651
+
652
+ table.KdsTable02 {
653
+ border: 1px solid var(--pie-text, black);
654
+ border-collapse: collapse;
655
+ border-spacing: 0px;
656
+ }
657
+
658
+ table.KdsTable02 > tbody > tr > th {
659
+ background-color: var(--pie-background-dark, #d3d3d3);
660
+ border: 1px solid var(--pie-text, black);
661
+ font-weight: normal;
662
+ padding: 2px;
663
+ }
664
+
665
+ table.KdsTable02 > tbody > tr > td {
666
+ border: 1px solid var(--pie-text, black);
667
+ padding: 2px;
668
+ }
669
+
670
+ /* Bootstrap 4 / Learnosity table classes, as content migrated from Learnosity
671
+ carries them: \`.table\`, \`.table-bordered\`, \`.table-striped\`,
672
+ \`.table-no-border\`, \`.lrn_width_auto\`. Hosts once imported these rules from
673
+ pie-player-components to give data tables visible borders (PD-876).
674
+
675
+ A layout table gets none of them. Authors mark one with \`.table-no-border\`,
676
+ \`role="presentation"\` or both, and the grid, 100% width and cell padding
677
+ pushed its letter tiles and images apart, where hosts that never imported
678
+ the rules render it bare. The class carries the exclusion on its own,
679
+ because one exported markup spells the role into the class list
680
+ (\`class="table … role= table-no-border"\`) and has no role attribute.
681
+ Elements leave presentation tables unstyled for the same reason (PIE-440).
682
+ The exclusion sits in \`:where()\` so every selector keeps the specificity of
683
+ its plain \`.table\` form.
684
+
685
+ The grid rules paint the ink, as every other authored grid in this file
686
+ does and as pie-lib's table grid falls back to: --pie-text is held to 4.5:1
687
+ against the page, so the rules clear SC 1.4.11's 3:1 wherever the text is
688
+ legible. They were a 15% mix, as faint as the fixed light grey (#dee2e6)
689
+ they first shipped with: 1.41:1 on white. A lighter fixed share cannot be
690
+ certified: the share that clears 3:1 depends on the palette, 62% on the
691
+ Grey on Light Grey scheme, and is unknown for a host's own.
692
+ --pie-border-light is no substitute either; the DaisyUI mapping fills it
693
+ from base-200, a surface. Each rule reads the ink itself, not through a
694
+ custom property, which would substitute var(--pie-text) where it is
695
+ declared: a scoped <pie-theme scope="self"> below :root would not reach it,
696
+ and neither would a shade fill's swapped ink (AUTHORED COLOURS below), which
697
+ keeps the rules around adjacent filled cells in the scheme's page colour. */
698
+ :where([data-pie-content])
699
+ .table:where(:not(.table-no-border, [role="presentation"])) {
700
+ width: 100%;
701
+ margin-bottom: 1em;
702
+ background-color: transparent;
703
+ border-collapse: collapse;
704
+ }
705
+
706
+ /* Learnosity's opt-out of the full-width table: it sizes to its content
707
+ (PD-194). */
708
+ :where([data-pie-content])
709
+ .table.lrn_width_auto:where(:not(.table-no-border, [role="presentation"])) {
710
+ width: auto;
711
+ }
712
+
713
+ :where([data-pie-content])
714
+ .table:where(:not(.table-no-border, [role="presentation"]))
715
+ th,
716
+ :where([data-pie-content])
717
+ .table:where(:not(.table-no-border, [role="presentation"]))
718
+ td {
719
+ padding: 0.75em;
720
+ vertical-align: top;
721
+ border-top: 1px solid var(--pie-text, black);
722
+ }
723
+
724
+ :where([data-pie-content])
725
+ .table:where(:not(.table-no-border, [role="presentation"]))
726
+ tbody
727
+ + tbody {
728
+ border-top: 2px solid var(--pie-text, black);
729
+ }
730
+
731
+ :where([data-pie-content])
732
+ .table:where(:not(.table-no-border, [role="presentation"]))
733
+ thead
734
+ th {
735
+ vertical-align: bottom;
736
+ border-bottom: 2px solid var(--pie-text, black);
737
+ }
738
+
739
+ :where([data-pie-content]) th {
740
+ text-align: inherit;
741
+ }
742
+
743
+ :where([data-pie-content])
744
+ .table-bordered:where(:not(.table-no-border, [role="presentation"])),
745
+ :where([data-pie-content])
746
+ .table-bordered:where(:not(.table-no-border, [role="presentation"]))
747
+ th,
748
+ :where([data-pie-content])
749
+ .table-bordered:where(:not(.table-no-border, [role="presentation"]))
750
+ td {
751
+ border: 1px solid var(--pie-text, black);
752
+ }
753
+
754
+ :where([data-pie-content])
755
+ .table-bordered:where(:not(.table-no-border, [role="presentation"]))
756
+ thead
757
+ td,
758
+ :where([data-pie-content])
759
+ .table-bordered:where(:not(.table-no-border, [role="presentation"]))
760
+ thead
761
+ th {
762
+ border-bottom-width: 2px;
763
+ }
764
+
765
+ :where([data-pie-content])
766
+ .table-striped:where(:not(.table-no-border, [role="presentation"]))
767
+ tbody
768
+ tr:nth-of-type(odd) {
769
+ background-color: color-mix(in srgb, var(--pie-text, #000) 5%, transparent);
770
+ }
771
+
772
+ :where([data-pie-content]) .text-center {
773
+ text-align: center !important;
774
+ }
775
+
776
+ :where([data-pie-content]) .h5,
777
+ :where([data-pie-content]) h5 {
778
+ font-size: 1.25em;
779
+ }
780
+
781
+ :where([data-pie-content]) h1,
782
+ :where([data-pie-content]) h2,
783
+ :where([data-pie-content]) h3,
784
+ :where([data-pie-content]) h4,
785
+ :where([data-pie-content]) h5,
786
+ :where([data-pie-content]) h6 {
787
+ margin-top: 0;
788
+ }
789
+
790
+ /* Spacing and inheritance only: \`font-weight: 500\` used to sit here and flatten
791
+ every authored heading to lighter-than-bold, weakening the visual hierarchy
792
+ a screen-reader user gets from the heading level. */
793
+ :where([data-pie-content]) .h1,
794
+ :where([data-pie-content]) .h2,
795
+ :where([data-pie-content]) .h3,
796
+ :where([data-pie-content]) .h4,
797
+ :where([data-pie-content]) .h5,
798
+ :where([data-pie-content]) .h6,
799
+ :where([data-pie-content]) h1,
800
+ :where([data-pie-content]) h2,
801
+ :where([data-pie-content]) h3,
802
+ :where([data-pie-content]) h4,
803
+ :where([data-pie-content]) h5,
804
+ :where([data-pie-content]) h6 {
805
+ margin-bottom: 0.5em;
806
+ font-family: inherit;
807
+ line-height: 1.2;
808
+ color: inherit;
809
+ }
810
+
811
+ /*
812
+ * Removed: a \`#stimulus\` / \`#item\` pair of 50% left floats and a
813
+ * \`.lrn_feature h3\` margin override. The float pair hard-coded a two-column
814
+ * layout keyed to two global ids — it cannot reflow at 400% zoom (SC 1.4.10),
815
+ * and it applied to any element in the host document carrying those ids.
816
+ * The legacy players never applied the margin override, so content migrated
817
+ * with \`.lrn_feature\` keeps the heading margin it had there.
818
+ */
819
+
820
+ .TEX-S3 {
821
+ font-family: MJXZERO, MJXTEX-S3 !important;
822
+ }
823
+
824
+ .TEX-S2 {
825
+ font-family: MJXZERO, MJXTEX-S2 !important;
826
+ }
827
+
828
+ .TEX-S1 {
829
+ font-family: MJXZERO, MJXTEX-S1 !important;
830
+ }
831
+
832
+ .TEX-I {
833
+ font-family: MJXZERO, MJXTEX-I !important;
834
+ }
835
+
836
+ mjx-c.mjx-c2032 {
837
+ font-family: "CerebriSans", serif !important;
838
+ }
839
+
840
+ mjx-c.mjx-c22,
841
+ mjx-c.mjx-c27 {
842
+ font-family: MJXZERO, serif !important;
843
+ }
844
+
845
+ :where([data-pie-content]) table {
846
+ border-collapse: collapse;
847
+ }
848
+
849
+ .evaluate-bottom-border > :first-child::after {
850
+ content: "";
851
+ display: block;
852
+ border-bottom: 1px solid
853
+ color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
854
+ }
855
+
856
+ /* ANSWER ELIMINATOR */
857
+
858
+ :where([data-pie-content]) .pie-answer-eliminator-toggle {
859
+ /* em, not px: PNP font scaling raises the surrounding text size without
860
+ touching px boxes, which left a fixed 28px control under grown text. The
861
+ box is 1.75x the surrounding text and the glyph 1.125x — the 28px/18px the
862
+ control used to pin at a 16px base — and the box stays past SC 2.5.8's 24px
863
+ minimum for any base at or above 14px. The box divides by the glyph factor
864
+ because \`em\` in a length resolves against this element's own font-size, not
865
+ the parent's; a bare 1.75em here measures 31.5px, not 28px. */
866
+ width: calc(1.75em / 1.125);
867
+ height: calc(1.75em / 1.125);
868
+ padding: 0;
869
+ border: 1px solid var(--pie-border, #ccc);
870
+ border-radius: 4px;
871
+ background: var(--pie-white, #fff);
872
+ cursor: pointer;
873
+ font-size: 1.125em;
874
+ line-height: 1;
875
+ display: inline-flex;
876
+ align-items: center;
877
+ justify-content: center;
878
+ color: var(
879
+ --pie-answer-eliminator-toggle-color,
880
+ var(--pie-button-color, #8c8c8c)
881
+ );
882
+ transition: all 0.2s ease;
883
+ z-index: 10;
884
+ }
885
+
886
+ :where([data-pie-content]) .pie-answer-eliminator-toggle:hover {
887
+ background: var(--pie-secondary-background, #f0f0f0);
888
+ border-color: var(--pie-border-dark, #999);
889
+ color: var(--pie-text, #333);
890
+ }
891
+
892
+ :where([data-pie-content]) .pie-answer-eliminator-toggle--active,
893
+ :where([data-pie-content]) .pie-answer-eliminator-toggle--active:hover {
894
+ background: var(--pie-incorrect, #ff9800);
895
+ border-color: var(--pie-incorrect, #ff9800);
896
+ color: var(--pie-white, #fff);
897
+ }
898
+
899
+ :where([data-pie-content]) .pie-answer-eliminator-eliminated-fallback {
900
+ text-decoration: line-through;
901
+ text-decoration-thickness: 2px;
902
+ text-decoration-color: var(
903
+ --pie-answer-eliminator-strike-color,
904
+ var(--pie-incorrect, #ff9800)
905
+ );
906
+ }
907
+
908
+ /*
909
+ * Dims the choice as well as striking it, so elimination survives a strike
910
+ * colour the learner cannot distinguish. Kept at 0.6 rather than lower: the text
911
+ * stays readable, because eliminating a choice is reversible and the learner has
912
+ * to be able to reconsider it.
913
+ *
914
+ * Keyed on the attribute rather than on the fallback class, because the class is
915
+ * added only by the path for browsers without the CSS Highlight API. The
916
+ * attribute is set by both paths, and a highlight pseudo cannot carry \`opacity\`
917
+ * at all — declaring it there dimmed nothing, so the modern path shipped the
918
+ * strike as its only cue.
919
+ */
920
+ :where([data-pie-content]) [data-pie-answer-eliminated="true"] {
921
+ opacity: 0.6;
922
+ }
923
+
924
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike {
925
+ position: relative;
926
+ display: inline-block;
927
+ max-width: 100%;
928
+ /*
929
+ * Collapse the line-box strut so the wrapper hugs the image exactly (no
930
+ * baseline descender gap under it) and the X cannot overhang the artwork.
931
+ * It also keeps the image bottom on the text baseline, as an unwrapped
932
+ * baseline-aligned image sits.
933
+ */
934
+ line-height: 0;
935
+ }
936
+
937
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-overlay {
938
+ position: absolute;
939
+ inset: 0;
940
+ width: 100%;
941
+ height: 100%;
942
+ pointer-events: none;
943
+ }
944
+
945
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-line {
946
+ stroke: var(
947
+ --pie-answer-eliminator-strike-color,
948
+ var(--pie-incorrect, #ff9800)
949
+ );
950
+ stroke-width: 3;
951
+ stroke-linecap: square;
952
+ }
953
+
954
+ /* Wider light line under each diagonal so the X stays legible on dark imagery. */
955
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-casing {
956
+ stroke: var(
957
+ --pie-answer-eliminator-image-strike-casing-color,
958
+ rgba(255, 255, 255, 0.85)
959
+ );
960
+ stroke-width: 6;
961
+ stroke-linecap: square;
962
+ }
963
+
964
+ /*
965
+ * Eliminated math: MathJax's rendered glyphs are generated content, so neither
966
+ * \`::highlight()\` nor \`text-decoration\` reaches them. The eliminator marks the
967
+ * rendered math box instead and the paint happens here, in the same colour and
968
+ * weight as the text line-through so a choice mixing prose and math reads as one
969
+ * strike. Which mark it gets depends on the shape of the expression — the tool
970
+ * measures the box and picks \`--line\` or \`--cross\`.
971
+ */
972
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike {
973
+ position: relative;
974
+ /*
975
+ * Internal: the resolved strike paint, so the rules below need not repeat the
976
+ * fallback chain. Not a themeable knob — set --pie-answer-eliminator-strike-color.
977
+ */
978
+ --pie-answer-eliminator-strike-paint: var(
979
+ --pie-answer-eliminator-strike-color,
980
+ var(--pie-incorrect, #ff9800)
981
+ );
982
+ }
983
+
984
+ /* A single row of symbols takes the same line-through as the surrounding prose. */
985
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike--line::after {
986
+ content: "";
987
+ position: absolute;
988
+ left: 0;
989
+ right: 0;
990
+ top: 50%;
991
+ border-top: 2px solid var(--pie-answer-eliminator-strike-paint);
992
+ pointer-events: none;
993
+ }
994
+
995
+ /*
996
+ * A stacked 2D layout (fraction, radical, matrix) takes the diagonals instead.
997
+ * A centred line would land on the math axis — precisely where the fraction bar
998
+ * already is — and read as a recoloured bar rather than an elimination, so the
999
+ * expression is crossed out the way an eliminated image is. Corner keywords make
1000
+ * each gradient's transition run exactly corner to corner at any aspect ratio,
1001
+ * with a 1px feather either side of the 1px core for a smooth 2px line.
1002
+ */
1003
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike--cross::after {
1004
+ content: "";
1005
+ position: absolute;
1006
+ inset: 0;
1007
+ pointer-events: none;
1008
+ background-image:
1009
+ linear-gradient(
1010
+ to bottom right,
1011
+ transparent calc(50% - 1.5px),
1012
+ var(--pie-answer-eliminator-strike-paint) calc(50% - 0.5px),
1013
+ var(--pie-answer-eliminator-strike-paint) calc(50% + 0.5px),
1014
+ transparent calc(50% + 1.5px)
1015
+ ),
1016
+ linear-gradient(
1017
+ to bottom left,
1018
+ transparent calc(50% - 1.5px),
1019
+ var(--pie-answer-eliminator-strike-paint) calc(50% - 0.5px),
1020
+ var(--pie-answer-eliminator-strike-paint) calc(50% + 0.5px),
1021
+ transparent calc(50% + 1.5px)
1022
+ );
1023
+ }
1024
+
1025
+ :where([data-pie-content]) .pie-answer-masked-fallback {
1026
+ opacity: 0.2;
1027
+ filter: blur(2px);
1028
+ }
1029
+
1030
+ :where([data-pie-content]) .pie-answer-eliminator-sr-announcement {
1031
+ position: absolute;
1032
+ left: -10000px;
1033
+ width: 1px;
1034
+ height: 1px;
1035
+ overflow: hidden;
1036
+ }
1037
+
1038
+ /* AUTHORED COLOURS
1039
+
1040
+ Under a color scheme, colours written into authored markup give way to the
1041
+ scheme. Sanitizers mark the elements that carry one (\`markAuthoredColors\` in
1042
+ @pie-element/shared-utils): \`data-pie-authored-ink\` for a text colour,
1043
+ \`data-pie-authored-border\` for a border colour and \`data-pie-authored-fill\`
1044
+ for a background, \`light\` when it is near white and \`shade\` otherwise. Ink
1045
+ and borders take the scheme's text and border colours. A light fill, usually
1046
+ the page the text was pasted from, drops away. A shade fill (a header row, a highlight) inverts:
1047
+ it takes the scheme's ink, and everything inside it reads the scheme's page
1048
+ as its ink, so it keeps the contrast the scheme certifies and still stands
1049
+ out. The default theme stamps no data-color-scheme and keeps the authored
1050
+ colours. Gradients, background images and colours in MathJax output carry
1051
+ no marker and render as authored.
1052
+
1053
+ The ink and page are captured on the element that declares the scheme's
1054
+ tokens, so the swap inside a fill reads them without a cycle, and a fill
1055
+ nested in a fill inverts once. Controls inside a fill read the swapped
1056
+ neutral tokens; accent and feedback tokens keep their page values.
1057
+
1058
+ \`!important\` outranks the authored inline style, and the sanitizers drop
1059
+ \`!important\` from a marked declaration. The rules stay document-wide: the
1060
+ markers name authored content only, and elements portal authored markup to
1061
+ <body>. */
1062
+ [data-color-scheme] {
1063
+ --pie-scheme-ink: var(--pie-text);
1064
+ --pie-scheme-page: var(--pie-background);
1065
+ }
1066
+
1067
+ [data-color-scheme] [data-pie-authored-ink] {
1068
+ color: var(--pie-text) !important;
1069
+ }
1070
+
1071
+ [data-color-scheme] [data-pie-authored-border] {
1072
+ border-color: var(--pie-border) !important;
1073
+ }
1074
+
1075
+ [data-color-scheme] [data-pie-authored-fill="light"] {
1076
+ background-color: transparent !important;
1077
+ color: var(--pie-text) !important;
1078
+ }
1079
+
1080
+ [data-color-scheme] [data-pie-authored-fill="shade"] {
1081
+ --pie-text: var(--pie-scheme-page);
1082
+ --pie-black: var(--pie-scheme-page);
1083
+ --pie-border: var(--pie-scheme-page);
1084
+ --pie-background: var(--pie-scheme-ink);
1085
+ --pie-white: var(--pie-scheme-ink);
1086
+ background-color: var(--pie-scheme-ink) !important;
1087
+ color: var(--pie-scheme-page) !important;
1088
+ }
1089
+ `,Q7=class{constructor(){Ee(this,"initialized",!1),Ee(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}};function qS(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function Ic(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(qS(e))return e;if(qS(t))return t}var Z7=class extends Q7{constructor(...e){super(...e),Ee(this,"providerId","newrelic"),Ee(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(Ic()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&Ic()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){Ic()?.noticeError(e,t)}doTrackEvent(e,t){Ic()?.addPageAction(e,t)}doSetUserContext(e,t){const r=Ic();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=Ic();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}},cm={retryDelayMs:3e3,timeoutMs:12e4},WS={trackPageActions:!1,instrumentationProvider:void 0,maxResourceRetries:3,resourceRetryDelay:500,iifeBundleRetry:cm};function ez(e,t="iife"){return e==="iife"||e==="esm"||e==="preloaded"?e:t}function tz(e,t){this.v=e,this.k=t}function VS(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function rz(e){if(Array.isArray(e))return e}function nz(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,o,s,a=[],l=!0,c=!1;try{if(o=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);l=!0);}catch(u){c=!0,i=u}finally{try{if(!l&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function iz(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1090
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function oz(e,t){return rz(e)||nz(e,t)||sz(e,t)||iz()}function sz(e,t){if(e){if(typeof e=="string")return VS(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?VS(e,t):void 0}}function Ph(e){var t,r;function n(o,s){try{var a=e[o](s),l=a.value,c=l instanceof tz;Promise.resolve(c?l.v:l).then(function(u){if(c){var d=o==="return"&&l.k?o:"next";if(!l.k||u.done)return n(d,u);u=e[d](u).value}i(!!a.done,u)},function(u){n("throw",u)})}catch(u){i(2,u)}}function i(o,s){o===2?t.reject(s):t.resolve({value:s,done:o}),(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(o,s){return new Promise(function(a,l){var c={key:o,arg:s,resolve:a,reject:l,next:null};r?r=r.next=c:(t=r=c,n(o,s))})},typeof e.return!="function"&&(this.return=void 0)}Ph.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Ph.prototype.next=function(e){return this._invoke("next",e)},Ph.prototype.throw=function(e){return this._invoke("throw",e)},Ph.prototype.return=function(e){return this._invoke("return",e)};var YR=Object.entries,GS=Object.setPrototypeOf,az=Object.isFrozen,lz=Object.getPrototypeOf,cz=Object.getOwnPropertyDescriptor,On=Object.freeze,Hn=Object.seal,Uc=Object.create,KR=typeof Reflect<"u"&&Reflect,zy=KR.apply,By=KR.construct;On||(On=function(e){return e});Hn||(Hn=function(e){return e});zy||(zy=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e.apply(t,n)});By||(By=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});var cl=kn(Array.prototype.forEach);Array.prototype.indexOf;var uz=kn(Array.prototype.lastIndexOf),YS=kn(Array.prototype.pop),Ku=kn(Array.prototype.push);Array.prototype.slice;var dz=kn(Array.prototype.splice),Zc=Array.isArray,vd=kn(String.prototype.toLowerCase),tv=kn(String.prototype.toString),KS=kn(String.prototype.match),Xu=kn(String.prototype.replace),XS=kn(String.prototype.indexOf),fz=kn(String.prototype.trim),hz=kn(Number.prototype.toString),pz=kn(Boolean.prototype.toString),JS=typeof BigInt>"u"?null:kn(BigInt.prototype.toString),QS=typeof Symbol>"u"?null:kn(Symbol.prototype.toString),mi=kn(Object.prototype.hasOwnProperty),Ju=kn(Object.prototype.toString),Kn=kn(RegExp.prototype.test),ba=mz(TypeError);function kn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return zy(e,t,n)}}function mz(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return By(e,r)}}function Sr(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:vd;if(GS&&GS(e,null),!Zc(t))return e;let n=t.length;for(;n--;){let i=t[n];if(typeof i=="string"){const o=r(i);o!==i&&(az(t)||(t[n]=o),i=o)}e[i]=!0}return e}function gz(e){for(let t=0;t<e.length;t++)mi(e,t)||(e[t]=null);return e}function Li(e){const t=Uc(null);for(const n of YR(e)){var r=oz(n,2);const i=r[0],o=r[1];mi(e,i)&&(Zc(o)?t[i]=gz(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=Li(o):t[i]=o)}return t}function vz(e){switch(typeof e){case"string":return e;case"number":return hz(e);case"boolean":return pz(e);case"bigint":return JS?JS(e):"0";case"symbol":return QS?QS(e):"Symbol()";case"undefined":return Ju(e);case"function":case"object":{if(e===null)return Ju(e);const t=e,r=to(t,"toString");if(typeof r=="function"){const n=r(t);return typeof n=="string"?n:Ju(n)}return Ju(e)}default:return Ju(e)}}function to(e,t){for(;e!==null;){const n=cz(e,t);if(n){if(n.get)return kn(n.get);if(typeof n.value=="function")return kn(n.value)}e=lz(e)}function r(){return null}return r}function yz(e){try{return Kn(e,""),!0}catch{return!1}}var ZS=On(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),rv=On(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),nv=On(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),bz=On(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),iv=On(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),wz=On(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),eI=On(["#text"]),tI=On(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),ov=On(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),rI=On(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),_h=On(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Sz=Hn(/{{[\w\W]*|^[\w\W]*}}/g),Iz=Hn(/<%[\w\W]*|^[\w\W]*%>/g),kz=Hn(/\${[\w\W]*/g),Tz=Hn(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ez=Hn(/^aria-[\-\w]+$/),nI=Hn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Cz=Hn(/^(?:\w+script|data):/i),xz=Hn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Rz=Hn(/^html$/i),Pz=Hn(/^[a-z][.\w]*(-[.\w]+)+$/i),iI=Hn(/<[/\w!]/g),oI=Hn(/<[/\w]/g),_z=Hn(/<\/no(script|embed|frames)/i),Az=Hn(/\/>/i),Ai={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},XR=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],$z=On(Sr({},XR)),Mz=(function(){const e={};return cl(XR,t=>{e[t]=Hn(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),On(e)})(),Oz=function(){return typeof window>"u"?null:window},Lz=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},sI=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},wa=function(e,t,r,n){return mi(e,t)&&Zc(e[t])?Sr(n.base?Li(n.base):{},e[t],n.transform):r},sv=function(e,t,r){const n=mi(e,t)?e[t]:void 0;return n&&typeof n=="object"?Li(n):r()};function JR(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Oz();const t=S=>JR(S);if(t.version="3.4.16",t.removed=[],!e||!e.document||e.document.nodeType!==Ai.document||!e.Element)return t.isSupported=!1,t;let r=e.document;const n=r,i=n.currentScript;e.DocumentFragment;const o=e.HTMLTemplateElement,s=e.Node,a=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const c=e.DOMParser,u=e.trustedTypes,d=a.prototype,f=to(d,"cloneNode"),h=to(d,"remove"),g=to(d,"removeAttributeNode"),m=to(d,"nextSibling"),v=to(d,"childNodes"),b=to(d,"parentNode"),I=to(d,"shadowRoot"),C=to(d,"attributes"),x=s&&s.prototype?to(s.prototype,"nodeType"):null,$=s&&s.prototype?to(s.prototype,"nodeName"):null,P=s&&s.prototype?to(s.prototype,"ownerDocument"):null,L=function(S){return x?x(S):S.nodeType},J=function(S){return $?$(S):S.nodeName};if(typeof o=="function"){const S=r.createElement("template");S.content&&S.content.ownerDocument&&(r=S.content.ownerDocument)}let V,Y="",Pe,M=!1,H=0;const ne=function(){if(H>0)throw ba('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},ae=function(S){ne(),H++;try{return V.createHTML(S)}finally{H--}},ye=function(S){ne(),H++;try{return V.createScriptURL(S)}finally{H--}},te=function(){return M||(Pe=Lz(u,i),M=!0),Pe},z=r,A=z.implementation,K=z.createNodeIterator,Q=z.createDocumentFragment,_=z.getElementsByTagName,B=n.importNode;let U=sI();t.isSupported=typeof YR=="function"&&typeof b=="function"&&A&&A.createHTMLDocument!==void 0;const fe=Sz,W=Iz,se=kz,_e=Tz,Ue=Ez,it=Cz,le=xz,de=Pz;let Ne=nI,Ae=null;const ce=Sr({},[...ZS,...rv,...nv,...iv,...eI]);let ie=null;const De=Sr({},[...tI,...ov,...rI,..._h]);let Je=Object.seal(Uc(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),At=null,pt=null;const Et=Object.seal(Uc(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Re=!0,Ze=!0,Ye=!1,yt=!0,re=!1,Qe=!0,lt=!1,zt=!1,Vt=null,ur=null,st=!1,Rt=!1,bt=!1,ft=!1,me=!0,Nt=!1;const tr="user-content-";let mt=!0,vr=!1,dr={},Ir=null;const Qt=Sr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Nr=null;const on=Sr({},["audio","video","img","source","image","track"]);let Or=null;const yr=Sr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fn="http://www.w3.org/1998/Math/MathML",or="http://www.w3.org/2000/svg",j="http://www.w3.org/1999/xhtml";let ke=j,Fe=!1,Ve=null;const Ft=Sr({},[fn,or,j],tv),Pr=On(["mi","mo","mn","ms","mtext"]);let en=Sr({},Pr);const En=On(["annotation-xml"]);let ri=Sr({},En);const ko=Sr({},["title","style","font","a","script"]);let ge=null;const fr=["application/xhtml+xml","text/html"],Nn="text/html";let _r=null,Ji=null;const ni=r.createElement("form"),Os=function(S){return S instanceof RegExp||S instanceof Function},Vn=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ji&&Ji===S)return;(!S||typeof S!="object")&&(S={}),S=Li(S),ge=fr.indexOf(S.PARSER_MEDIA_TYPE)===-1?Nn:S.PARSER_MEDIA_TYPE,_r=ge==="application/xhtml+xml"?tv:vd,Ae=wa(S,"ALLOWED_TAGS",ce,{transform:_r}),ie=wa(S,"ALLOWED_ATTR",De,{transform:_r}),Ve=wa(S,"ALLOWED_NAMESPACES",Ft,{transform:tv}),Or=wa(S,"ADD_URI_SAFE_ATTR",yr,{transform:_r,base:yr}),Nr=wa(S,"ADD_DATA_URI_TAGS",on,{transform:_r,base:on}),Ir=wa(S,"FORBID_CONTENTS",Qt,{transform:_r}),At=wa(S,"FORBID_TAGS",Li({}),{transform:_r}),pt=wa(S,"FORBID_ATTR",Li({}),{transform:_r}),dr=mi(S,"USE_PROFILES")?S.USE_PROFILES&&typeof S.USE_PROFILES=="object"?Li(S.USE_PROFILES):S.USE_PROFILES:!1,Re=S.ALLOW_ARIA_ATTR!==!1,Ze=S.ALLOW_DATA_ATTR!==!1,Ye=S.ALLOW_UNKNOWN_PROTOCOLS||!1,yt=S.ALLOW_SELF_CLOSE_IN_ATTR!==!1,re=S.SAFE_FOR_TEMPLATES||!1,Qe=S.SAFE_FOR_XML!==!1,lt=S.WHOLE_DOCUMENT||!1,Rt=S.RETURN_DOM||!1,bt=S.RETURN_DOM_FRAGMENT||!1,ft=S.RETURN_TRUSTED_TYPE||!1,st=S.FORCE_BODY||!1,me=S.SANITIZE_DOM!==!1,Nt=S.SANITIZE_NAMED_PROPS||!1,mt=S.KEEP_CONTENT!==!1,vr=S.IN_PLACE||!1,Ne=yz(S.ALLOWED_URI_REGEXP)?S.ALLOWED_URI_REGEXP:nI,ke=typeof S.NAMESPACE=="string"?S.NAMESPACE:j,en=sv(S,"MATHML_TEXT_INTEGRATION_POINTS",()=>Sr({},Pr)),ri=sv(S,"HTML_INTEGRATION_POINTS",()=>Sr({},En));const Z=sv(S,"CUSTOM_ELEMENT_HANDLING",()=>Uc(null));if(Je=Uc(null),mi(Z,"tagNameCheck")&&Os(Z.tagNameCheck)&&(Je.tagNameCheck=Z.tagNameCheck),mi(Z,"attributeNameCheck")&&Os(Z.attributeNameCheck)&&(Je.attributeNameCheck=Z.attributeNameCheck),mi(Z,"allowCustomizedBuiltInElements")&&typeof Z.allowCustomizedBuiltInElements=="boolean"&&(Je.allowCustomizedBuiltInElements=Z.allowCustomizedBuiltInElements),Hn(Je),re&&(Ze=!1),bt&&(Rt=!0),dr&&(Ae=Sr({},eI),ie=Uc(null),dr.html===!0&&(Sr(Ae,ZS),Sr(ie,tI)),dr.svg===!0&&(Sr(Ae,rv),Sr(ie,ov),Sr(ie,_h)),dr.svgFilters===!0&&(Sr(Ae,nv),Sr(ie,ov),Sr(ie,_h)),dr.mathMl===!0&&(Sr(Ae,iv),Sr(ie,rI),Sr(ie,_h))),Et.tagCheck=null,Et.attributeCheck=null,mi(S,"ADD_TAGS")&&(typeof S.ADD_TAGS=="function"?Et.tagCheck=S.ADD_TAGS:Zc(S.ADD_TAGS)&&(Ae===ce&&(Ae=Li(Ae)),Sr(Ae,S.ADD_TAGS,_r))),mi(S,"ADD_ATTR")&&(typeof S.ADD_ATTR=="function"?Et.attributeCheck=S.ADD_ATTR:Zc(S.ADD_ATTR)&&(ie===De&&(ie=Li(ie)),Sr(ie,S.ADD_ATTR,_r))),mi(S,"ADD_FORBID_CONTENTS")&&Zc(S.ADD_FORBID_CONTENTS)&&(Ir===Qt&&(Ir=Li(Ir)),Sr(Ir,S.ADD_FORBID_CONTENTS,_r)),mt&&(Ae["#text"]=!0),lt&&Sr(Ae,["html","head","body"]),Ae.table&&(Sr(Ae,["tbody"]),delete At.tbody),S.TRUSTED_TYPES_POLICY){if(typeof S.TRUSTED_TYPES_POLICY.createHTML!="function")throw ba('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof S.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ba('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const oe=V;V=S.TRUSTED_TYPES_POLICY;try{Y=ae("")}catch(we){throw V=oe,we}}else S.TRUSTED_TYPES_POLICY===null?(V=void 0,Y=""):(V===void 0&&(V=te()),V&&typeof Y=="string"&&(Y=ae("")));On&&On(S),Ji=S},ua=Sr({},[...rv,...nv,...bz]),ns=Sr({},[...iv,...wz]),Qi=function(S,Z,oe){return Z.namespaceURI===j?S==="svg":Z.namespaceURI===fn?S==="svg"&&(oe==="annotation-xml"||en[oe]):!!ua[S]},Zi=function(S,Z,oe){return Z.namespaceURI===j?S==="math":Z.namespaceURI===or?S==="math"&&ri[oe]:!!ns[S]},Ls=function(S,Z,oe){return Z.namespaceURI===or&&!ri[oe]||Z.namespaceURI===fn&&!en[oe]?!1:!ns[S]&&(ko[S]||!ua[S])},is=function(S){let Z=b(S);(!Z||!Z.tagName)&&(Z={namespaceURI:ke,tagName:"template"});const oe=vd(S.tagName),we=vd(Z.tagName);return Ve[S.namespaceURI]?S.namespaceURI===or?Qi(oe,Z,we):S.namespaceURI===fn?Zi(oe,Z,we):S.namespaceURI===j?Ls(oe,Z,we):!!(ge==="application/xhtml+xml"&&Ve[S.namespaceURI]):!1},Ri=function(S){Ku(t.removed,{element:S});try{b(S).removeChild(S)}catch{if(h(S),!b(S))throw ba("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Un=function(S,Z,oe){try{g(S,Z)}catch{try{S.removeAttribute(oe)}catch{}}},O=function(S){he(S);const Z=v(S);if(Z){const we=[];cl(Z,qe=>{Ku(we,qe)}),cl(we,qe=>{try{h(qe)}catch{}})}const oe=C(S);if(oe)for(let we=oe.length-1;we>=0;--we){const qe=oe[we],We=qe&&qe.name;typeof We=="string"&&Un(S,qe,We)}},ee=function(S,Z,oe){if(!oe)try{oe=Z.getAttributeNode(S)}catch{oe=null}Ku(t.removed,{attribute:oe||null,from:Z});try{oe?g(Z,oe):Z.removeAttribute(S)}catch{try{Z.removeAttribute(S)}catch{}}if(S==="is")if(Rt||bt)try{Ri(Z)}catch{}else try{Z.setAttribute(S,"")}catch{}},X=function(S){const Z=C(S);if(Z)for(let oe=Z.length-1;oe>=0;--oe){const we=Z[oe],qe=we&&we.name;typeof qe!="string"||ie[_r(qe)]||Un(S,we,qe)}},he=function(S){const Z=[S];for(;Z.length>0;){const oe=Z.pop();L(oe)===Ai.element&&X(oe);const we=v(oe);if(we)for(let qe=we.length-1;qe>=0;--qe)Z.push(we[qe])}},gt=function(S,Z){return Qe?S==="patchsrc"?!0:S==="for"&&Z!=="label"&&Z!=="output":!1},kr=function(S){if(!Qe)return;const Z=[S];for(;Z.length>0;){const oe=Z.pop(),we=L(oe);if(we===Ai.processingInstruction||we===Ai.comment&&Kn(oI,oe.data)){try{h(oe)}catch{}continue}if(we===Ai.element){const We=oe,ot=_r(J(oe));try{We.hasAttribute&&We.hasAttribute("patchsrc")&&We.removeAttribute("patchsrc"),We.hasAttribute&&We.hasAttribute("for")&&gt("for",ot)&&We.removeAttribute("for")}catch{}}const qe=v(oe);if(qe)for(let We=qe.length-1;We>=0;--We)Z.push(qe[We])}},Ie=function(S){let Z=null,oe=null;if(st)S="<remove></remove>"+S;else{const We=KS(S,/^[\r\n\t ]+/);oe=We&&We[0]}ge==="application/xhtml+xml"&&ke===j&&(S='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+S+"</body></html>");const we=V?ae(S):S;if(ke===j)try{Z=new c().parseFromString(we,ge)}catch{}if(!Z||!Z.documentElement){Z=A.createDocument(ke,"template",null);try{Z.documentElement.innerHTML=Fe?Y:we}catch{}}const qe=Z.body||Z.documentElement;return S&&oe&&qe.insertBefore(r.createTextNode(oe),qe.childNodes[0]||null),ke===j?_.call(Z,lt?"html":"body")[0]:lt?Z.documentElement:qe},et=function(S){const Z=P?P(S):S.ownerDocument;return K.call(Z||S,S,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},jr=function(S){return S=Xu(S,fe," "),S=Xu(S,W," "),S=Xu(S,se," "),S},$t=function(S){var Z;S.normalize();const oe=P?P(S):S.ownerDocument,we=K.call(oe||S,S,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let qe=we.nextNode();for(;qe;)qe.data=jr(qe.data),qe=we.nextNode();const We=(Z=S.querySelectorAll)===null||Z===void 0?void 0:Z.call(S,"template");We&&cl(We,ot=>{Ar(ot.content)&&$t(ot.content)})},$e=function(S){const Z=$?$(S):null;return typeof Z!="string"||_r(Z)!=="form"?!1:typeof S.nodeName!="string"||typeof S.textContent!="string"||typeof S.removeChild!="function"||S.attributes!==C(S)||typeof S.removeAttribute!="function"||typeof S.removeAttributeNode!="function"||typeof S.getAttributeNode!="function"||typeof S.setAttribute!="function"||typeof S.namespaceURI!="string"||typeof S.insertBefore!="function"||typeof S.hasChildNodes!="function"||S.nodeType!==x(S)||S.childNodes!==v(S)},Ar=function(S){if(!x||typeof S!="object"||S===null)return!1;try{return x(S)===Ai.documentFragment}catch{return!1}},Kr=function(S){if(!x||typeof S!="object"||S===null)return!1;try{return typeof x(S)=="number"}catch{return!1}};function br(S,Z,oe){S.length!==0&&cl(S,we=>{we.call(t,Z,oe,Ji)})}const Xr=function(S,Z){return!!(Qe&&S.hasChildNodes()&&!Kr(S.firstElementChild)&&Kn(iI,S.textContent)&&Kn(iI,S.innerHTML)||Qe&&S.namespaceURI===j&&$z[Z]&&(Kr(S.firstElementChild)||typeof S.textContent=="string"&&Kn(Mz[Z],S.textContent))||S.nodeType===Ai.processingInstruction||Qe&&S.nodeType===Ai.comment&&Kn(oI,S.data))},wr=function(S,Z){if(S instanceof RegExp)return Kn(S,Z);if(S instanceof Function){for(var oe=arguments.length,we=new Array(oe>2?oe-2:0),qe=2;qe<oe;qe++)we[qe-2]=arguments[qe];return!!S(Z,...we)}return!1},Cr=function(S,Z,oe){if(!At[Z]&&hr(Z)&&wr(Je.tagNameCheck,Z))return!1;if(mt&&!Ir[Z]){const we=b(S),qe=v(S);if(qe&&we){const We=qe.length;for(let ot=We-1;ot>=0;--ot){const Rr=S===oe?f(qe[ot],!0):qe[ot];we.insertBefore(Rr,m(S))}}}return Ri(S),!0},Dt=function(S,Z,oe,we){return S.length===0?Z:Z===oe||Z===we?Li(Z):Z},Mt=function(S,Z){return S===Z||b(S)!==null?!1:(vr&&he(S),!0)},Hr=function(S,Z){if(br(U.beforeSanitizeElements,S,null),Mt(S,Z))return!0;if($e(S))return Ri(S),!0;const oe=_r(J(S));if(Ae=Dt(U.uponSanitizeElement,Ae,ce,Vt),br(U.uponSanitizeElement,S,{tagName:oe,allowedTags:Ae}),Mt(S,Z))return!0;if(Xr(S,oe))return Ri(S),!0;if(At[oe]||!(Et.tagCheck instanceof Function&&Et.tagCheck(oe))&&!Ae[oe]){const we=Cr(S,oe,Z);return we===!1&&(br(U.afterSanitizeElements,S,null),Mt(S,Z))?!0:we}if(L(S)===Ai.element&&!is(S)||(oe==="noscript"||oe==="noembed"||oe==="noframes")&&Kn(_z,S.innerHTML))return Ri(S),!0;if(re&&S.nodeType===Ai.text){const we=jr(S.textContent);S.textContent!==we&&(Ku(t.removed,{element:S.cloneNode()}),S.textContent=we)}return br(U.afterSanitizeElements,S,null),Mt(S,Z)},zr=function(S,Z,oe){if(pt[Z]||gt(Z,S)||me&&(Z==="id"||Z==="name")&&(oe in r||oe in ni))return!1;const we=ie[Z]||Et.attributeCheck instanceof Function&&Et.attributeCheck(Z,S);return Ze&&Kn(_e,Z)||Re&&Kn(Ue,Z)?!0:we?Or[Z]||Kn(Ne,Xu(oe,le,""))||(Z==="src"||Z==="xlink:href"||Z==="href")&&S!=="script"&&XS(oe,"data:")===0&&Nr[S]||Ye&&!Kn(it,Xu(oe,le,""))?!0:!oe:hr(S)&&wr(Je.tagNameCheck,S)&&wr(Je.attributeNameCheck,Z,S)||Z==="is"&&Je.allowCustomizedBuiltInElements&&wr(Je.tagNameCheck,oe)},Pt=Sr({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),hr=function(S){return!Pt[vd(S)]&&Kn(de,S)},Ur=function(S,Z,oe,we){if(V&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!oe)switch(u.getAttributeType(S,Z)){case"TrustedHTML":return ae(we);case"TrustedScriptURL":return ye(we)}return we},Gn=function(S,Z,oe,we){try{return oe?S.setAttributeNS(oe,Z,we):S.setAttribute(Z,we),$e(S)?(Ri(S),!1):!0}catch{return ee(Z,S),!1}},xr=function(S,Z){if(br(U.beforeSanitizeAttributes,S,null),Mt(S,Z))return;const oe=S.attributes;if(!oe||$e(S))return;ie=Dt(U.uponSanitizeAttribute,ie,De,ur);const we={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ie,forceKeepAttr:void 0};let qe=oe.length;const We=_r(S.nodeName);for(;qe--;){const ot=oe[qe],Rr=ot.name,qr=ot.namespaceURI,Br=ot.value,Gt=_r(Rr),Fr=Br;let sr=Rr==="value"?Fr:fz(Fr),k=!1;if(we.attrName=Gt,we.attrValue=sr,we.keepAttr=!0,we.forceKeepAttr=void 0,br(U.uponSanitizeAttribute,S,we),sr=we.attrValue,Nt&&(Gt==="id"||Gt==="name")&&XS(sr,tr)!==0&&(ee(Rr,S,ot),sr=tr+sr,k=!0),Qe&&Kn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,sr)){ee(Rr,S,ot);continue}if(Gt==="attributename"&&KS(sr,"href")){ee(Rr,S,ot);continue}if(!we.forceKeepAttr){if(!we.keepAttr){ee(Rr,S,ot);continue}if(!yt&&Kn(Az,sr)){ee(Rr,S,ot);continue}if(re&&(sr=jr(sr)),!zr(We,Gt,sr)){ee(Rr,S,ot);continue}sr=Ur(We,Gt,qr,sr),sr!==Fr&&Gn(S,Rr,qr,sr)&&k&&YS(t.removed)}}br(U.afterSanitizeAttributes,S,null),Mt(S,Z)},gn=function(S){let Z=null;const oe=et(S);for(br(U.beforeSanitizeShadowDOM,S,null);Z=oe.nextNode();)if(br(U.uponSanitizeShadowNode,Z,null),Hr(Z,S),xr(Z,S),Ar(Z.content)&&gn(Z.content),L(Z)===Ai.element){const we=I(Z);Ar(we)&&(qn(we),gn(we))}br(U.afterSanitizeShadowDOM,S,null)},qn=function(S){const Z=[{node:S,shadow:null}];for(;Z.length>0;){const oe=Z.pop();if(oe.shadow){gn(oe.shadow);continue}const we=oe.node,qe=L(we)===Ai.element,We=v(we);if(We)for(let ot=We.length-1;ot>=0;--ot)Z.push({node:We[ot],shadow:null});if(qe){const ot=$?$(we):null;if(typeof ot=="string"&&_r(ot)==="template"){const Rr=we.content;Ar(Rr)&&Z.push({node:Rr,shadow:null})}}if(qe){const ot=I(we);Ar(ot)&&Z.push({node:null,shadow:ot},{node:ot,shadow:null})}}};return t.sanitize=function(S){let Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},oe=null,we=null,qe=null,We=null;if(Fe=!S,Fe&&(S="<!-->"),typeof S!="string"&&!Kr(S)&&(S=vz(S),typeof S!="string"))throw ba("dirty is not a string, aborting");if(!t.isSupported)return S;zt?(Ae=Vt,ie=ur):Vn(Z),(U.uponSanitizeElement.length>0||U.uponSanitizeAttribute.length>0)&&(Ae=Li(Ae)),U.uponSanitizeAttribute.length>0&&(ie=Li(ie)),t.removed=[];const ot=vr&&typeof S!="string"&&Kr(S);if(ot){kr(S);const Br=J(S);if(typeof Br=="string"){const Gt=_r(Br);if(!Ae[Gt]||At[Gt])throw O(S),ba("root node is forbidden and cannot be sanitized in-place")}if($e(S))throw O(S),ba("root node is clobbered and cannot be sanitized in-place");try{qn(S)}catch(Gt){throw O(S),Gt}}else if(Kr(S))oe=Ie("<!---->"),we=oe.ownerDocument.importNode(S,!0),we.nodeType===Ai.element&&we.nodeName==="BODY"||we.nodeName==="HTML"?oe=we:oe.appendChild(we),qn(oe);else{if(!Rt&&!re&&!lt&&S.indexOf("<")===-1)return V&&ft?ae(S):S;if(oe=Ie(S),!oe)return Rt?null:ft?Y:""}oe&&st&&Ri(oe.firstChild);const Rr=ot?S:oe;try{const Br=et(Rr);for(;qe=Br.nextNode();)Hr(qe,Rr),xr(qe,Rr),Ar(qe.content)&&gn(qe.content)}catch(Br){throw ot&&(O(S),cl(t.removed,Gt=>{Gt.element&&he(Gt.element)})),Br}if(ot){let Br=!1;if(cl(t.removed,Gt=>{Gt.element&&(Gt.element===S&&(Br=!0),he(Gt.element))}),Br)throw ba("a node selected for removal could not be safely returned; refusing to sanitize in place");return re&&$t(S),S}if(Rt){if(re&&$t(oe),bt)for(We=Q.call(oe.ownerDocument);oe.firstChild;)We.appendChild(oe.firstChild);else We=oe;return(ie.shadowroot||ie.shadowrootmode)&&(We=B.call(n,We,!0)),We}let qr=lt?oe.outerHTML:oe.innerHTML;return lt&&Ae["!doctype"]&&oe.ownerDocument&&oe.ownerDocument.doctype&&oe.ownerDocument.doctype.name&&Kn(Rz,oe.ownerDocument.doctype.name)&&(qr="<!DOCTYPE "+oe.ownerDocument.doctype.name+`>
1091
+ `+qr),re&&(qr=jr(qr)),V&&ft?ae(qr):qr},t.setConfig=function(){let S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Vn(S),zt=!0,Vt=Ae,ur=ie},t.clearConfig=function(){Ji=null,zt=!1,Vt=null,ur=null,V=Pe,Y=""},t.isValidAttribute=function(S,Z,oe){Ji||Vn({});const we=_r(S),qe=_r(Z);return zr(we,qe,oe)},t.addHook=function(S,Z){typeof Z=="function"&&mi(U,S)&&Ku(U[S],Z)},t.removeHook=function(S,Z){if(mi(U,S)){if(Z!==void 0){const oe=uz(U[S],Z);return oe===-1?void 0:dz(U[S],oe,1)[0]}return YS(U[S])}},t.removeHooks=function(S){mi(U,S)&&(U[S]=[])},t.removeAllHooks=function(){U=sI()},t}var aI=JR(),Nz="data-pie-authored-ink",Dz="data-pie-authored-fill",jz="data-pie-authored-border",zz=["border-top-color","border-right-color","border-bottom-color","border-left-color"],Bz=new Set(["currentcolor","inherit","initial","unset","revert","revert-layer","transparent"]);function av(e){let t=e?.trim().toLowerCase();return!t||Bz.has(t)||t.includes("var(")?!1:QR(t)?.a!==0}function Fz(e){let t=QR(e);if(!t)return"shade";let r=l=>(l*t.a+255*(1-t.a))/255,[n,i,o]=[r(t.r),r(t.g),r(t.b)],s=.2126*uv(n)+.7152*uv(i)+.0722*uv(o),a=Math.max(n,i,o)-Math.min(n,i,o);return s>=.85&&a<=.08?"light":"shade"}function Hz(e){e.removeAttribute(Nz),e.removeAttribute(Dz),e.removeAttribute(jz);let t=e.hasAttribute("style")?e.style:void 0,r=c=>t?.getPropertyValue(c).trim()??"",n=[],i=r("color"),o=e.localName==="font"?e.getAttribute("color"):null;av(i||o)&&(e.setAttribute("data-pie-authored-ink",""),i&&n.push("color"));let s=r("background-color"),a=s||Uz(e.getAttribute("bgcolor"));av(a)&&(e.setAttribute("data-pie-authored-fill",Fz(a)),s&&n.push("background-color"));let l=zz.filter(c=>av(r(c)));l.length&&(e.setAttribute("data-pie-authored-border",""),n.push(...l));for(let c of n)t?.getPropertyPriority(c)==="important"&&t.setProperty(c,t.getPropertyValue(c))}function Uz(e){let t=e?.trim()??"";return/^(?:[\da-f]{3}|[\da-f]{6})$/i.test(t)?`#${t}`:t}function QR(e){let t=e.trim().toLowerCase();if(t==="transparent")return{r:0,g:0,b:0,a:0};let r=qz().get(t);if(r)return lI(r);if(t.startsWith("#"))return lI(t.slice(1));let n=/^([a-z]+)\(([^()]*)\)$/.exec(t);if(!n)return null;let i=n[2].trim().split(/\s*[\s,/]\s*/);if(i.length!==3&&i.length!==4)return null;let[o,s,a,l]=i,c=Wz(l),u;switch(n[1]){case"rgb":case"rgba":u=[o,s,a].map(g=>Xn(g,255)/255);break;case"hsl":case"hsla":u=eP(Ah(o),Xn(s,100)/100,Xn(a,100)/100);break;case"hwb":u=Vz(Ah(o),Xn(s,100)/100,Xn(a,100)/100);break;case"lab":u=uI(Xn(o,100),Xn(s,125),Xn(a,125));break;case"lch":u=uI(Xn(o,100),...cI(Xn(s,150),Ah(a)));break;case"oklab":u=dI(Xn(o,1),Xn(s,.4),Xn(a,.4));break;case"oklch":u=dI(Xn(o,1),...cI(Xn(s,.4),Ah(a)));break;default:return null}if(Number.isNaN(c)||u.some(Number.isNaN))return null;let[d,f,h]=u.map(g=>na(g,0,1)*255);return{r:d,g:f,b:h,a:c}}var lv;function qz(){return lv??(lv=new Map("aliceblue:f0f8ff antiquewhite:faebd7 aqua:00ffff aquamarine:7fffd4 azure:f0ffff beige:f5f5dc bisque:ffe4c4 black:000000 blanchedalmond:ffebcd blue:0000ff blueviolet:8a2be2 brown:a52a2a burlywood:deb887 cadetblue:5f9ea0 chartreuse:7fff00 chocolate:d2691e coral:ff7f50 cornflowerblue:6495ed cornsilk:fff8dc crimson:dc143c cyan:00ffff darkblue:00008b darkcyan:008b8b darkgoldenrod:b8860b darkgray:a9a9a9 darkgreen:006400 darkgrey:a9a9a9 darkkhaki:bdb76b darkmagenta:8b008b darkolivegreen:556b2f darkorange:ff8c00 darkorchid:9932cc darkred:8b0000 darksalmon:e9967a darkseagreen:8fbc8f darkslateblue:483d8b darkslategray:2f4f4f darkslategrey:2f4f4f darkturquoise:00ced1 darkviolet:9400d3 deeppink:ff1493 deepskyblue:00bfff dimgray:696969 dimgrey:696969 dodgerblue:1e90ff firebrick:b22222 floralwhite:fffaf0 forestgreen:228b22 fuchsia:ff00ff gainsboro:dcdcdc ghostwhite:f8f8ff gold:ffd700 goldenrod:daa520 gray:808080 green:008000 greenyellow:adff2f grey:808080 honeydew:f0fff0 hotpink:ff69b4 indianred:cd5c5c indigo:4b0082 ivory:fffff0 khaki:f0e68c lavender:e6e6fa lavenderblush:fff0f5 lawngreen:7cfc00 lemonchiffon:fffacd lightblue:add8e6 lightcoral:f08080 lightcyan:e0ffff lightgoldenrodyellow:fafad2 lightgray:d3d3d3 lightgreen:90ee90 lightgrey:d3d3d3 lightpink:ffb6c1 lightsalmon:ffa07a lightseagreen:20b2aa lightskyblue:87cefa lightslategray:778899 lightslategrey:778899 lightsteelblue:b0c4de lightyellow:ffffe0 lime:00ff00 limegreen:32cd32 linen:faf0e6 magenta:ff00ff maroon:800000 mediumaquamarine:66cdaa mediumblue:0000cd mediumorchid:ba55d3 mediumpurple:9370db mediumseagreen:3cb371 mediumslateblue:7b68ee mediumspringgreen:00fa9a mediumturquoise:48d1cc mediumvioletred:c71585 midnightblue:191970 mintcream:f5fffa mistyrose:ffe4e1 moccasin:ffe4b5 navajowhite:ffdead navy:000080 oldlace:fdf5e6 olive:808000 olivedrab:6b8e23 orange:ffa500 orangered:ff4500 orchid:da70d6 palegoldenrod:eee8aa palegreen:98fb98 paleturquoise:afeeee palevioletred:db7093 papayawhip:ffefd5 peachpuff:ffdab9 peru:cd853f pink:ffc0cb plum:dda0dd powderblue:b0e0e6 purple:800080 rebeccapurple:663399 red:ff0000 rosybrown:bc8f8f royalblue:4169e1 saddlebrown:8b4513 salmon:fa8072 sandybrown:f4a460 seagreen:2e8b57 seashell:fff5ee sienna:a0522d silver:c0c0c0 skyblue:87ceeb slateblue:6a5acd slategray:708090 slategrey:708090 snow:fffafa springgreen:00ff7f steelblue:4682b4 tan:d2b48c teal:008080 thistle:d8bfd8 tomato:ff6347 turquoise:40e0d0 violet:ee82ee wheat:f5deb3 white:ffffff whitesmoke:f5f5f5 yellow:ffff00 yellowgreen:9acd32".split(" ").map(e=>e.split(":")))),lv}function lI(e){if(!/^(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/.test(e))return null;let[t,r,n,i=255]=(e.length<=4?[...e].map(o=>o+o):e.match(/../g)??[]).map(o=>Number.parseInt(o,16));return{r:t,g:r,b:n,a:i/255}}var ZR=/^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|deg|rad|grad|turn)?$/;function Xn(e,t){if(e==="none")return 0;let r=ZR.exec(e);return!r||r[2]&&r[2]!=="%"?NaN:r[2]?Number(r[1])/100*t:Number(r[1])}function Ah(e){if(e==="none")return 0;let t=ZR.exec(e);if(!t||t[2]==="%")return NaN;let r=Number(t[1]);return((t[2]==="rad"?r*180/Math.PI:t[2]==="grad"?r*.9:t[2]==="turn"?r*360:r)%360+360)%360}function Wz(e){return e===void 0?1:na(Xn(e,1),0,1)}function cI(e,t){let r=Math.max(0,e),n=t*Math.PI/180;return[r*Math.cos(n),r*Math.sin(n)]}function eP(e,t,r){let n=na(t,0,1),i=na(r,0,1),o=s=>{let a=(s+e/30)%12,l=n*Math.min(i,1-i);return i-l*Math.max(-1,Math.min(a-3,9-a,1))};return[o(0),o(8),o(4)]}function Vz(e,t,r){let n=na(t,0,1),i=na(r,0,1);return n+i>=1?[,,,].fill(n/(n+i)):eP(e,1,.5).map(o=>o*(1-n-i)+n)}var $h=24389/27,cv=216/24389,Gz=[.3457/.3585,1,.2958/.3585],Yz=[[.955473421488075,-.02309845494876471,.06325924320057072],[-.0283697093338637,1.0099953980813041,.021041441191917323],[.012314014864481998,-.020507649298898964,1.330365926242124]],Kz=[[12831/3959,-329/214,-1974/3959],[-851781/878810,1648619/878810,36519/878810],[705/12673,-2585/12673,705/667]];function uI(e,t,r){let n=na(e,0,100),i=(n+16)/116,o=t/500+i,s=i-r/200;return Fy(Kz,Fy(Yz,[o**3>cv?o**3:(116*o-16)/$h,n>$h*cv?i**3:n/$h,s**3>cv?s**3:(116*s-16)/$h].map((a,l)=>a*Gz[l]))).map(tP)}function dI(e,t,r){let n=na(e,0,1);return Fy([[4.0767416621,-3.3077115913,.2309699292],[-1.2684380046,2.6097574011,-.3413193965],[-.0041960863,-.7034186147,1.707614701]],[n+.3963377774*t+.2158037573*r,n-.1055613458*t-.0638541728*r,n-.0894841775*t-1.291485548*r].map(i=>i**3)).map(tP)}function Fy(e,t){return e.map(r=>r[0]*t[0]+r[1]*t[1]+r[2]*t[2])}function tP(e){let t=na(e,0,1);return t<=.0031308?12.92*t:1.055*t**(1/2.4)-.055}function uv(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function na(e,t,r){return Math.min(r,Math.max(t,e))}function Xz(e,t={}){if(typeof e!="string"||e.length===0)return{ok:!1,reason:"invalid-url",message:"External stylesheet URL must be a non-empty string."};let r;try{r=t.baseUrl?new URL(e,t.baseUrl):new URL(e)}catch(o){return{ok:!1,reason:"invalid-url",message:`External stylesheet URL could not be parsed: ${String(o)}`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{ok:!1,reason:"disallowed-protocol",message:`External stylesheet protocol ${r.protocol} is not allowed (only http/https).`};const n=t.allowedOrigins??[];if(n.length>0)return n.includes(r.origin)?{ok:!0,resolvedUrl:r}:{ok:!1,reason:"disallowed-origin",message:`External stylesheet origin ${r.origin} is not in the configured allow-list.`};let i=null;if(t.baseUrl)try{i=new URL(t.baseUrl).origin}catch{i=null}return i===null?{ok:!1,reason:"disallowed-origin",message:"External stylesheet origin cannot be checked: no allow-list is configured and no usable baseUrl was supplied. Pass allowedOrigins to permit a cross-origin stylesheet."}:r.origin!==i?{ok:!1,reason:"disallowed-origin",message:`External stylesheet origin ${r.origin} is cross-origin and no allow-list is configured. Add it to \`allowed-style-origins\` to permit it.`}:{ok:!0,resolvedUrl:r}}function Jz(e){return typeof e!="string"||e.length===0?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function Qz(e){const t=new Map;for(const n of Object.values(e)){const i=String(n),o=Sm(i).name,s=t.get(o)??new Set;s.add(i),t.set(o,s)}const r=[...t.entries()].filter(([,n])=>n.size>1).map(([n])=>n).sort();return r.length>0?`IIFE bundles cannot load multiple package specs for: ${r.join(", ")}`:void 0}function Zz(e){const t=e.bundleType??Ro.clientPlayer,r=e.needsControllers??!0;let n=fI;const i=new Map,o={replaceLoadBundleScript(f){n=f,i.clear()},restore(){n=fI,i.clear()}};async function s(f,h){const g=i.get(f);if(g)return g;const m=a(f,h).finally(()=>{i.delete(f)});return i.set(f,m),m}async function a(f,h){const{retryDelayMs:g,timeoutMs:m}=nB(e.bundleRetry),v=Date.now();let b=0;for(;;){b+=1;try{await n(f,h);const I=Date.now()-v;b>1&&(e.onBundleRetryStatus?.({state:"completed",url:f,attempt:b,elapsedMs:I,timeoutMs:m}),c("pie-iife-bundle-retry-success",{url:f,attempt:b,elapsedMs:I,timeoutMs:m}));return}catch(I){const C=Date.now()-v,x=m-C,$=I instanceof Error?I.message:String(I);if(x<=0){const L=new Error(`IIFE bundle load timed out after ${m}ms: ${f}`);throw e.onBundleRetryStatus?.({state:"timeout",url:f,attempt:b,elapsedMs:C,timeoutMs:m,reason:$}),c("pie-iife-bundle-retry-timeout",{url:f,attempt:b,elapsedMs:C,timeoutMs:m,lastError:$}),u(L,{url:f,attempt:b,elapsedMs:C,timeoutMs:m,lastError:$}),L}const P=Math.min(g,x);e.onBundleRetryStatus?.({state:"retrying",url:f,attempt:b,elapsedMs:C,timeoutMs:m,retryDelayMs:P,reason:$}),c("pie-iife-bundle-retry",{url:f,attempt:b,elapsedMs:C,retryDelayMs:P,timeoutMs:m,lastError:$}),await iB(P)}}}function l(){if(!e.trackPageActions)return;const f=e.instrumentationProvider;if(Pb(f)&&f.isReady())return f}function c(f,h){const g=l();if(g)try{g.trackEvent(f,h)}catch{}}function u(f,h){const g=l();if(g)try{g.trackError(f,{...h,component:"iife-adapter",errorType:"IifeBundleRetryError"})}catch{}}async function d(f,h){if(!f||Object.keys(f).length===0)return;const g=Qz(f);if(g){const C=new Map;for(const x of Object.keys(f))C.set(x,{kind:"backend-rejected",tag:x,cause:g});throw new Wc(C)}const m=tB(f,t,e);try{await s(m,h.doc)}catch(C){const x=C instanceof Error?C.message:String(C),$=new Map;for(const P of Object.keys(f))$.set(P,{kind:"bundle-load-failed",tag:P,url:m,cause:x});throw new Wc($)}const v=eB();if(!v){const C=new Map;for(const x of Object.keys(f))C.set(x,{kind:"bundle-load-failed",tag:x,url:m,cause:"window.pie.default missing after bundle load"});throw new Wc(C)}const b=new Map,I=t===Ro.editor;for(const[C,x]of Object.entries(f)){const $=d$(x),P=v[$];if(!P){b.set(C,{kind:"package-not-in-bundle",tag:C,packageName:$,availablePackages:Object.keys(v)});continue}const L=I?P.Configure??oB():P.Element;if(!L){b.set(C,{kind:"no-element-class",tag:C,packageName:$});continue}if(!f$(L)){b.set(C,{kind:"not-a-constructor",tag:C,packageName:$});continue}let J;try{J=s$(C,`element tag for ${$}`)}catch(V){b.set(C,{kind:"define-failed",tag:C,cause:V instanceof Error?V.message:String(V)});continue}try{_T(J,class extends L{},`element tag for ${$}`)}catch(V){b.set(C,{kind:"define-failed",tag:C,cause:V instanceof Error?V.message:String(V)});continue}xT({package:x,status:Rb.loaded,tagName:J,element:L,controller:r?P.controller??null:null,config:P.config??null,bundleType:t})}if(b.size>0)throw new Wc(b)}return{load:d,get __seams(){return o}}}function fI(e,t){return new Promise((r,n)=>{const i=t.createElement("script");i.src=e,i.defer=!0,i.setAttribute("data-pie-bundle","true"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load IIFE bundle from: ${e}`)),t.head.appendChild(i)})}function eB(){const e=globalThis.window?.pie?.default;if(!(!e||typeof e!="object"))return e}function tB(e,t,r){const n=Object.keys(e).sort().join(",");if(r.bundleInfo?.url){const s=r.bundleInfo.url.includes("?")?"&":"?";return n?`${r.bundleInfo.url}${s}elements=${encodeURIComponent(n)}`:r.bundleInfo.url}const i=t$(Object.values(e)),o=`${rB(r.bundleHost)}${i}/${t}`;return n?`${o}?elements=${encodeURIComponent(n)}`:o}function rB(e){return`${e.trim().replace(/\/+$/,"")}/`}function nB(e){return{retryDelayMs:typeof e?.retryDelayMs=="number"&&e.retryDelayMs>0?e.retryDelayMs:cm.retryDelayMs,timeoutMs:typeof e?.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:cm.timeoutMs}}function iB(e){return new Promise(t=>setTimeout(t,e))}function oB(){return class extends HTMLElement{constructor(...e){super(...e),Ee(this,"_model",void 0),Ee(this,"_configuration",void 0)}get model(){return this._model}set model(e){this._model=e}get configuration(){return this._configuration}set configuration(e){this._configuration=e}}}var rP=class extends Error{constructor(e,t,r){super(e),Ee(this,"name","ElementLoaderError"),Ee(this,"unregisteredTags",void 0),Ee(this,"reasons",void 0),this.unregisteredTags=t,this.reasons=r}},sB=e=>{switch(e.kind){case"timeout":return`not defined within ${e.timeoutMs} ms`;case"module-load-failed":return`${e.specifier} failed to load: ${e.cause}`;case"bundle-load-failed":return`${e.url} failed to load: ${e.cause}`;case"define-failed":case"backend-rejected":return e.cause;case"not-a-constructor":return`${e.packageName??"its package"} exports no element constructor`;case"no-element-class":return`${e.packageName} exports no element class`;case"package-not-in-bundle":return`${e.packageName} is not in the bundle, which holds ${e.availablePackages.join(", ")||"no packages"}`}};function aB(e){if(e instanceof rP)return[...e.reasons].map(([t,r])=>`${t} (${r.kind}): ${sB(r)}`).join("; ")}var lB=class extends Error{constructor(e,t,r,n={}){super(cB(e,t,r,n)),Ee(this,"name","ElementAssertionError"),Ee(this,"expectedTags",void 0),Ee(this,"missingTags",void 0),Ee(this,"currentlyRegisteredTags",void 0),this.expectedTags=e,this.missingTags=t,this.currentlyRegisteredTags=r}};function cB(e,t,r,n){const i=t.map(o=>{const s=nP(n[o]),a=Od(o).baseName,l=s?r.filter(u=>uB(u)===s):r.filter(u=>Od(u).baseName===a);!l.includes(a)&&Ff(a)&&l.push(a);const c=s??a;return l.length>0?`${c} is registered as [${l.join(", ")}]`:`nothing is registered for ${c}`});return`ElementLoader.assertRegistered: missing [${t.join(", ")}] of [${e.join(", ")}]; ${i.join("; ")}.`}function nP(e){if(e)try{return Sm(e).name||void 0}catch{return}}function uB(e){return nP(wm()[e]?.package)}var dB=5e3,fB=cm.timeoutMs,Mh=new Map,hI=new Map,hB=new Map;async function pI(e,t){if(!e||Object.keys(e).length===0)return;PT(e,t.elementPackagePolicy);const r=Object.keys(e),n=t.whenDefinedTimeoutMs??dB,i=t.loadTimeoutMs??fB;if(CB(r))return;const o=bB(t.backend,e),s=Mh.get(o);if(s)return s;const a=pB(e,r,vB(t.backend),{doc:yB(t.doc),whenDefinedTimeoutMs:n},n,i);Mh.set(o,a);try{await a}finally{Mh.get(o)===a&&Mh.delete(o)}}async function pB(e,t,r,n,i,o){let s;try{await mB(r.load(e,n),t,o)}catch(u){s=u instanceof Error?u:new Error(String(u))}const a=await Promise.all(t.map(async u=>{if(Ff(u))return{tag:u,ok:!0};const d=bI(s,u);if(d&&d.kind!=="timeout")return{tag:u,ok:!1};try{return await xB(u,i),{tag:u,ok:!0}}catch{return{tag:u,ok:!1}}})),l=new Set,c=new Map;for(const u of a){if(u.ok)continue;l.add(u.tag);const d=bI(s,u.tag);c.set(u.tag,d??{kind:"timeout",tag:u.tag,timeoutMs:i})}if(l.size>0)throw new rP(`Element registration failed; missing tags: ${[...l].join(", ")}`,l,c)}async function mB(e,t,r){let n;try{await Promise.race([e,new Promise((i,o)=>{n=setTimeout(()=>{const s=new Map;for(const a of t)s.set(a,{kind:"timeout",tag:a,timeoutMs:r});o(new Wc(s))},r)})])}finally{n&&clearTimeout(n)}}function gB(e){const t=Array.isArray(e)?{}:e??{},r=Array.isArray(e)?e:Object.keys(t);if(r.length===0)return;const n=r.filter(i=>!Ff(i));if(n.length!==0)throw new lB(r,n,RB(),t)}function vB(e){if(iP(e))return e;if("kind"in e){if(e.kind==="iife")return Zz(e);if(e.kind==="esm"){const t=oP(e),r=hB.get(t);if(r)return r;const n=hI.get(t);if(n)return n;const i=i$(e);return hI.set(t,i),i}}throw new Error("ElementLoader: invalid backend option")}function iP(e){return typeof e.load=="function"&&!("kind"in e)}function yB(e){if(e)return e;if(typeof document<"u")return document;throw new Error("ElementLoader: no Document available; pass options.doc explicitly")}function bB(e,t){const r=oP(e),n=Object.entries(t).sort(([i],[o])=>i.localeCompare(o));return`${r}|${JSON.stringify(n)}`}var mI=new WeakMap,wB=0,gI=new WeakMap,SB=0,vI=new WeakMap,IB=0;function oP(e){if(iP(e)){let t=mI.get(e);return t||(t=`b${++wB}`,mI.set(e,t)),`backend#${t}`}if("kind"in e){if(e.kind==="iife")return`iife#${yI({kind:"iife",bundleHost:e.bundleHost,bundleType:e.bundleType??"",needsControllers:e.needsControllers??!0,bundleInfo:e.bundleInfo??null,debugEnabled:e.debugEnabled??null,bundleRetry:e.bundleRetry??null,onBundleRetryStatus:e.onBundleRetryStatus??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`;if(e.kind==="esm")return`esm#${yI({kind:"esm",cdnBaseUrl:e.cdnBaseUrl,cdnProvider:e.cdnProvider??null,moduleResolution:e.moduleResolution??"url",view:e.view??"delivery",viewConfig:e.viewConfig??null,loadControllers:e.loadControllers??!0,debugEnabled:e.debugEnabled??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`}return"unknown"}function yI(e){return JSON.stringify(Hy(e,new Map))}function Hy(e,t){if(e==null)return e;const r=typeof e;if(r==="string"||r==="number"||r==="boolean")return e;if(r==="function")return{__functionRef:TB(e)};if(r!=="object")return String(e);const n=e,i=t.get(n);if(i)return{__cycleRef:i};const o=`cycle#${t.size+1}`;if(t.set(n,o),Array.isArray(e))return e.map(a=>Hy(a,t));if(!kB(e))return{__objectRef:EB(n)};const s={};for(const a of Object.keys(e).sort())s[a]=Hy(e[a],t);return s}function kB(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function TB(e){let t=gI.get(e);return t||(t=`fn#${++SB}`,gI.set(e,t)),t}function EB(e){let t=vI.get(e);return t||(t=`obj#${++IB}`,vI.set(e,t)),t}function CB(e){return e.every(t=>Ff(t))}function Ff(e){return typeof customElements>"u"?!1:customElements.get(e)!==void 0}async function xB(e,t){if(typeof customElements>"u")throw new Error(`no customElements to await ${e}`);let r;try{return await Promise.race([customElements.whenDefined(e).then(()=>{}),new Promise((n,i)=>{r=setTimeout(()=>i(new Error(`Timeout waiting for ${e}`)),t)})])}finally{r&&clearTimeout(r)}}function RB(){return typeof window>"u"?[]:Object.values(wm()).filter(e=>e?.status===Rb.loaded).map(e=>e.tagName).filter(e=>typeof e=="string"&&Ff(e)).sort()}function bI(e,t){if(e)return e instanceof Wc?e.reasons.get(t):{kind:"backend-rejected",tag:t,cause:e.message}}function PB(e){return e.loadControllers??(e.author||!e.hosted)}function _B(e,t=$B()){const r=e?.elements;if(!t||!r||typeof r!="object")return e;let n=!1;const i={};for(const[o,s]of Object.entries(r)){const a=String(s),l=AB(a,t);i[o]=l??a,l!==void 0&&l!==a&&(n=!0)}return n?{...e,elements:i}:e}function AB(e,t){let r;try{r=Sm(e).name}catch{return}const n=t[r];return typeof n=="string"&&n.length>0?n:void 0}function $B(){if(typeof window>"u")return;const e=window.PIE_PRELOADED_ELEMENTS;return e&&typeof e=="object"?e:void 0}function MB(e){if(typeof window>"u"||typeof customElements>"u")return[];const t=[];for(const[r,n]of Object.entries(e)){if(customElements.get(r))continue;const i=OB(r,n);if(!i)continue;const{entry:o,elementClass:s}=i;_T(r,class extends s{},`preloaded element tag for ${n}`),xT({...o,tagName:r}),t.push(r)}return t}function OB(e,t){const{existingEncodedVersion:r}=Od(e);if(!r)return;let n;for(const i of Object.values(wm())){if(i?.status!==Rb.loaded||i.package!==t||typeof i.tagName!="string"||Od(i.tagName).existingEncodedVersion!==r)continue;const o=customElements.get(i.tagName);o&&(!n||!n.entry.controller&&i.controller)&&(n={entry:i,elementClass:o})}return n}var sP=(...e)=>e.reduce((t,r)=>{for(const n in r)Object.hasOwn(r,n)&&r[n]!==null&&r[n]!==void 0&&(t[n]=r[n]);return t},{}),co=lf("pie-updates",()=>cf()),aP=e=>{if(!e)return"missing";if(typeof e=="function")return"function";if(typeof e!="object")return typeof e;const t=Object.keys(e),r=e.default,n=r&&typeof r=="object"?Object.keys(r):[];return n.length>0?`object(keys=[${t.join(",")}],defaultKeys=[${n.join(",")}])`:`object(keys=[${t.join(",")}])`},LB=e=>{if(!e)return null;if(typeof e=="function")return e;if(typeof e!="object")return null;const t=e.model;if(typeof t=="function")return(n,i,o,s)=>t.call(e,n,i,o,s);const r=e.default;if(r&&typeof r=="object"){const n=r.model;if(typeof n=="function")return(i,o,s,a)=>n.call(r,i,o,s,a)}return null},NB=(e,t)=>{e.dispatchEvent(new CustomEvent("pie-controller-error",{detail:t,bubbles:!0,composed:!0}))},DB=e=>{const t=e.isConnected;return()=>t&&!e.isConnected},jB=async(e,t,r,n,i,o,s,a)=>{co.debug(`${o} Using controller, env:`,i),co.debug(`${o} Model before filter:`,{id:t.id,element:t.element,hasCorrectResponse:"correctResponse"in t});const l=(c,u,d)=>(co.debug(`${o} updateSession called for ${c} with:`,d),Object.assign(r,d),a?.(t.id,t.element,d),Promise.resolve());try{const c=LB(n);if(!c)throw new Error(`Controller contract mismatch: expected a model() function but received ${aP(n)}`);const u=await c(t,r,i,l),d=u&&typeof u=="object"?u:{},f={id:t.id,element:t.element,...d};if(co.debug(`${o} ✅ Controller filtered model:`,{id:f.id,element:f.element,hasCorrectResponse:"correctResponse"in f,mode:i.mode,role:i.role}),s())return;e.model=f,e.session=r}catch(c){throw co.error(`${o} ❌ Controller error:`,c),c}},zB=e=>{const{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}=sP(RT,e);if(!n)throw new Error("env is required");if(!r)throw new Error("session is required");if(!t)throw new Error("config is required");return{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}},BB=async(e,t,r,n)=>{const{config:i,session:o,env:s,eventListeners:a,invokeControllerForModel:l,bundleType:c,onElementSessionUpdate:u}=r,d=i.models?.find(h=>h.id===e.id);if(!d)throw co.error(`${n} Model not found for`,t),new Error(`model not found for ${t}`);const f=$T(o,d.id,d.element);if(a&&Object.entries(a).forEach(([h,g])=>{e.addEventListener(h,g)}),s&&l){const h=BR(t,c);if(!h){co.debug(`${n} ℹ️ No controller for ${t}, using server-processed model`),e.model=d,e.session=f;return}co.debug(`${n} Invoking controller for ${t}#${e.id}`,{mode:s.mode,role:s.role,hasCorrectResponse:"correctResponse"in d});const g=DB(e);try{await jB(e,d,f,h,s,`${n}(${t}#${e.id})`,g,u)}catch(m){const v=m instanceof Error?m.message:String(m),b=v.includes("Controller contract mismatch");if(co.error(`${n} Controller failed for ${t}#${e.id}:`,m),NB(e,{code:b?"PIE_CONTROLLER_CONTRACT_ERROR":"PIE_CONTROLLER_RUNTIME_ERROR",message:`${t} controller failed while applying model for ${e.id}. ${v}`,recoverable:!0,elementName:t,elementId:e.id,controllerShape:aP(h),cause:v}),g())return;e.model=d,e.session=f}}else co.debug(`${n} Direct model assignment for ${t}#${e.id} (no controller invocation requested)`),e.model=d,e.session=f},FB=(e,t)=>{const r=zB(t),{container:n}=sP(RT,t),i=(n||document).querySelectorAll(e);return!i||i.length===0?(co.debug(`no elements found for ${e}`),Promise.resolve()):Promise.all(Array.from(i,o=>BB(o,e,r,"[updatePieElement]"))).then(()=>{})},wI=(e,t,r,n,i,o)=>(co.debug("[updatePieElements] Updating all elements with env:",r),Promise.all(Object.entries(e.elements).map(([s,a])=>FB(s,{config:e,session:t,env:r,container:n,onElementSessionUpdate:i,bundleType:o}))).then(()=>{})),HB=lf("instrumentation-event-bridge",()=>cf());function UB(e){if(e===null)return!0;const t=typeof e;if(t==="function"||t==="symbol")return!1;if(t!=="object"||Array.isArray(e))return!0;const r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function qB(e){if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))UB(n)&&(t[r]=n);return t}return typeof e>"u"?{}:{value:e}}function WB(e){HB.warn(`[InstrumentationEventBridge:${e}] Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}function VB(e){try{e.provider.trackError(e.error instanceof Error?e.error:new Error(String(e.error??"Unknown instrumentation bridge error")),{component:e.component,errorType:"InstrumentationBridgeError",sourceEventName:e.sourceEventName})}catch{}}function GB(e){if(!e.host||!e.eventMap.length)return()=>{};if(!e.instrumentationProvider)return()=>{};if(!Pb(e.instrumentationProvider))return e.debug&&WB(e.component),()=>{};const t=e.instrumentationProvider,r=[],n=Math.max(0,e.dedupeWindowMs??0),i=new Map,o=(s,a)=>{const l=[a.assessmentId,a.sectionId,a.attemptId,a.itemId,a.canonicalItemId,a.sourceRuntimeId].map(c=>String(c??"")).join("|");return`${s.instrumentationEventName}|${l}`};for(const s of e.eventMap){const a=l=>{try{if(!t.isReady()||e.shouldTrackEvent&&!e.shouldTrackEvent(l))return;const c=qB(l.detail),u=new Date().toISOString(),d={...c,...e.staticAttributes,component:e.component,sourceEventName:s.sourceEventName,timestamp:u};if(n>0){const f=Date.now(),h=o(s,d),g=i.get(h);if(typeof g=="number"&&f-g<n)return;i.set(h,f)}t.trackEvent(s.instrumentationEventName,{...d})}catch(c){VB({provider:t,component:e.component,error:c,sourceEventName:s.sourceEventName})}};e.host.addEventListener(s.sourceEventName,a),r.push(()=>{e.host?.removeEventListener(s.sourceEventName,a)})}return()=>{for(const s of r)s()}}function SI(e){return e&&typeof e=="object"?e:{}}function II(e){const t=SI(SI(e).loaderConfig);return Object.keys(t).length>0?t:null}function kI(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function TI(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function YB(e,t){return e.kind==="value"||e.kind==="null"?e:t}var Oh,KB=lf("instrumentation-provider-resolution",()=>cf());function XB(){return Oh||(Oh=new Z7,Oh.initialize()),Oh}function JB(e){const t=II(e.runtimePlayer),r=II(e.player),n=TI(t),i=TI(r),o=n??i??!1,s=YB(kI(t),kI(r));if(s.kind!=="null"){if(s.kind==="unset")return o?XB():void 0;if(Pb(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";KB.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var QB=[{sourceEventName:"correct-responses-populated",instrumentationEventName:"pie-item-correct-responses-populated"}],ZB=class{constructor(){Ee(this,"store",new Map)}load(e){return this.store.get(e)??null}save(e,t){this.store.set(e,t)}clear(e){this.store.delete(e)}},e4="",Uy=new Set(["complete","component","elementId","timestamp","sourceRuntimeId"]),t4=new Set(["id","element",...Uy]);function r4(e,t){if(!e&&!t)return!0;if(!e||!t||(e.id||"")!==(t.id||""))return!1;try{return JSON.stringify(e.data||[])===JSON.stringify(t.data||[])}catch{return!1}}function n4(e,t){return!t||e.id!==""?t:{...t,id:""}}function Ma(e,t=e4){if(e&&typeof e=="object"){const r=e;return Array.isArray(r.data)?{id:typeof r.id=="string"?r.id:t,data:r.data}:Array.isArray(e)?{id:t,data:e}:{id:t,data:[e]}}return Array.isArray(e)?{id:t,data:e}:{id:t,data:[]}}function ef(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>ef(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"&&r!==void 0&&r!==null&&!(typeof r=="string"&&r.trim()==="")&&!(Array.isArray(r)&&r.length===0)||ef(r))return!0;return!1}var i4=new Set(["id","element","complete","component","timestamp","sourceRuntimeId","shuffledValues"]);function qy(e,t){return e==null?!1:typeof e=="string"?e.trim()!=="":typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.some(r=>qy(r)):typeof e!="object"?!1:Object.entries(e).some(([r,n])=>r==="id"&&t!==void 0&&n===t?!1:qy(n,r))}function X0(e){return!e||typeof e!="object"?!1:Array.isArray(e)?e.some(X0):Object.entries(e).some(([t,r])=>!i4.has(t)&&qy(r,t))}function um(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>um(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"||um(r))return!0;return!1}function Ul(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tl(e,t){if(typeof e.component=="string")return e.component;if(typeof t?.component=="string")return t.component}function rl(e,t){if(typeof e.complete=="boolean")return e.complete;if(typeof t?.complete=="boolean")return t.complete}function nl(e,t){const r=typeof e.elementId=="string"&&e.elementId?e.elementId:typeof t?.id=="string"&&t.id?t.id:void 0;return r?{elementId:r}:{}}function lP(e){const t=Object.keys(e);return("id"in e||"element"in e)&&!um(e)&&t.every(r=>t4.has(r))}function o4(e){return e.data.length>0&&e.data.every(t=>t&&typeof t=="object"&&!Array.isArray(t)&&lP(t))}function cP(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];r[n]=Ul(o)&&Ul(i)?cP(o,i):i}return r}function uP(e,t,r,n){const i=Ma(t,e),o=[...i.data],s=o.findIndex(a=>!a||typeof a!="object"?!1:a.id===r);if(s>=0){const a=o[s];o[s]=a&&typeof a=="object"?cP(a,n):n}else o.push(n);return{id:i.id||e,data:o}}function dP(e){const t=s4(e),r=e.sessionDetail?.sessionCommitReason;return typeof r=="string"&&r?{...t,sessionCommitReason:r}:t}function s4(e){const t=e.sessionDetail||{},r=t&&typeof t=="object"&&"session"in t?t.session:e.sessionDetail,n=typeof e.itemId=="string"&&e.itemId?e.itemId:typeof r?.id=="string"?String(r.id):"";if(!r||typeof r!="object")return{itemId:n,session:null,intent:"metadata-only",component:tl(t),...nl(t),complete:rl(t)};const i=r;if(Array.isArray(i.data)){const l=Ma(i,n),c=n4(l,e.previousItemSession!==void 0?Ma(e.previousItemSession,n):null),u=Object.keys(t),d=u.length>0&&u.every(h=>h==="session"||Uy.has(h)),f=u.some(h=>h!=="session");return d&&f&&c&&r4(l,c)?{itemId:n,session:null,intent:"metadata-only",component:tl(t),...nl(t),complete:rl(t)}:d&&o4(l)?{itemId:n,session:null,intent:"metadata-only",component:tl(t),...nl(t),complete:rl(t)}:{itemId:n,session:l,intent:"replace-item-session",component:tl(t),...nl(t),complete:rl(t)}}const o=Object.keys(i);if(o.length>0&&o.every(l=>Uy.has(l)))return{itemId:n,session:null,intent:"metadata-only",component:tl(t,i),...nl(t),complete:rl(t,i)};if(lP(i))return{itemId:n,session:null,intent:"metadata-only",component:tl(t,i),...nl(t,i),complete:rl(t,i)};const s=tl(t,i)??"response",a=typeof i.id=="string"&&i.id?i.id:s;return{itemId:n,session:uP(n,e.previousItemSession,a,{id:a,...i}),intent:"merge-element-session",component:s,...nl(t,i),complete:rl(t,i)}}function fP(e){if(!Ul(e)||Object.isFrozen(e))return null;const t=e.data;if(Array.isArray(t))return Object.isFrozen(t)?null:t;if(t==null){const r=[];return e.data=r,r}return null}function Wy(e){if(!Ul(e))return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function a4(e,t){const r=fP(e);if(!r)return!1;let n=!1;for(const i of t)typeof i!="string"||i.length===0||r.some(o=>Wy(o)===i)||(r.push({id:i}),n=!0);return n}function l4(e,t){const r=fP(e);if(!r||!Ul(e))return!1;const n=Ma(t);let i=!1;typeof e.id!="string"&&(e.id=n.id,i=!0);for(const o of n.data){const s=Wy(o);if(!s||!Ul(o))continue;const a=r.find(l=>Wy(l)===s);if(!Ul(a)){r.push({...o}),i=!0;continue}for(const l of Object.keys(a))l in o||(delete a[l],i=!0);for(const[l,c]of Object.entries(o))a[l]!==c&&(a[l]=c,i=!0)}return i}var c4="";function u4(e){try{return structuredClone(e)}catch{return{id:e.id,data:JSON.parse(JSON.stringify(e.data??[]))}}}var d4=class{constructor(e){Ee(this,"storage",void 0),Ee(this,"session",void 0),Ee(this,"storageKey",void 0),Ee(this,"sessionId",void 0),Ee(this,"itemId",void 0),this.storage=e.storage??new ZB,this.itemId=e.itemId,this.storageKey=e.storageKey??`pie:item-controller:v1:${e.itemId}`,this.sessionId=e.sessionId??c4,this.session=Ma(e.initialSession,this.sessionId)}async hydrate(){const e=await this.storage.load(this.storageKey);return e&&(this.session=Ma(e,this.sessionId)),this.getSession()}async persist(){await this.storage.save(this.storageKey,this.session)}async clearPersisted(){await this.storage.clear?.(this.storageKey)}getSession(){return u4(this.session)}setSession(e,t={}){const r=Ma(e,this.sessionId),n=t.allowMetadataOverwrite??!1,i=r.id===""||this.session.id===""||r.id===this.session.id;return!n&&i&&ef(this.session)&&!ef(r)&&!um(r)?this.getSession():(this.session=r,t.persist!==!1&&this.persist(),this.getSession())}mergeElementSession(e,t,r={}){return this.session=uP(this.session.id||this.sessionId,this.session,e,{id:e,...t}),r.persist===!0&&this.persist(),this.getSession()}updateFromEventDetail(e,t={}){const r=dP({itemId:this.session.id||this.itemId,sessionDetail:e,previousItemSession:this.session});return r.intent==="metadata-only"||!r.session?this.getSession():this.setSession(r.session,t)}},EI=Ma,f4="commitPendingSession",hP=Symbol.for("pie.sessionCommit.observedSignature");function pP(e){return!!e&&typeof e=="object"}function mP(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function h4(e){return e?.shadowRoot??null}function p4(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function Vy(e,t,r){const n=h4(e);n&&Vy(n,t,r);const i=s=>{t.has(s)||(t.add(s),mP(s)&&r.push(s),Vy(s,t,r))};for(const s of p4(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function m4(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function g4(e){const t=[],r=new Set;return m4(e)&&mP(e)&&(r.add(e),t.push(e)),Vy(e,r,t),t}function v4(e){try{return e.session}catch{return}}function y4(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function b4(e){const t=e[hP];return typeof t=="string"?t:void 0}function CI(e,t){try{Object.defineProperty(e,hP,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function w4(e,t,r){const n=e;if(typeof n.addEventListener!="function")return r();const i=o=>{const s=o.detail;if(!(!pP(s)||"sessionCommitReason"in s))try{s.sessionCommitReason=t}catch{}};n.addEventListener("session-changed",i,!0);try{return r()}finally{n.removeEventListener("session-changed",i,!0)}}function yd(e,t={}){const r={committed:0,synthesized:0,skipped:0};if(!e)return r;const n=t.reason??"teardown";return w4(e,n,()=>gP(e,n,t.logger,r))}function gP(e,t,r,n){const i=t?"commitPendingSessions":"flushPendingSessionNotifications";for(const o of g4(e)){const s=v4(o);if(!pP(s)){n.skipped+=1;continue}const a=y4(s);if(a===null){n.skipped+=1;continue}const l=b4(o);if(l===a){n.skipped+=1;continue}if(l===void 0&&!X0(s)){n.skipped+=1;continue}const c=o[f4];if(typeof c=="function"){let u=!1;const d=()=>{u=!0};o.addEventListener("session-changed",d,!0);let f=!1;try{c.call(o)}catch(h){f=!0,r?.warn(`[${i}] ${o.tagName.toLowerCase()} failed to commit its pending session`,h)}finally{o.removeEventListener("session-changed",d,!0)}if(f){n.skipped+=1;continue}if(u){CI(o,a),n.committed+=1;continue}}try{o.dispatchEvent(new CustomEvent("session-changed",{bubbles:!0,composed:!0,detail:{component:o.tagName.toLowerCase(),session:JSON.parse(a),...t?{sessionCommitReason:t}:{}}})),CI(o,a),n.synthesized+=1}catch(u){r?.warn(`[${i}] ${o.tagName.toLowerCase()} session commit dispatch failed`,u),n.skipped+=1}}return n}function S4(e,t={}){const r={committed:0,synthesized:0,skipped:0};return e?gP(e,null,t.logger,r):r}function I4(e){if(typeof document>"u"||typeof window>"u")return()=>{};const t=i=>{yd(e.root(),{reason:i,logger:e.logger});try{e.onHidden?.(i)}catch(o){e.logger?.warn("[bindPageLifecycleCommit] onHidden failed",o)}},r=()=>{document.visibilityState==="hidden"&&t("page-hidden")},n=()=>{t("page-hidden")};return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",n),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",n)}}var k4="pie-session-snapshot";function T4(e){return!!e.sessionId}function E4(e){return`${k4}:${[e.assignmentId||"",e.sessionId||"",e.itemId||""].join("|")}`}function C4(){return{read(e){try{return typeof sessionStorage>"u"?null:sessionStorage.getItem(e)}catch{return null}},write(e,t){try{if(typeof sessionStorage>"u")return;sessionStorage.setItem(e,t)}catch{}},clear(e){try{if(typeof sessionStorage>"u")return;sessionStorage.removeItem(e)}catch{}}}}function x4(e){return typeof e=="boolean"?e:e?e.enabled!==!1:!1}function R4(e){if(!x4(e.config))return null;const t=typeof e.config=="object"&&e.config?e.config:{};if(!t.key&&!T4(e.identity))return null;const r=t.key||E4(e.identity),n=t.store||C4(),i=()=>{try{return n.read(r)}catch{return null}},o=a=>{try{n.write(r,a)}catch{}},s=()=>{try{n.clear(r)}catch{}};return{key:r,write(a){let l;try{l=JSON.stringify({session:a,timestamp:Date.now()})}catch{return}o(l)},read(){const a=i();if(!a)return null;try{const l=JSON.parse(a);return!l||typeof l!="object"||!("session"in l)?null:{key:r,session:l.session,timestamp:typeof l.timestamp=="number"?l.timestamp:0}}catch{return null}},clear(){s()}}}var P4=new Set(["media","supports","container","layer","scope"]),_4=/^(?::root|html|body)(?![\w-])/,A4=/^@(?:-[a-z]+-)?([\w-]+)/i;function $4(e,t){if(typeof e!="string"||e.length===0)return"";const r=t?.trim();return r?vP(j4(e),r):e}function M4(e,t){const r=e.trim(),n=t.trim();if(!r||!n)return"";if(r===n||r.startsWith(`${n} `))return r;const i=_4.exec(r);return i?`${n}${r.slice(i[0].length)}`:`${n} ${r}`}function vP(e,t){let r="",n=0;for(;n<e.length;){const i=L4(e,n);if(i.end<=n)break;r+=O4(i,t),n=i.end}return r}function O4(e,t){if(e.kind==="statement"){const i=e.text.trim();return i===";"?"":`${i}
1092
+ `}if(e.kind==="trailing")return e.text.trim()?`${e.text.trim()}
1093
+ `:"";const r=e.prelude.trim();if(!r)return"";if(r.startsWith("@")){const i=A4.exec(r)?.[1]?.toLowerCase();if(i&&P4.has(i)){const o=vP(e.block,t);return o.trim()?`${r} {
1094
+ ${o}}
1095
+ `:""}return`${r} {${e.block}}
1096
+ `}const n=D4(r,",").map(i=>M4(i,t)).filter(Boolean);return n.length===0?"":`${n.join(", ")} {${e.block}}
1097
+ `}function L4(e,t){let r=t,n=null,i=0;for(;r<e.length;){const o=e[r];if(n)o==="\\"?r+=1:o===n&&(n=null);else if(o==='"'||o==="'")n=o;else if(o==="(")i+=1;else if(o===")")i>0&&(i-=1);else{if(i===0&&o===";")return{kind:"statement",text:e.slice(t,r+1),end:r+1};if(i===0&&o==="{"){const s=N4(e,r);return{kind:"rule",prelude:e.slice(t,r),block:e.slice(r+1,s.contentEnd),end:s.end}}}r+=1}return{kind:"trailing",text:e.slice(t),end:e.length}}function N4(e,t){let r=0,n=null;for(let i=t;i<e.length;i+=1){const o=e[i];if(n){o==="\\"?i+=1:o===n&&(n=null);continue}if(o==='"'||o==="'"){n=o;continue}if(o==="{")r+=1;else if(o==="}"&&(r-=1,r===0))return{contentEnd:i,end:i+1}}return{contentEnd:e.length,end:e.length}}function D4(e,t){const r=[];let n="",i=null,o=0;for(let s=0;s<e.length;s+=1){const a=e[s];if(i){n+=a,a==="\\"&&s+1<e.length?(n+=e[s+1],s+=1):a===i&&(i=null);continue}if(a==='"'||a==="'"){i=a,n+=a;continue}if(a==="("?o+=1:a===")"&&o>0&&(o-=1),a===t&&o===0){r.push(n),n="";continue}n+=a}return r.push(n),r}function j4(e){let t="",r=null,n=0;for(;n<e.length;){const i=e[n];if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===r&&(r=null),n+=1;continue}if(i==='"'||i==="'"){r=i,t+=i,n+=1;continue}if(i==="/"&&e[n+1]==="*"){const o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2,t+=" ";continue}t+=i,n+=1}return t}function z4(e,t){return e==="esm"&&t==="on"}var xI=new Set;function B4(e){const t=typeof window>"u"?void 0:window.PIE_REGISTRY,r=e.filter(n=>!t?.[n]?.controller&&!xI.has(n));for(const n of r)xI.add(n);return r}function F4(e){return`${e} is registered without a controller, so this player, which is not hosted, renders its authored model without running model(). Pass the package's ./browser/controller module as controller to registerPreloadedElements, or set hosted when a server processes models.`}function H4(e,t){return t===void 0||!Array.isArray(e?.models)?e:{...e,models:e.models.map(r=>({...r,autoplayAudioEnabled:t}))}}var dv=new WeakMap,RI=new WeakMap,U4=Math.random().toString(36).slice(2,10),PI=0;function q4(){return PI+=1,`pie-item-player-style-scope-${U4}-${PI.toString(36)}`}function W4(e){let t=RI.get(e);return t||(t=new Map,RI.set(e,t)),t}function V4(e,t){let r=dv.get(e);r||(r=new Map,dv.set(e,r));const n=r.get(t);if(n)return n;const i=fetch(t).then(s=>s.text());r.set(t,i);const o=()=>{r.get(t)===i&&(r.delete(t),r.size===0&&dv.delete(e))};return i.then(o,o),i}async function G4({document:e,resolvedUrl:t,scopeClass:r,signal:n,sourceUrl:i}){if(n.aborted)return null;const o=W4(e),s=JSON.stringify([t,r]),a=o.get(s);if(a)return a.refCount+=1,fv(o,s,a);const l=await V4(e,t);if(n.aborted)return null;const c=o.get(s);if(c)return c.refCount+=1,fv(o,s,c);const u=e.createElement("style");u.setAttribute("data-pie-style",i),u.textContent=$4(l,`.pie-item-player.${r}`);const d={element:u,refCount:1};return o.set(s,d),e.head.appendChild(u),fv(o,s,d)}function fv(e,t,r){let n=!1;return()=>{n||(n=!0,r.refCount-=1,!(r.refCount>0||e.get(t)!==r)&&(e.delete(t),r.element.remove()))}}var Y4=(e,t)=>{const r=e.defaultView?.CSS;return typeof r?.escape=="function"?r.escape(t):t.replace(/[^a-zA-Z0-9_-]/g,n=>`\\${n}`)};function K4(e,t,r){const n=Y4(e,t);if(e.querySelector(`link[data-pie-style-link="${n}"]`))return;const i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("href",r),i.setAttribute("data-pie-style-link",t),e.head.appendChild(i)}function dm(e){try{const t=new WeakSet;return JSON.stringify(e,(r,n)=>!n||typeof n!="object"||Array.isArray(n)?n:t.has(n)?"[Circular]":(t.add(n),Object.keys(n).sort().reduce((i,o)=>(i[o]=n[o],i),{})))}catch{return String(e)}}function vu(e){const t=e?.authoring;return!t||t.enabled===!1?null:t}function ls(e){const t=vu(e);return t?JSON.stringify({provider:t.provider??(t.client?"custom":"pie-api"),baseUrl:t.baseUrl??"",contentId:t.contentId??"",collectionId:t.collectionId??"",hasClientLoad:typeof t.client?.load=="function",endpoint:t.endpoints?.load??null}):""}function fm(e,t){return{contentId:t?.contentId??e.contentId,collectionId:t?.collectionId??e.collectionId}}function J0(e){return e.provider==="custom"||!!e.client&&e.provider!=="pie-api"}async function X4(e,t){const r=vu(e);if(!r)throw new Error("Authoring backend is not configured.");if(typeof r.client?.load=="function")return r.client.load({...fm(r),env:t});if(J0(r))throw new Error("backend.authoring.client.load is not configured.");const{callPieApiAuthoringLoad:n}=await Mr(async()=>{const{callPieApiAuthoringLoad:i}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringLoad:i}},[],import.meta.url);return n(r,e.auth,{...fm(r),env:t})}async function J4(e,t){const r=vu(e);if(!r)throw new Error("Authoring backend is not configured.");const n={...fm(r,t),config:t.config,env:t.env,options:t.options};if(typeof r.client?.saveContent=="function")return r.client.saveContent(n);if(J0(r))throw new Error("backend.authoring.client.saveContent is not configured.");const{callPieApiAuthoringSaveContent:i}=await Mr(async()=>{const{callPieApiAuthoringSaveContent:o}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringSaveContent:o}},[],import.meta.url);return i(r,e.auth,n)}async function Q4(e,t){const r=vu(e);if(!r)throw new Error("Authoring backend is not configured.");const n={...fm(r,t),env:t.env,options:t.options};if(typeof r.client?.releaseContent=="function")return r.client.releaseContent(n);if(J0(r))throw new Error("backend.authoring.client.releaseContent is not configured.");const{callPieApiAuthoringReleaseContent:i}=await Mr(async()=>{const{callPieApiAuthoringReleaseContent:o}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringReleaseContent:o}},[],import.meta.url);return i(r,e.auth,n)}var hv=100;function hm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qu(e){return hm(e)&&typeof e.markup=="string"&&hm(e.elements)&&Array.isArray(e.models)}function Z4(e){if(Qu(e.config))return e.config;if(Qu(e.item))return e.item;if(hm(e.item)&&Qu(e.item.config))return e.item.config;if(hm(e.item)&&Qu(e.item.pie))return{pie:e.item.pie,passage:Qu(e.item.passage)?e.item.passage:void 0};throw new Error("Backend delivery load did not return an item config.")}function e8(e){return e.session?e.session:{id:"",data:[]}}function vi(e){const t=e?.delivery;return!t||t.enabled===!1?null:t}function yP(e){return!!vi(e)}function t8(e){return e===!0?{enabled:!0,debounceMs:hv}:e?{enabled:e.enabled!==!1,debounceMs:typeof e.debounceMs=="number"&&e.debounceMs>=0?e.debounceMs:hv}:{enabled:!1,debounceMs:hv}}function Zu(e){const t=vi(e);return t?JSON.stringify({provider:t.provider??(t.client?"custom":"pie-api"),baseUrl:t.baseUrl??"",itemId:t.itemId??"",sessionId:t.sessionId??"",assignmentId:t.assignmentId??"",hasClientLoad:typeof t.client?.load=="function",endpoint:t.endpoints?.load??null}):""}function pv(e,t){const r=vi(e);if(!r)return"";const n=typeof r.client?.model=="function",i=!r.client||r.provider==="pie-api"||!!r.baseUrl||!!r.endpoints?.model;return!n&&!i?"":JSON.stringify({provider:r.provider??(r.client?"custom":"pie-api"),baseUrl:r.baseUrl??"",itemId:r.itemId??"",sessionId:r.sessionId??"",assignmentId:r.assignmentId??"",hasClientModel:typeof r.client?.model=="function",endpoint:r.endpoints?.model??null,options:r.options??null,env:t??null})}async function r8(e,t){const r=vi(e);if(!r)throw new Error("Delivery backend is not configured.");if(!r.itemId)throw new Error("backend.delivery.itemId is required to load from backend.");const n={itemId:r.itemId,sessionId:r.sessionId,assignmentId:r.assignmentId,env:t,requestOptions:r.options};let i;if(typeof r.client?.load=="function")i=await r.client.load(n);else{const{callPieApiDeliveryLoad:o}=await Mr(async()=>{const{callPieApiDeliveryLoad:s}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryLoad:s}},[],import.meta.url);i=await o(r,e.auth,n)}return{config:Z4(i),session:e8(i),metadata:i.metadata}}async function n8(e,t){const r=vi(e);if(!r)throw new Error("Delivery backend is not configured.");if(typeof r.client?.model=="function")return r.client.model({...t,requestOptions:r.options});const{callPieApiDeliveryModel:n}=await Mr(async()=>{const{callPieApiDeliveryModel:i}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryModel:i}},[],import.meta.url);return n(r,e.auth,{...t,requestOptions:r.options})}async function i8(e,t,r){const n=vi(e);if(!n)throw new Error("Delivery backend is not configured.");const i=r?.keepalive===!0,o=i?{...n.options??{},keepalive:!0}:n.options;if(typeof n.client?.saveSession=="function")return n.client.saveSession({...t,requestOptions:o});const{callPieApiDeliverySave:s}=await Mr(async()=>{const{callPieApiDeliverySave:a}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliverySave:a}},[],import.meta.url);return s(n,e.auth,{...t,requestOptions:o},{keepalive:i})}async function o8(e,t,r){const n=vi(e);if(!n)throw new Error("Delivery backend is not configured.");const i={...t,requestOptions:n.options,options:r};if(typeof n.client?.score=="function")return n.client.score(i);const{callPieApiDeliveryScore:o}=await Mr(async()=>{const{callPieApiDeliveryScore:s}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryScore:s}},[],import.meta.url);return o(n,e.auth,i)}function bP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function s8(e){return bP(e)&&typeof e.id=="string"&&typeof e.element=="string"}function a8(e,t){return e.id===t.id&&e.element===t.element}function _I(e,t){if(!e||!t?.length)return{config:e,changed:!1};let r=!1;const n=e.models.map(i=>{const o=t.find(a=>s8(a)&&a8(i,a));if(!o)return i;const s={...o,id:i.id,element:i.element};return JSON.stringify(s)!==JSON.stringify(i)&&(r=!0),s});return{config:r?{...e,models:n}:e,changed:r}}function l8(e){return Array.isArray(e)?{models:e,passageModels:void 0,metadata:void 0}:{models:Array.isArray(e.models)?e.models:void 0,passageModels:Array.isArray(e.passageModels)?e.passageModels:void 0,metadata:bP(e.metadata)?e.metadata:void 0}}function c8(e){const t=l8(e.result),r=_I(e.itemConfig,t.models),n=_I(e.passageConfig,t.passageModels);return{itemConfig:r.config,passageConfig:n.config,metadata:t.metadata,itemChanged:r.changed,passageChanged:n.changed,changed:r.changed||n.changed}}function u8(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}var AI=new WeakMap,d8=0;function Lh(e){if(typeof e!="function")return"none";let t=AI.get(e);return t||(t=d8+=1,AI.set(e,t)),`fn:${t}`}function f8(e){let t=nr(null),r=nr(null),n=nr(0),i=0,o="",s=null,a=Promise.resolve(),l=null,c=0,u="",d=null,f="",h=null,g=0,m=0,v=0;function b(){return g+=1,g}function I(_){return _===g}function C(){return m+=1,m}function x(_){return _===m}function $(){return v+=1,v}function P(_){return _===v}function L(_){const B=e.getSessionContainer();return B.id||!_?B:{...B,id:_}}function J(_){const B=_?.models?.filter(U=>typeof U.id=="string"&&typeof U.element=="string").map(U=>({id:U.id,element:U.element}));return B&&B.length>0?B:void 0}function V(_,B){e.dispatchPlayerEvent(new CustomEvent(_,{detail:B}))}function Y(_,B){V("backend-error",{scope:"delivery",operation:_,message:B instanceof Error?B.message:String(B),error:B})}function Pe(){return vu(e.getBackend())?.media??null}function M(_=ls(e.getBackend())){return h&&f===_?{contentId:h}:{}}async function H(_,B){if(_==="authoring"){const _e=e.getBackend();if(!_e||!vu(_e))throw new Error("backend.authoring is not configured.");const Ue=C(),it=await X4(_e,e.getEnv());if(!x(Ue)||B&&ls(e.getBackend())!==B)return;const le=ls(e.getBackend());He(t,it.config,!0),d="authoring",He(r,{id:"",data:[]},!0),He(n,R(n)+1);const de=await e.loadPlayerConfig(it.config);if(await Jd(),!x(Ue)||B&&ls(e.getBackend())!==B)return;if(!de)throw new Error("Authoring backend config failed to load.");f=le,h=typeof it.contentId=="string"?it.contentId:null,V("backend-load-complete",{scope:"authoring",operation:"load",contentId:it.contentId,metadata:it.metadata??{},config:it.config});return}const U=e.getBackend();if(!U||!yP(U))throw new Error("backend.delivery is not configured.");const fe=e.getEnv(),W=pv(U,fe),se=await r8(U,fe);B&&Zu(e.getBackend())!==B||d!=="authoring"&&(He(t,se.config,!0),d="delivery",He(r,se.session,!0),He(n,R(n)+1),u=W,V("backend-load-complete",{scope:"delivery",operation:"load",metadata:se.metadata??{},session:se.session}))}async function ne(_,B,U){const fe=e.getBackend();if(!fe||!vi(fe)||!e.getItemConfig()||d==="authoring")return;const W=vi(fe),se=e.getEnv(),_e=L(W.sessionId),Ue=dm(_e);let it;try{it=await n8(fe,{itemId:W.itemId,sessionId:W.sessionId,assignmentId:W.assignmentId,session:_e,env:se,models:J(e.getItemConfig()),passageModels:J(e.getPassageConfig())})}catch(de){if(!I(U))return;throw de}if(!I(U)||_&&pv(e.getBackend(),e.getEnv())!==_||B!==c||dm(L(W.sessionId))!==Ue)return;const le=c8({itemConfig:e.getItemConfig(),passageConfig:e.getPassageConfig(),result:it});u=_,le.changed&&(c+=1,await e.applyRefreshedConfigs(le)),V("backend-model-complete",{scope:"delivery",operation:"model",metadata:le.metadata??{}})}async function ae(_,B){const U=e.getBackend();if(!U||!vi(U))throw new Error("backend.delivery is not configured.");const fe=vi(U),W=B??{itemId:fe.itemId,sessionId:fe.sessionId,assignmentId:fe.assignmentId},se=W.session??L(W.sessionId);await i8(U,{itemId:W.itemId,sessionId:W.sessionId,assignmentId:W.assignmentId,session:se,env:e.getEnv()},_),V("backend-session-saved",{scope:"delivery",operation:"saveSession",sessionId:se.id,session:se})}async function ye(_,B){const U=a.catch(()=>{}).then(()=>ae(_,B));return a=U,U}function te(_){if(!s)return;clearTimeout(s),s=null;const B=l;l=null,ye(_,B?{...B,session:L(B.sessionId)}:null).catch(U=>{Y("saveSession",U)})}async function z(_){const B=e.getBackend();if(!B||!vi(B))throw new Error("backend.delivery is not configured.");const U=vi(B),fe=L(U.sessionId),W=await o8(B,{itemId:U.itemId,sessionId:U.sessionId,assignmentId:U.assignmentId,session:fe,env:e.getEnv()},_);return V("backend-score-complete",{scope:"delivery",operation:"score",sessionId:fe.id,score:W}),W}async function A(_){const B=e.getItemConfig();if(!B)throw new Error("Cannot save content before the item config has loaded.");const U=e.getBackend()??{},fe=ls(U),W=$(),se=await J4(U,{...M(fe),config:u8(B),env:e.getEnv(),options:_});return typeof se.contentId=="string"&&P(W)&&fe===ls(e.getBackend())&&(h=se.contentId,f=fe),V("backend-content-saved",{scope:"authoring",operation:"saveContent",contentId:se.contentId}),se.contentId}async function K(_){const B=e.getBackend()??{},U=ls(B),fe=$(),W=await Q4(B,{...M(U),env:e.getEnv(),options:_});return typeof W.contentId=="string"&&P(fe)&&U===ls(e.getBackend())&&(h=W.contentId,f=U),V("backend-content-released",{scope:"authoring",operation:"releaseContent",contentId:W.contentId}),W.contentId}function Q(){const _=e.getBackend();if(!_)return;const B=vi(_);if(!B)return;const U=t8(B.autosave);if(!U.enabled)return;s&&clearTimeout(s);const fe=Zu(_),W={itemId:B.itemId,sessionId:B.sessionId,assignmentId:B.assignmentId};l=W,s=setTimeout(()=>{s=null,l=null,fe===Zu(e.getBackend())&&ye(void 0,W).catch(se=>{Y("saveSession",se)})},U.debounceMs)}return Vr(()=>{const _=Zu(e.getBackend());if(!_){queueMicrotask(()=>{zn(()=>{s&&(clearTimeout(s),s=null),o="",d!=="authoring"&&(He(t,null),d=null,He(r,null))})});return}_!==o&&(te(),o=_,queueMicrotask(()=>{zn(()=>{H("delivery",_).catch(B=>{Y("load",B)})})}))}),Vr(()=>{const _=ls(e.getBackend());(!_||f&&f!==_)&&queueMicrotask(()=>{zn(()=>{f="",h=null,d==="authoring"&&!_&&(He(t,null),d=null,He(r,null))})})}),Vr(()=>{const _=e.getBackend(),B=e.getEnv(),U=e.getItemConfig(),fe=pv(_,B);if(!fe||!U){u="",b();return}if(fe===u){b();return}const W=c,se=b();queueMicrotask(()=>{zn(()=>{ne(fe,W,se).catch(_e=>{Y("model",_e)})})})}),Vr(()=>()=>{te()}),{get configOverride(){return R(t)},get sessionOverride(){return R(r)},get authoringMedia(){return Pe()},hasPendingSessionReplacement(){return R(n)!==i},markSessionReplacementApplied(){i=R(n)},noteConfigChanged(){c+=1},load(_="delivery"){return H(_,_==="authoring"?ls(e.getBackend()):Zu(e.getBackend()))},saveSession:ye,flushPendingSave:te,score:z,saveContent:A,releaseContent:K,scheduleAutosave:Q}}var $I={error:"player-error"};function Q0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.providerId=="string"&&typeof t.providerName=="string"&&typeof t.initialize=="function"&&typeof t.trackError=="function"&&typeof t.trackEvent=="function"&&typeof t.destroy=="function"&&typeof t.isReady=="function"}var wP={retryDelayMs:3e3,timeoutMs:12e4},pm={trackPageActions:!1,instrumentationProvider:void 0,maxResourceRetries:3,resourceRetryDelay:500,iifeBundleRetry:wP},h8=["script","iframe","object","embed","base","form","meta","link","style","foreignobject"],p8=["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onfocus","onblur","onkeydown","onkeyup","onkeypress","onsubmit","onchange","onbeforeunload","formaction","xlink:href"],SP=/(?:^|[^\w-])(?:url|image-set|-webkit-image-set|src)\s*\(/i,m8=/url\s*\(|image-set\s*\(|src\s*\(|position|\\/i;function IP(e,t){return SP.test(t)?!0:e.toLowerCase()==="position"&&/\bfixed\b/i.test(t)}function g8(e,t){const r=t.createElement("span");r.setAttribute("style",e);const n=r.style,i=[];for(let o=0;o<n.length;o+=1){const s=n.item(o);if(!s)continue;const a=n.getPropertyValue(s);if(IP(s,a))continue;const l=n.getPropertyPriority(s);i.push(`${s}: ${a}${l?` !${l}`:""}`)}return i.join("; ")}function v8(e,t){if(typeof e!="string"||e.length===0)return"";if(!t||!m8.test(e))return e;const r=t.createElement("span");r.setAttribute("style",e);const n=r.style;let i=!1;for(let o=0;o<n.length;o+=1){const s=n.item(o);if(s&&IP(s,n.getPropertyValue(s))){i=!0;break}}return!i&&!SP.test(e)?e:g8(e,t)}function y8(e){typeof e.addHook=="function"&&e.addHook("afterSanitizeAttributes",t=>{const r=t;if(!r||typeof r.getAttribute!="function")return;const n=r.getAttribute("style");if(!n)return;const i=v8(n,r.ownerDocument);i!==n&&(i?r.setAttribute("style",i):r.removeAttribute("style"))})}var b8=/^pie-/i,w8='[contenteditable]:not([contenteditable="false" i])';function S8(e,t){let r=e.parentElement;for(;r&&r!==t;){if(b8.test(r.tagName))return!0;r=r.parentElement}return!1}var mv=new WeakSet;function Z0(e,t,r={}){const{skipPieDescendants:n=!1}=r,i=Array.from(e.querySelectorAll(t.selector));if(i.length===0)return 0;const o=e.ownerDocument;if(!o)return 0;const s=!!t.layoutClass&&!!o.defaultView&&e.isConnected,a=[],l=[];for(const g of i){const m=g.parentElement;if(!m)continue;const v=m.classList?.contains(t.wrapperClass);v&&(!s||mv.has(m))||n&&S8(g,e)||g.closest(w8)||(v?l.some(b=>b.parentElement===m)||l.push(g):a.push(g))}const c=l.map(g=>g.parentElement),u=c.map(g=>g.className);for(const g of c)g.className="";const d=a.map(g=>t.layoutClass?.(g)??null),f=l.map(g=>t.layoutClass?.(g)??null);for(const[g,m]of c.entries()){m.className=u[g];const v=f[g];v&&m.classList.add(v),mv.add(m)}let h=0;for(const[g,m]of a.entries()){const v=m.parentElement;if(!v)continue;const b=o.createElement(t.wrapperTag),I=d[g];b.className=I?`${t.wrapperClass} ${I}`:t.wrapperClass,b.setAttribute("tabindex","0"),b.setAttribute("role","region"),b.setAttribute("aria-label",t.buildAriaLabel(m)),s&&mv.add(b),v.insertBefore(b,m),b.appendChild(m),h+=1}return h}function kP(e,t){if(!e)return"";if(!t.markupProbe.test(e)||typeof window>"u"||!window.document)return e;const r=typeof DOMParser<"u"?DOMParser:window.DOMParser;if(!r)return e;const n=new r().parseFromString(`<!DOCTYPE html><html><body>${e}</body></html>`,"text/html").body;return n&&Z0(n,t,{skipPieDescendants:!0})>0?n.innerHTML:e}function TP(e){return e.nodeType===1}function I8(e,t){if(!TP(e)||!e.classList?.contains(t.wrapperClass))return!1;for(const r of Array.from(e.children))if(!r.matches(t.selector))return!1;return!0}function k8(e,t){return!TP(e)||!e.parentElement?.classList?.contains(t.wrapperClass)?!1:e.matches(t.selector)}function MI(e,t){for(const r of Array.from(e))if(!I8(r,t)&&!k8(r,t))return!1;return!0}function EP(e,t){return e.type!=="childList"?!1:MI(e.addedNodes,t)&&MI(e.removedNodes,t)}function T8(e){const t=e.getAttribute("alt"),r=t?t.trim():"";return r?`Scrollable image: ${r}`:"Scrollable image"}function E8(e){const t=e.ownerDocument?.defaultView,r=t?t.getComputedStyle(e).display:e.style?.display;return r&&!r.startsWith("inline")&&r!=="none"&&r!=="contents"?"pie-image-scroll-block":null}var ew={selector:"img",wrapperTag:"span",wrapperClass:"pie-image-scroll",markupProbe:/<img\b/i,buildAriaLabel:T8,layoutClass:E8};function C8(e,t={}){return Z0(e,ew,t)}function x8(e){return kP(e,ew)}function R8(e){return EP(e,ew)}function P8(e){const t=e.getAttribute("aria-label");if(t?.trim())return`Scrollable table: ${t.trim()}`;const r=e.getAttribute("aria-labelledby");if(r?.trim()){const i=e.ownerDocument,o=r.trim().split(/\s+/),s=[];for(const a of o){const l=i?.getElementById(a)?.textContent?.trim();l&&s.push(l)}if(s.length>0)return`Scrollable table: ${s.join(" ")}`}const n=e.querySelector("caption")?.textContent?.trim();return n?`Scrollable table: ${n}`:"Scrollable table"}var tw={selector:"table",wrapperTag:"div",wrapperClass:"pie-table-scroll",markupProbe:/<table\b/i,buildAriaLabel:P8};function _8(e,t={}){return Z0(e,tw,t)}function A8(e){return kP(e,tw)}function $8(e){return EP(e,tw)}var M8=["slot","role","tabindex","id","class","style","href","src","alt","title","hidden","disabled","lang","dir"],O8=new Set(["mstack","mlongdiv","msgroup","msrow","msline","mscarries","mscarry","semantics","annotation","mprescripts","none"]),L8=["stackalign","charalign","charspacing","longdivstyle","position","shift","location","crossout","leftoverhang","rightoverhang","mslinethickness","linebreak"],N8=/^[a-z_][\w.-]*:[a-z][\w.-]*$/,D8=["pie-id"],j8=h8,z8=p8,B8=/^pie-[a-z0-9-]+$/i,F8=/^(id|class|style|slot|role|tabindex|hidden|disabled|lang|dir|data-[\w-]+|aria-[\w-]+|pie-[\w-]+|model-[\w-]+|session-[\w-]+|config-[\w-]+|context-[\w-]+)$/i,kc=null;function H8(){if(kc)return kc;if(typeof window>"u"||!window.document)return null;const e=aI;return kc=typeof e=="function"?e(window):aI,y8(kc),kc.addHook?.("afterSanitizeAttributes",t=>Hz(t)),kc}function U8(e,t={}){if(!e)return"";const r=H8();if(!r)return"";const n=(t.allowedCustomElements??[]).map(a=>a.toLowerCase()),i=new Set(n),o=r.sanitize(e,{ADD_TAGS:a=>i.has(a)||O8.has(a)||N8.test(a),ADD_ATTR:[...M8,...L8],ADD_URI_SAFE_ATTR:D8,FORBID_TAGS:j8,FORBID_ATTR:z8,ALLOW_UNKNOWN_PROTOCOLS:!1,SANITIZE_DOM:!0,SANITIZE_NAMED_PROPS:!1,WHOLE_DOCUMENT:!1,ALLOW_DATA_ATTR:!0,ALLOW_ARIA_ATTR:!0,CUSTOM_ELEMENT_HANDLING:{tagNameCheck:a=>{const l=a.toLowerCase();return B8.test(l)||i.has(l)},attributeNameCheck:a=>F8.test(a),allowCustomizedBuiltInElements:!1},RETURN_TRUSTED_TYPE:!1}),s=typeof o=="string"?o:String(o??"");return t.wrapOverwideContent===!1?s:A8(x8(s))}function q8(e={}){const{allowedCustomElements:t,wrapOverwideContent:r}=e;return n=>U8(n,{allowedCustomElements:t,wrapOverwideContent:r})}function OI(e){const t=new Set;for(const r of e){if(!r)continue;const n=r.toLowerCase();t.add(n),t.add(`${n}-config`)}return[...t]}var W8="-pie-editor--";Ee(class CP extends CustomEvent{constructor(t,r=!1){super(CP.TYPE,{bubbles:!0,detail:{update:t,reset:r}}),Ee(this,"update",void 0),Ee(this,"reset",void 0),this.update=t,this.reset=r}},"TYPE","model.updated");var Gy=class xP extends CustomEvent{constructor(t,r){super(xP.TYPE,{bubbles:!0,detail:{src:t,done:r}}),Ee(this,"src",void 0),Ee(this,"done",void 0),this.src=t,this.done=r}};Ee(Gy,"TYPE","delete.image");var Yy=class RP extends CustomEvent{constructor(t){super(RP.TYPE,{bubbles:!0,detail:t}),Ee(this,"handler",void 0),this.handler=t}};Ee(Yy,"TYPE","insert.image");var Ky=class PP extends CustomEvent{constructor(t,r){super(PP.TYPE,{bubbles:!0,detail:{src:t,done:r}}),Ee(this,"src",void 0),Ee(this,"done",void 0),this.src=t,this.done=r}};Ee(Ky,"TYPE","delete.sound");var Xy=class _P extends CustomEvent{constructor(t){super(_P.TYPE,{bubbles:!0,detail:t}),Ee(this,"handler",void 0),this.handler=t}};Ee(Xy,"TYPE","insert.sound");function Xi(e,t){const r=`[${e}]`;return{debug:(n,...i)=>{t()&&console.debug(r,n,...i)},info:(n,...i)=>console.info(r,n,...i),warn:(n,...i)=>console.warn(r,n,...i),error:(n,...i)=>console.error(r,n,...i)}}function ki(){return typeof window<"u"&&window.PIE_DEBUG===!0}var Yr=Xi("asset-handler",()=>ki()),AP=class{constructor(e){Ee(this,"onComplete",void 0),Ee(this,"cancelled",!1),Ee(this,"fileReader",null),this.onComplete=e}cancel(){this.cancelled=!0,this.fileReader&&this.fileReader.abort(),Yr.debug("[DataURLAssetHandler] Upload cancelled")}done(e,t){if(!this.cancelled){if(e){Yr.error("[DataURLAssetHandler] Error during upload:",e);return}t&&(Yr.debug("[DataURLAssetHandler] Upload complete, src:",t.substring(0,50)+"..."),this.onComplete(t))}}fileChosen(e){this.cancelled||(Yr.debug("[DataURLAssetHandler] File chosen:",e.name,e.type,e.size),this.fileReader=new FileReader,this.fileReader.onload=t=>{const r=t.target?.result;Yr.debug("[DataURLAssetHandler] File converted to data URL"),this.done(void 0,r)},this.fileReader.onerror=()=>{Yr.error("[DataURLAssetHandler] FileReader error"),this.done(new Error("Failed to read file"))},this.fileReader.onprogress=t=>{if(t.lengthComputable){const r=t.loaded/t.total*100;this.progress(r,t.loaded,t.total)}},this.fileReader.readAsDataURL(e))}progress(e,t,r){Yr.debug(`[DataURLAssetHandler] Progress: ${e.toFixed(1)}% (${t}/${r} bytes)`)}};function eu(e,t){return e instanceof Error?e:new Error(String(e??t))}function $P(e,t){let r=!1;const n=e.done,i=e.cancel,o=(a,l)=>{if(!r){if(r=!0,a){try{i?.()}catch(c){Yr.error("[asset-handler] cancel callback failed:",c)}t.cancel()}try{n?.(a,l)}catch(c){Yr.error("[asset-handler] done callback failed:",c)}}},s=()=>{if(!r){r=!0;try{i?.()}catch(a){Yr.error("[asset-handler] cancel callback failed:",a)}t.cancel()}};return e.done=o,e.cancel=s,{done:o,cancel:s,isSettled:()=>r}}function MP(e,t){return new Promise(r=>{const n=document.createElement("input");n.type="file",n.accept=e;let i=!1,o=!1,s=!1;const a=()=>{n.onchange=null,window.removeEventListener("focus",c),n.removeEventListener("cancel",u)},l=d=>{i||(i=!0,a(),r(d))},c=()=>{!s||o||(s=!1,window.setTimeout(()=>{if(o||i)return;const d=n.files?.[0]??null;d||t(),l(d)},300))},u=()=>{t(),l(null)};n.onchange=()=>{o=!0,s=!1,l(n.files?.[0]??null)},n.addEventListener("cancel",u),window.addEventListener("focus",c),s=!0,n.click()})}function OP(e){if(!e.isPasted||typeof e.getChosenFile!="function")return null;try{return e.getChosenFile()??null}catch(t){return Yr.error("[asset-handler] Failed to read pasted file",t),null}}var V8=class{constructor(e,t,r,n,i){Ee(this,"element",void 0),Ee(this,"onInsertImage",void 0),Ee(this,"onDeleteImage",void 0),Ee(this,"onInsertSound",void 0),Ee(this,"onDeleteSound",void 0),Ee(this,"listeners",[]),this.element=e,this.onInsertImage=t,this.onDeleteImage=r,this.onInsertSound=n,this.onDeleteSound=i}attach(){if(Yr.debug("[AssetEventManager] Attaching event listeners"),this.onInsertImage){const e=t=>{const r=t;Yr.debug("[AssetEventManager] InsertImageEvent received"),this.onInsertImage(r.detail)};this.element.addEventListener(Yy.TYPE,e),this.listeners.push({type:Yy.TYPE,handler:e})}if(this.onDeleteImage){const e=t=>{const r=t;Yr.debug("[AssetEventManager] DeleteImageEvent received, src:",r.detail.src),this.onDeleteImage(r.detail.src,r.detail.done)};this.element.addEventListener(Gy.TYPE,e),this.listeners.push({type:Gy.TYPE,handler:e})}if(this.onInsertSound){const e=t=>{const r=t;Yr.debug("[AssetEventManager] InsertSoundEvent received"),this.onInsertSound(r.detail)};this.element.addEventListener(Xy.TYPE,e),this.listeners.push({type:Xy.TYPE,handler:e})}if(this.onDeleteSound){const e=t=>{const r=t;Yr.debug("[AssetEventManager] DeleteSoundEvent received, src:",r.detail.src),this.onDeleteSound(r.detail.src,r.detail.done)};this.element.addEventListener(Ky.TYPE,e),this.listeners.push({type:Ky.TYPE,handler:e})}Yr.debug("[AssetEventManager] Attached",this.listeners.length,"event listeners")}detach(){Yr.debug("[AssetEventManager] Detaching event listeners"),this.listeners.forEach(({type:e,handler:t})=>{this.element.removeEventListener(e,t)}),this.listeners=[],Yr.debug("[AssetEventManager] All event listeners detached")}};function G8(e){return t=>{Yr.debug("[createDefaultImageInsertHandler] Creating DataURL handler");let r=null;const n=new AP(a=>{e(a),r?.done(void 0,a)});r=$P(t,n);const i=()=>{r?.done(new Error("Image selection cancelled"))},o=a=>{if(!a){i();return}try{t.fileChosen(a)}catch(l){Yr.error("[createDefaultImageInsertHandler] fileChosen failed",l),r?.done(eu(l,"Image fileChosen failed"));return}try{n.fileChosen(a)}catch(l){r?.done(eu(l,"Image upload failed"))}},s=OP(t);if(s){o(s);return}if(t.isPasted){r?.done(new Error("Pasted image is unavailable"));return}MP("image/*",i).then(a=>{r?.isSettled()||o(a)}).catch(a=>{r?.done(eu(a,"Image selection failed"))})}}function Y8(e){return t=>{Yr.debug("[createDefaultSoundInsertHandler] Creating DataURL handler");let r=null;const n=new AP(l=>{e(l),r?.done(void 0,l)}),i=t;r=$P(i,n);const o=()=>{r?.done(new Error("Sound selection cancelled"))},s=l=>{if(!l){o();return}const c=i.fileChosen;if(typeof c=="function")try{c(l)}catch(u){Yr.error("[createDefaultSoundInsertHandler] fileChosen failed",u),r?.done(eu(u,"Sound fileChosen failed"));return}try{n.fileChosen(l)}catch(u){r?.done(eu(u,"Sound upload failed"))}},a=OP(i);if(a){s(a);return}if(i.isPasted){r?.done(new Error("Pasted sound is unavailable"));return}MP("audio/*",o).then(l=>{r?.isSettled()||s(l)}).catch(l=>{r?.done(eu(l,"Sound selection failed"))})}}function K8(){return(e,t)=>{Yr.debug("[createDefaultImageDeleteHandler] Delete requested for:",e.substring(0,50)),t()}}function X8(){return(e,t)=>{Yr.debug("[createDefaultSoundDeleteHandler] Delete requested for:",e.substring(0,50)),t()}}var sc=(function(e){return e.player="player.js",e.clientPlayer="client-player.js",e.editor="editor.js",e.esm="esm",e})({}),Jy=(function(e){return e.loading="loading",e.loaded="loaded",e})({}),LP={invokeControllerForModel:!0,env:{mode:"gather",role:"student",partialScoring:!1},eventListeners:{}};function J8(e){return e&&typeof e.pie=="object"}function LI(e){return typeof e=="function"&&"prototype"in e&&e.prototype instanceof HTMLElement}function Q8(e){return e&&typeof e.PIE_REGISTRY=="object"}var Du=()=>{let e;return Q8(window)?e=window.PIE_REGISTRY:(e={},window.PIE_REGISTRY=e),e};function NI(e){const t=Du(),r=t[e.tagName];if(!r||r.status!==Jy.loaded||!Z8(e.tagName))return t[e.tagName]=e,e;const n=!r.controller&&!!e.controller,i=r.config==null&&e.config!=null;if(!n&&!i)return r;const o={...r};return n&&(o.controller=e.controller,o.bundleType=e.bundleType),i&&(o.config=e.config),t[e.tagName]=o,o}function Z8(e){return typeof customElements<"u"&&customElements.get(e)!==void 0}var NP=e=>{if(!e)throw new Error("Parameter is required: input");const t=e.charAt(0)==="@"?e.match(/^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/):e.match(/^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/);if(!t)throw new Error(`[parse-package-name] "${e}" is not a valid string`);return{name:t[1],path:t[2]||"",version:t[3]||""}},eF=e=>e.split("+").map(t=>NP(t).name).join("+"),DP=(e,t,r)=>{if(!e)throw new Error("session data is required");const n=e.find(o=>o.id===t);if(n)return r&&!n.element&&(n.element=r),n;const i=r?{id:t,element:r}:{id:t};return e.push(i),i},Fs=Xi("pie-scoring",()=>ki()),Zm=(e,t)=>{if(t===sc.player){Fs.debug(`[findPieController] ℹ️ ${e} delivered as player.js; using server-processed models`);return}const r=Du();Fs.debug(`[findPieController] Looking for controller for: ${e}`),Fs.debug("[findPieController] Registry has entries for:",Object.keys(r));const n=r[e];if(!n){Fs.error(`[findPieController] ❌ No registry entry found for element: ${e}`),Fs.error("[findPieController] Available element names:",Object.keys(r)),Fs.error("[findPieController] Full registry:",r);return}Fs.debug(`[findPieController] Found registry entry for ${e}:`,{package:n.package,tagName:n.tagName,hasController:!!n.controller,controllerKeys:n.controller?Object.keys(n.controller):[],bundleType:n.bundleType});const i=n.controller??void 0;return i?Fs.debug(`[findPieController] ✅ Controller found for ${e} with functions:`,Object.keys(i)):Fs.debug(`[findPieController] ℹ️ No controller for ${e}; its model is used as given`),i},Hs=Xi("authoring",()=>ki());function tu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tF(e){try{return NP(e).name}catch{return e}}function rF(e){return e.split("/").pop()||e}function DI(e,t){if(tu(e)){for(const r of t)if(Object.hasOwn(e,r))return e[r]}}function nF(e,t){return t===void 0?e??{}:tu(e)&&tu(t)?{...e,...t}:t}function jP(e,t,r){const n=tF(r),i=rF(n);return nF(DI(e,[r,n,t]),DI(e?.authoring,[t,r,n,i]))}function zP(e,t){const r=t.id;if(r)return e.find(n=>n.id===r)}function BP(e,t){return Array.from(e.querySelectorAll(t))}function iF(e,t={},r){const n=r.container??document,i=[];if(Hs.debug("[initializeAuthoringConfigures] Starting initialization"),Hs.debug("[initializeAuthoringConfigures] Config:",e),Hs.debug("[initializeAuthoringConfigures] Configuration:",t),Hs.debug("[initializeAuthoringConfigures] Env:",r.env),!e?.elements||!e?.models)return Hs.warn("[initializeAuthoringConfigures] Invalid config - missing elements or models"),i;for(const[o,s]of Object.entries(e.elements)){const a=`${o}-config`,l=BP(n,a);Hs.debug(`[initializeAuthoringConfigures] Found ${l.length} ${a} elements`);for(const c of l){const u=zP(e.models,c);if(!u){Hs.warn(`[initializeAuthoringConfigures] No model found for ${a}#${c.id||"(missing-id)"}`);continue}const d=c,f=jP(t,o,String(s));d.model=u,d.configuration=f,i.push({id:u.id,element:u.element,configureTag:a,configuration:f}),Hs.debug(`[initializeAuthoringConfigures] Model and configuration set for ${a}#${u.id}`,f)}}return Hs.debug("[initializeAuthoringConfigures] Initialization complete"),i}function oF(e){return Zm(e.localName)}function sF(e){return tu(e)?tu(e.partA)&&tu(e.partB)?Object.keys(e.partA).length>0||Object.keys(e.partB).length>0:Object.keys(e).length>0:!1}async function jI(e,t={},r={}){const n=r.container??document,i=[];if(!e?.elements||!e?.models)return{hasErrors:!1,validatedModels:i};for(const[o,s]of Object.entries(e.elements)){const a=BP(n,`${o}-config`);for(const l of a){const c=zP(e.models,l);if(!c)continue;const u=oF(l),d=jP(t,o,String(s));if(typeof u?.validate!="function"){i.push(c);continue}const f=await u.validate(c,d),h={...c,errors:f};i.push(h);const g=l;JSON.stringify(g.model?.errors)!==JSON.stringify(f)&&(g.model=h)}}return{hasErrors:i.some(o=>sF(o.errors)),validatedModels:i}}function Nh(e){return e instanceof Error?e:new Error(String(e??"Unknown authoring error"))}function aF(e,t,r){return new V8(e,t.onInsertImage?n=>{try{t.onInsertImage?.(n)}catch(i){const o=Nh(i);r("onInsertImage",o),n.done(o)}}:void 0,t.onDeleteImage?(n,i)=>{try{t.onDeleteImage?.(n,i)}catch(o){const s=Nh(o);r("onDeleteImage",s),i(s)}}:void 0,t.onInsertSound?n=>{try{t.onInsertSound?.(n)}catch(i){const o=Nh(i);r("onInsertSound",o),n.done(o)}}:void 0,t.onDeleteSound?(n,i)=>{try{t.onDeleteSound?.(n,i)}catch(o){const s=Nh(o);r("onDeleteSound",s),i(s)}}:void 0)}var lF=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function zI(e,t){return Object.keys(t).reduce((r,n)=>{const i=new RegExp(`(<\\/?)${lF(n)}(?=[\\t\\n\\f\\r />])`,"g");return r.replace(i,(o,s)=>`${s}${n}-config`)},e)}var gv=Xi("configure-init",()=>ki());function BI(e,t,r){if(gv.debug("[initializeConfiguresFromLoadedBundle] Starting initialization"),!e?.elements||!e?.models)return gv.warn("[initializeConfiguresFromLoadedBundle] Invalid config - missing elements or models"),[];Du();const n=iF(e,t,r);return gv.debug("[initializeConfiguresFromLoadedBundle] Initialization complete"),n}function Qy(e){try{const t=new WeakSet;return JSON.stringify(e,(r,n)=>{if(!n||typeof n!="object"||Array.isArray(n))return n;if(t.has(n))return"[Circular]";t.add(n);const i=n,o={};for(const s of Object.keys(i).sort())o[s]=i[s];return o})??"undefined"}catch{return null}}function cF(){const e=new WeakMap;return({element:t,complete:r,session:n,commit:i})=>{if(!t||typeof t!="object")return!0;const o=Qy({complete:r,session:n});return o===null?!0:!i&&e.get(t)===o?!1:(e.set(t,o),!0)}}function uF(e,t){return e===void 0||e===t?!1:Qy(e)!==Qy(t)}var il=Xi("pie-initialize-element",()=>ki()),FP=(e,t)=>{const{config:r,session:n,env:i,eventListeners:o,bundleType:s}=t;if(e.__pieInitialized)return!0;const a=e.tagName.toLowerCase();il.debug(`[initializePieElement] Initializing ${a}#${e.id}`);const l=r?.models?.find(d=>d.id===e.id);if(!l){const d=Du()[a];return d&&d.bundleType===sc.clientPlayer&&il.warn(`[initializePieElement] Model not found for PIE element ${a}#${e.id} (client-player.js bundle)`),!1}const c=DP(n,l.id,l.element);e.session=c,e.__pieInitialized=!0,il.debug(`[initializePieElement] Session set for ${a}#${e.id}:`,c);const u=Zm(a,s);if(!i)throw il.error(`[initializePieElement] ❌ FATAL: No env provided for ${a}`),new Error(`No env provided for ${a}. PIE elements require an env object with mode and role.`);return u?il.debug(`[initializePieElement] Controller found for ${a}, will invoke model() function`):(il.debug(`[initializePieElement] ℹ️ No controller for ${a}, using server-processed model`),il.debug("[initializePieElement] Model already processed by server:",{id:l.id,element:l.element,hasCorrectResponse:"correctResponse"in l,mode:i.mode,role:i.role}),e.model=l),o&&Object.entries(o).forEach(([d,f])=>{e.addEventListener(d,f)}),!0},ip=Xi("pie-element-observer",()=>ki()),vv=new Map,dF=e=>{const t=[];for(const r of e)try{t.push(r())}catch(n){ip.error("[pieElementObserver] A context source threw; skipping it.",n)}return t},FI=(e,t)=>{const r=e.tagName.toLowerCase();if(Du()[r]){for(const n of t)if(FP(e,{config:n.config,session:n.session,env:n.env,eventListeners:n.eventListeners?.[r],bundleType:n.bundleType}))return}},fF=(e,t)=>{const r=dF(e);if(r.length!==0){for(const n of t)if(n.type==="childList")for(const i of n.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;const o=i;FI(o,r);for(const s of Array.from(o.querySelectorAll("*")))FI(s,r)}}},HI=(e,t)=>{if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const r=e??document.body;if(!r)return()=>{};let n=vv.get(r);if(!n){const a=new Set,l=new MutationObserver(c=>fF(a,c));l.observe(r,{childList:!0,subtree:!0}),n={sources:a,observer:l},vv.set(r,n),ip.debug("[observePieElements] Observing a new container")}const{sources:i,observer:o}=n;i.add(t),ip.debug(`[observePieElements] Container now has ${i.size} registration(s)`);let s=!1;return()=>{s||(s=!0,i.delete(t),!(i.size>0)&&(o.disconnect(),vv.delete(r),ip.debug("[observePieElements] Released the last registration, disconnected")))}};function UI(e){return e.firstElementChild||e.shadowRoot?.firstChild?!0:!!e.textContent?.trim()}function hF(e){return e.localName.includes("-")&&customElements.get(e.localName)!==void 0}function pF(e){if(!e.isConnected)return!0;if(!UI(e))return!1;for(const t of e.querySelectorAll("*"))if(hF(t)&&!UI(t))return!1;return!0}function mF(e,t){const r=[];for(const n of t){const i=new Set((n.models??[]).map(o=>o?.id));for(const o of Object.keys(n.elements??{}))if(customElements.get(o))for(const s of e.querySelectorAll(o))i.has(s.id)&&r.push(s)}return r}function gF(e,t,r,n=200){const i=mF(e,t),o=()=>i.every(pF);return r.aborted||o()||typeof MutationObserver>"u"?Promise.resolve():new Promise(s=>{let a;const l=new MutationObserver(()=>{if(o()){u();return}c()});function c(){clearTimeout(a),a=setTimeout(u,n)}function u(){clearTimeout(a),l.disconnect(),r.removeEventListener("abort",u),s()}l.observe(e,{childList:!0,subtree:!0,characterData:!0}),r.addEventListener("abort",u),c()})}var vF=e=>e.mode!=="evaluate",yF=e=>({...e,role:"instructor"});function bF(e){try{const t={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1}[e];if(typeof t=="string"&&t.length>0)return t}catch{}}var wF=typeof window<"u"&&window.PIE_BUILDER_BUNDLE_URL||bF("PUBLIC_BUILDER_BUNDLE_URL")||"https://proxy.pie-api.com/bundles/",rw=(...e)=>e.reduce((t,r)=>{for(const n in r)Object.hasOwn(r,n)&&r[n]!==null&&r[n]!==void 0&&(t[n]=r[n]);return t},{}),SF="@pie-lib/math-rendering";Xi("math-rendering",()=>ki());var IF=()=>typeof window>"u"?null:window[SF]||null,kF=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]),TF=/^[a-z][a-z0-9._-]*-[a-z0-9._-]*$/,nw=(e,t="custom element tag")=>{if(!e||typeof e!="string")throw new Error(`Invalid ${t}: expected a non-empty string`);const r=e.trim();if(!r)throw new Error(`Invalid ${t}: tag is empty`);if(r!==r.toLowerCase())throw new Error(`Invalid ${t} "${r}": custom element names must be lowercase`);if(!r.includes("-"))throw new Error(`Invalid ${t} "${r}": custom element names must include a hyphen`);if(kF.has(r))throw new Error(`Invalid ${t} "${r}": this name is reserved by the HTML spec`);if(!TF.test(r))throw new Error(`Invalid ${t} "${r}": allowed characters are lowercase letters, numbers, ".", "_" and "-"`);return r},EF=e=>typeof DOMException<"u"&&e instanceof DOMException?e.name==="NotSupportedError"||e.code===DOMException.NOT_SUPPORTED_ERR:(typeof e=="object"&&e!==null&&"name"in e?String(e.name):"")==="NotSupportedError",CF=(e,t,r="custom element tag",n={})=>{const i=nw(e,r);if(customElements.get(i))return{outcome:"already-defined",tagName:i};try{return customElements.define(i,t),{outcome:"defined",tagName:i}}catch(o){if(!EF(o))return{outcome:"error",tagName:i,error:o};if(customElements.get(i))return{outcome:"already-defined",tagName:i};if(!n.allowWrappedFallback)return{outcome:"error",tagName:i,error:o};try{return customElements.define(i,class extends t{}),{outcome:"defined-wrapped",tagName:i}}catch(s){return{outcome:"wrapped-error",tagName:i,error:s}}}},qI=(e,t,r="custom element tag")=>{const n=CF(e,t,r);if(n.outcome==="error"||n.outcome==="wrapped-error")throw n.error;return{status:n.outcome==="already-defined"?"already-defined":"defined",tagName:n.tagName}},uo=Xi("pie-updates",()=>ki()),HP=e=>{if(!e)return"missing";if(typeof e=="function")return"function";if(typeof e!="object")return typeof e;const t=Object.keys(e),r=e.default,n=r&&typeof r=="object"?Object.keys(r):[];return n.length>0?`object(keys=[${t.join(",")}],defaultKeys=[${n.join(",")}])`:`object(keys=[${t.join(",")}])`},xF=e=>{if(!e)return null;if(typeof e=="function")return e;if(typeof e!="object")return null;const t=e.model;if(typeof t=="function")return(n,i,o,s)=>t.call(e,n,i,o,s);const r=e.default;if(r&&typeof r=="object"){const n=r.model;if(typeof n=="function")return(i,o,s,a)=>n.call(r,i,o,s,a)}return null},RF=(e,t)=>{e.dispatchEvent(new CustomEvent("pie-controller-error",{detail:t,bubbles:!0,composed:!0}))},PF=e=>{const t=e.isConnected;return()=>t&&!e.isConnected},_F=async(e,t,r,n,i,o,s,a)=>{uo.debug(`${o} Using controller, env:`,i),uo.debug(`${o} Model before filter:`,{id:t.id,element:t.element,hasCorrectResponse:"correctResponse"in t});const l=(c,u,d)=>(uo.debug(`${o} updateSession called for ${c} with:`,d),Object.assign(r,d),a?.(t.id,t.element,d),Promise.resolve());try{const c=xF(n);if(!c)throw new Error(`Controller contract mismatch: expected a model() function but received ${HP(n)}`);const u=await c(t,r,i,l),d=u&&typeof u=="object"?u:{},f={id:t.id,element:t.element,...d};if(uo.debug(`${o} ✅ Controller filtered model:`,{id:f.id,element:f.element,hasCorrectResponse:"correctResponse"in f,mode:i.mode,role:i.role}),s())return;e.model=f,e.session=r}catch(c){throw uo.error(`${o} ❌ Controller error:`,c),c}},AF=e=>{const{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}=rw(LP,e);if(!n)throw new Error("env is required");if(!r)throw new Error("session is required");if(!t)throw new Error("config is required");return{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}},$F=async(e,t,r,n)=>{const{config:i,session:o,env:s,eventListeners:a,invokeControllerForModel:l,bundleType:c,onElementSessionUpdate:u}=r,d=i.models?.find(h=>h.id===e.id);if(!d)throw uo.error(`${n} Model not found for`,t),new Error(`model not found for ${t}`);const f=DP(o,d.id,d.element);if(a&&Object.entries(a).forEach(([h,g])=>{e.addEventListener(h,g)}),s&&l){const h=Zm(t,c);if(!h){uo.debug(`${n} ℹ️ No controller for ${t}, using server-processed model`),e.model=d,e.session=f;return}uo.debug(`${n} Invoking controller for ${t}#${e.id}`,{mode:s.mode,role:s.role,hasCorrectResponse:"correctResponse"in d});const g=PF(e);try{await _F(e,d,f,h,s,`${n}(${t}#${e.id})`,g,u)}catch(m){const v=m instanceof Error?m.message:String(m),b=v.includes("Controller contract mismatch");if(uo.error(`${n} Controller failed for ${t}#${e.id}:`,m),RF(e,{code:b?"PIE_CONTROLLER_CONTRACT_ERROR":"PIE_CONTROLLER_RUNTIME_ERROR",message:`${t} controller failed while applying model for ${e.id}. ${v}`,recoverable:!0,elementName:t,elementId:e.id,controllerShape:HP(h),cause:v}),g())return;e.model=d,e.session=f}}else uo.debug(`${n} Direct model assignment for ${t}#${e.id} (no controller invocation requested)`),e.model=d,e.session=f},UP=(e,t)=>{const r=AF(t),{container:n}=rw(LP,t),i=(n||document).querySelectorAll(e);return!i||i.length===0?(uo.debug(`no elements found for ${e}`),Promise.resolve()):Promise.all(Array.from(i,o=>$F(o,e,r,"[updatePieElement]"))).then(()=>{})},Tc=(e,t,r,n,i,o)=>(uo.debug("[updatePieElements] Updating all elements with env:",r),Promise.all(Object.entries(e.elements).map(([s,a])=>UP(s,{config:e,session:t,env:r,container:n,onElementSessionUpdate:i,bundleType:o}))).then(()=>{})),xn=Xi("pie-initialization",()=>ki());wP.timeoutMs;var MF={buildServiceBase:wF,bundleType:sc.player,env:{mode:"gather",role:"student"}},WI=(e,t)=>nw(e+W8,`editor element tag for ${t}`),VI=(e,t,r,n,i=!1)=>{UP(e,{config:t,session:r,...i?{}:{env:n.env},bundleType:n.bundleType,container:n.container,...n.eventListeners?.[e]&&{eventListeners:n.eventListeners[e]}})},GI=(e,t,r,n,i)=>{const o=[];return e?xn.debug("[registerPieElementsFromBundle] Available packages in bundle:",Object.keys(e)):xn.debug("[registerPieElementsFromBundle] No bundle module supplied; will only update tags already registered with customElements."),xn.debug("[registerPieElementsFromBundle] config.elements:",t.elements),Object.entries(t.elements).forEach(([s,a])=>{const l=nw(s,`element tag in config.elements for ${String(a)}`);if(xn.debug(`[registerPieElementsFromBundle] Processing element: ${l} -> ${a}`),customElements.get(l)){VI(l,t,r,i),i.bundleType===sc.editor&&VI(WI(l,String(a)),t,r,i,!0);return}if(!e){xn.warn(`[registerPieElementsFromBundle] Skipping "${l}" — no bundle module available and the tag is not yet registered. Will bind on next update if the host's loader registers it.`);return}const c=eF(a);xn.debug(`[registerPieElementsFromBundle] Package without version: "${c}"`);const u=e[c];if(xn.debug("[registerPieElementsFromBundle] elementData result:",u?"FOUND":"UNDEFINED"),!u)throw xn.error(`[registerPieElementsFromBundle] ❌ Package "${c}" not found in bundle!`),xn.error(`[registerPieElementsFromBundle] Lookup key: "${c}"`),xn.error("[registerPieElementsFromBundle] Available packages:",Object.keys(e)),new Error(`pie ${c} not found in ${Object.keys(e)}`);if(xn.debug(`[registerPieElementsFromBundle] elementData for ${c}:`,{hasController:!!u.controller,hasElement:!!u.Element,hasConfig:!!u.config,controllerKeys:u.controller?Object.keys(u.controller):[],bundleType:i.bundleType}),xn.debug(`[registerPieElementsFromBundle] Registering ${s} in registry${u.controller?" with controller":" (no controller; its model is used as given)"}`),NI({package:a,status:Jy.loading,tagName:l,controller:u.controller||null,config:u.config,bundleType:i.bundleType}),LI(u.Element)){qI(l,u.Element,`element tag in config.elements for ${String(a)}`);const d=(i.container||document).querySelectorAll(l);if(xn.debug(`[registerPieElementsFromBundle] Found ${d.length} elements for tag '${l}'`),d.forEach(f=>{FP(f,{config:t,session:r,env:i.env,eventListeners:i.eventListeners?.[l],bundleType:i.bundleType})}),NI({...n[l],status:Jy.loaded}),o.push(customElements.whenDefined(l).then(()=>{xn.debug("[registerPieElementsFromBundle] defined custom PIE element: %s",l)})),i.bundleType===sc.editor)if(LI(u.Configure)){const f=WI(l,String(a));qI(f,u.Configure,`editor element tag for ${String(a)}`),o.push(customElements.whenDefined(f).then(()=>{xn.debug(`[registerPieElementsFromBundle] defined custom PIE editor element: ${f}`)}))}else xn.error(`[registerPieElementsFromBundle] pie.Configure for ${c} is not a valid custom element constructor.`,u.configure)}else xn.error(`[registerPieElementsFromBundle] pie.Element for ${c} is not a valid custom element constructor.`)}),o},YI=(e,t,r={})=>{const n=Du(),i=rw(MF,r);if(J8(window)){xn.debug("[initializePiesFromLoadedBundle] window.pie available");const o=window.pie.default;GI(o,e,t,n,i);return}xn.debug("[initializePiesFromLoadedBundle] window.pie not present; using update-only path. Already-registered tags will be bound now; missing tags are expected to be registered by the host's loader and will bind on the next update pass."),GI(null,e,t,n,i)},OF=/\\\(|\\\[|\$\$|\\\$|\\begin\{|\\(?:eq)?ref\{/,LF=/\\\(|\\\[|\$|\\begin\{|\\(?:eq)?ref\{/,NF=new Set(["script","noscript","style","textarea","pre","code","annotation","annotation-xml","mjx-container","mjx-assistive-mml"]),DF=/(?:^|\s)mathjax_ignore(?:\s|$)/,jF="http://www.w3.org/1999/xhtml";function zF(){return globalThis["@pie-lib/math-rendering@2"]?.opts?.useSingleDollar?LF:OF}function BF(e){return NF.has(e.localName)||DF.test(e.getAttribute("class")??"")}function qP(e){return e.localName==="math"||e.hasAttribute("data-latex")&&!e.hasAttribute("data-math-handled")}function KI(e,t){if(qP(e)||e.querySelector("[data-latex]:not([data-math-handled])"))return!0;for(const r of e.getElementsByTagName("math"))if(!r.closest("mjx-assistive-mml"))return!0;return t.test(e.textContent??"")}function XI(e){const t=(e.ownerDocument??document).createElement("span");return e.replaceWith(t),t.append(e),t}function FF(e,t){const r=zF(),n=new Set;for(const s of t)for(const a of e.getElementsByTagName(s))for(let l=a.parentElement;l&&!n.has(l)&&(n.add(l),l!==e);l=l.parentElement);if(!n.has(e))return KI(e,r)?[e]:[];const i=[],o=s=>{for(const a of[...s.childNodes]){if(a.nodeType===Node.TEXT_NODE){r.test(a.data)&&i.push(XI(a));continue}if(a.nodeType!==Node.ELEMENT_NODE)continue;const l=a;t.has(l.localName)||BF(l)||(n.has(l)?o(l):KI(l,r)&&(qP(l)?i.push(XI(l)):l.namespaceURI===jF&&i.push(l)))}};return o(e),i}async function HF(e,t,r){const n=[...e].flatMap(i=>FF(i,t));for(const i of n)await r(i)}var UF="@pie-lib/math-rendering@2";function qF(){if(typeof window>"u")return;const e=window[UF]?.opts?.assetRoot;return typeof e=="string"&&e?e:void 0}var Dh=null;function WF(){return!!globalThis["@pie-lib/math-rendering@2"]?.opts?.useSingleDollar}async function VF(e,t){Dh??(Dh=Mr(async()=>{const{createMathjaxRenderer:n}=await import("./chunks/browser-a3c32178.js");return{createMathjaxRenderer:n}},[],import.meta.url).then(({createMathjaxRenderer:n})=>n({useSingleDollar:WF(),assetRoot:qF()?void 0:t})));let r;try{r=await Dh}catch(n){throw Dh=null,n}await r(e)}function JI(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function Ec(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(JI(e))return e;if(JI(t))return t}var GF=class{constructor(){Ee(this,"initialized",!1),Ee(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}},YF=class extends GF{constructor(...e){super(...e),Ee(this,"providerId","newrelic"),Ee(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(Ec()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&Ec()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){Ec()?.noticeError(e,t)}doTrackEvent(e,t){Ec()?.addPageAction(e,t)}doSetUserContext(e,t){const r=Ec();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=Ec();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}};function QI(e){return e&&typeof e=="object"?e:{}}function ZI(e){const t=QI(QI(e).loaderConfig);return Object.keys(t).length>0?t:null}function ek(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function tk(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function KF(e,t){return e.kind==="value"||e.kind==="null"?e:t}var jh,XF=Xi("instrumentation-provider-resolution",()=>ki());function JF(){return jh||(jh=new YF,jh.initialize()),jh}function WP(e){const t=ZI(e.runtimePlayer),r=ZI(e.player),n=tk(t),i=tk(r),o=n??i??!1,s=KF(ek(t),ek(r));if(s.kind!=="null"){if(s.kind==="unset")return o?JF():void 0;if(Q0(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";XF.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var QF=Symbol.for("pie.sessionCommit.observedSignature");function VP(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function ZF(e){return e?.shadowRoot??null}function e6(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function Zy(e,t,r){const n=ZF(e);n&&Zy(n,t,r);const i=s=>{t.has(s)||(t.add(s),VP(s)&&r.push(s),Zy(s,t,r))};for(const s of e6(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function GP(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function t6(e){const t=[],r=new Set;return GP(e)&&VP(e)&&(r.add(e),t.push(e)),Zy(e,r,t),t}function YP(e){try{return e.session}catch{return}}function KP(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function XP(e,t){try{Object.defineProperty(e,QF,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function r6(e){if(!GP(e))return;const t=KP(YP(e));t!==null&&XP(e,t)}function n6(e){if(e)for(const t of t6(e)){const r=KP(YP(t));r!==null&&XP(t,r)}}var Cc={trackPageActions:!1,manageProviderLifecycle:!1,maxRetries:3,initialRetryDelay:500,maxRetryDelay:5e3,debug:!1},i6=80,o6=1200,s6=75,a6=class{constructor(e={}){Ee(this,"config",void 0),Ee(this,"logger",void 0),Ee(this,"observer",null),Ee(this,"mutationObserver",null),Ee(this,"errorHandler",null),Ee(this,"retryAttempts",new Map),Ee(this,"retryTargets",new Map),Ee(this,"container",null),Ee(this,"isBrowser",void 0),Ee(this,"containerResources",new Set),Ee(this,"provider",void 0),Ee(this,"started",!1),Ee(this,"lifecycleVersion",0),Ee(this,"pendingRetryTimers",new Map),Ee(this,"retryInFlight",new Set),Ee(this,"pendingMediaChecks",new Map),this.config={trackPageActions:e.trackPageActions??Cc.trackPageActions,manageProviderLifecycle:e.manageProviderLifecycle??Cc.manageProviderLifecycle,maxRetries:e.maxRetries??Cc.maxRetries,initialRetryDelay:e.initialRetryDelay??Cc.initialRetryDelay,maxRetryDelay:e.maxRetryDelay??Cc.maxRetryDelay,debug:e.debug??Cc.debug},this.logger=Xi("resource-monitor",()=>this.isDebugEnabled()),this.provider=Q0(e.instrumentationProvider)?e.instrumentationProvider:void 0,e.instrumentationProvider&&!this.provider&&this.isDebugEnabled()&&this.logger.warn("Ignoring invalid instrumentation provider; expected InstrumentationProvider shape"),this.provider&&this.config.manageProviderLifecycle?this.provider.initialize().catch(t=>{this.isDebugEnabled()&&this.logger.warn("Failed to initialize instrumentation provider:",t)}):this.provider&&this.isDebugEnabled()&&this.logger.debug("Skipping provider lifecycle management for injected provider"),this.isBrowser=typeof window<"u"&&typeof document<"u"}isDebugEnabled(){return this.config.debug||ki()}truncateUrl(e){return e.length>i6?"..."+e.slice(-77):e}getOriginalUrl(e){try{const t=new URL(e);return t.searchParams.delete("retry"),t.searchParams.delete("t"),t.toString()}catch{return e}}withRetryParams(e,t){const r=String(t),n=Date.now().toString();try{const i=new URL(e);return i.searchParams.set("retry",r),i.searchParams.set("t",n),i.toString()}catch{return`${e}${e.includes("?")?"&":"?"}retry=${encodeURIComponent(r)}&t=${encodeURIComponent(n)}`}}getMediaErrorName(e){switch(e){case 1:return"MEDIA_ERR_ABORTED";case 2:return"MEDIA_ERR_NETWORK";case 3:return"MEDIA_ERR_DECODE";case 4:return"MEDIA_ERR_SRC_NOT_SUPPORTED";default:return}}buildResourceErrorDiagnostics(e,t){const r={eventType:t.eventType,tagName:e.tagName.toLowerCase(),resourceUrl:t.resourceUrl,originalUrl:t.originalUrl,currentRetries:t.currentRetries,remainingRetries:t.remainingRetries,willRetry:t.willRetry,cacheBypassActive:t.resourceUrl.includes("retry=")||t.resourceUrl.includes("t=")};if(e instanceof HTMLAudioElement||e instanceof HTMLVideoElement){const n=e.error,i=n?.code;r.currentSrc=e.currentSrc||e.src,r.readyState=e.readyState,r.networkState=e.networkState,r.paused=e.paused,r.ended=e.ended,r.currentTime=e.currentTime,r.duration=Number.isFinite(e.duration)?e.duration:null,r.mediaErrorCode=i,r.mediaErrorName=this.getMediaErrorName(i),r.mediaErrorMessage=typeof n?.message=="string"?n.message:void 0}return r}trackInstrumentationEvent(e,t){!this.config.trackPageActions||!this.provider?.isReady()||this.provider.trackEvent(e,{...t,component:"resource-monitor",timestamp:new Date().toISOString()})}trackInstrumentationError(e,t){!this.config.trackPageActions||!this.provider?.isReady()||this.provider.trackError(e,{...t,component:"resource-monitor",errorType:t.errorType||"ResourceError"})}start(e){if(this.started){if(this.container===e)return;this.stop()}if(!this.isBrowser){this.logger.debug("Not in browser environment, skipping resource monitoring");return}this.container=e,this.lifecycleVersion+=1,this.setupMutationObserver(),this.scanContainerResources(),this.setupPerformanceObserver(),this.setupErrorHandler(),this.started=!0,this.logger.info("✅ Resource monitoring started")}stop(){if(this.started){this.lifecycleVersion+=1,this.observer&&(this.observer.disconnect(),this.observer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.errorHandler&&this.container&&(this.container.removeEventListener("error",this.errorHandler,!0),this.errorHandler=null),this.retryAttempts.clear(),this.retryTargets.clear(),this.retryInFlight.clear();for(const e of this.pendingRetryTimers.values())clearTimeout(e);this.pendingRetryTimers.clear();for(const e of this.pendingMediaChecks.values())e.cleanup();if(this.pendingMediaChecks.clear(),this.containerResources.clear(),this.container=null,this.started=!1,this.provider&&this.config.manageProviderLifecycle)try{this.provider.destroy()}catch(e){this.isDebugEnabled()&&this.logger.warn("Failed to destroy instrumentation provider:",e)}this.logger.info("Resource monitoring stopped")}}setupMutationObserver(){if(!this.isBrowser||typeof MutationObserver>"u"||!this.container){this.logger.debug("MutationObserver not available or no container");return}try{this.mutationObserver=new MutationObserver(e=>{for(const t of e)if(t.addedNodes.forEach(r=>{r instanceof HTMLElement&&this.scanElementForResources(r)}),t.type==="attributes"&&t.target instanceof HTMLElement){const r=t.target;if(this.isResourceElement(r)){const n=this.getResourceSrc(r);n&&(this.containerResources.add(n),this.isDebugEnabled()&&this.logger.debug(`📌 Tracked resource attribute change: ${n}`))}}}),this.mutationObserver.observe(this.container,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","href"]}),this.logger.debug("MutationObserver set up successfully")}catch(e){this.logger.warn("Failed to set up MutationObserver:",e)}}scanElementForResources(e){if(this.isResourceElement(e)){const t=this.getResourceSrc(e);t&&(this.containerResources.add(t),this.isDebugEnabled()&&this.logger.debug(`📌 Tracked new resource in container: ${t}`))}["img","audio","video",'link[rel="stylesheet"]',"source"].forEach(t=>{e.querySelectorAll(t).forEach(r=>{if(this.isResourceElement(r)){const n=this.getResourceSrc(r);n&&this.containerResources.add(n)}})})}scanContainerResources(){this.container&&(this.scanElementForResources(this.container),this.isDebugEnabled()&&(this.logger.debug(`📊 Initial container scan found ${this.containerResources.size} resources`),this.containerResources.size>0&&this.containerResources.forEach(e=>{this.logger.debug(` - ${this.truncateUrl(e)}`)})))}setupPerformanceObserver(){if(!this.isBrowser||typeof PerformanceObserver>"u"){this.logger.debug("PerformanceObserver not available");return}try{this.observer=new PerformanceObserver(e=>{for(const t of e.getEntries())t.entryType==="resource"&&this.handleResourceTiming(t)}),this.observer.observe({type:"resource",buffered:!0}),this.logger.debug("PerformanceObserver set up successfully")}catch(e){this.logger.warn("Failed to set up PerformanceObserver:",e)}}handleResourceTiming(e){if(!this.isRelevantResource(e)){this.isDebugEnabled()&&(e.initiatorType==="img"||e.initiatorType==="audio"||e.initiatorType==="video")&&this.logger.debug(`⏭️ Skipping non-container resource: ${this.truncateUrl(e.name)}`);return}const t=e.duration,r=e.transferSize,n=e.name,i=this.getOriginalUrl(n),o=e.responseEnd===0&&e.duration>0,s=this.retryAttempts.has(i),a=this.retryAttempts.get(i)||0;if(this.isDebugEnabled()){const l=this.truncateUrl(n),c=(r/1024).toFixed(2),u=o?"❌ FAILED":"✅ SUCCESS",d={total:`${t.toFixed(2)}ms`,dns:e.domainLookupEnd>0?`${(e.domainLookupEnd-e.domainLookupStart).toFixed(2)}ms`:"n/a",tcp:e.connectEnd>0?`${(e.connectEnd-e.connectStart).toFixed(2)}ms`:"n/a",request:e.responseStart>0?`${(e.responseStart-e.requestStart).toFixed(2)}ms`:"n/a",response:e.responseEnd>0?`${(e.responseEnd-e.responseStart).toFixed(2)}ms`:"n/a",size:r>0?`${c} KB`:"0 KB",type:e.initiatorType,protocol:e.nextHopProtocol||"unknown"},f=s&&!o?`
1098
+ 🔄 Retry Success: Succeeded after ${a} ${a===1?"retry":"retries"}`:"";this.logger.info(`📊 PIE Resource Load ${u}
1099
+ URL: ${l}
1100
+ Type: ${d.type} | Protocol: ${d.protocol}
1101
+ ⏱️ Total Time: ${d.total}
1102
+ └─ DNS Lookup: ${d.dns}
1103
+ └─ TCP Connect: ${d.tcp}
1104
+ └─ Request Time: ${d.request}
1105
+ └─ Response Time: ${d.response}
1106
+ 📦 Transfer Size: ${d.size}${f}`)}else this.logger.debug(`Resource loaded: ${e.name}`,{duration:`${t.toFixed(2)}ms`,size:`${r} bytes`,type:e.initiatorType,failed:o,wasRetried:s,retryCount:a});o||this.handleSuccessfulLoad(i,e,t,r,a,s),this.trackInstrumentationEvent("pie-resource-load",{url:e.name,duration:Math.round(t),size:r,type:e.initiatorType,failed:o,wasRetried:s,retryCount:a}),o&&this.handleFailedLoad(i,e,t,a,s)}isLifecycleActive(e){return this.started&&this.lifecycleVersion===e}clearRetryTracking(e){this.retryAttempts.delete(e),this.retryTargets.delete(e),this.retryInFlight.delete(e)}clearPendingMediaCheck(e){const t=this.pendingMediaChecks.get(e);t&&(t.cleanup(),this.pendingMediaChecks.delete(e))}getRetryTargets(e){let t=this.retryTargets.get(e);return t||(t=new Set,this.retryTargets.set(e,t)),t}getPrimaryRetryTarget(e){const t=this.retryTargets.get(e);if(!t||t.size===0)return null;for(const r of t)return r;return null}handleSuccessfulLoad(e,t,r,n,i,o){const s={url:e,resourceType:t.initiatorType,duration:r,size:n,retryCount:i,maxRetries:this.config.maxRetries},a=t.initiatorType==="audio"||t.initiatorType==="video"||t.initiatorType==="source";if(o&&a){this.reconcileMediaRetrySuccess(e,s);return}this.dispatchEvent("pie-resource-load-success",s),o&&this.finalizeRetrySuccess(e,s)}resolveMediaTarget(e){if(e instanceof HTMLAudioElement)return{mediaEl:e,mediaTag:"audio"};if(e instanceof HTMLVideoElement)return{mediaEl:e,mediaTag:"video"};if(e instanceof HTMLSourceElement){const t=e.parentElement;if(t instanceof HTMLAudioElement)return{mediaEl:t,mediaTag:"audio"};if(t instanceof HTMLVideoElement)return{mediaEl:t,mediaTag:"video"}}return null}resolveMediaTargetsForUrl(e){const t=this.retryTargets.get(e);if(!t||t.size===0)return[];const r=new Set,n=[];for(const i of t){const o=this.resolveMediaTarget(i);if(!o)continue;const{mediaEl:s,mediaTag:a}=o;if(r.has(s))continue;const l=s.currentSrc||s.src;l&&this.getOriginalUrl(l)!==e||(r.add(s),n.push({mediaEl:s,mediaTag:a}))}return n}normalizeRetrySuccessResourceType(e,t){if(t!=="source")return t;const r=this.resolveMediaTargetsForUrl(e);return r.length===0?t:r[0].mediaTag}isMediaRetryRecovered(e){const t=this.resolveMediaTargetsForUrl(e);if(t.length===0)return!1;for(const{mediaEl:r}of t){const n=!!r.error,i=r.networkState===HTMLMediaElement.NETWORK_NO_SOURCE,o=r.readyState>=HTMLMediaElement.HAVE_METADATA;if(!n&&!i&&o)return!0}return!1}finalizeRetrySuccess(e,t){if(!this.retryAttempts.has(e))return;const r={...t,resourceType:this.normalizeRetrySuccessResourceType(e,t.resourceType)},n=this.truncateUrl(e);this.logger.info(`✅ PIE Resource Retry Succeeded!
1107
+ URL: ${n}
1108
+ Retry Attempt: ${r.retryCount}
1109
+ Load Time: ${(r.duration||0).toFixed(2)}ms
1110
+ Result: Resource now available to user`),this.dispatchEvent("pie-resource-retry-success",r),this.dispatchMediaRetryReady(e,r),this.clearPendingMediaCheck(e),this.clearRetryTracking(e)}reconcileMediaRetrySuccess(e,t){if(this.clearPendingMediaCheck(e),this.isMediaRetryRecovered(e)){this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t);return}this.isDebugEnabled()&&this.logger.debug(`⏳ Waiting for media readiness before retry success: ${this.truncateUrl(e)}`);const r=this.lifecycleVersion,n=this.resolveMediaTargetsForUrl(e),i=[],o=setInterval(()=>{if(!this.isLifecycleActive(r)){this.clearPendingMediaCheck(e);return}if(!this.retryAttempts.has(e)){this.clearPendingMediaCheck(e);return}this.isMediaRetryRecovered(e)&&(this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t))},s6),s=setTimeout(()=>{if(!this.isLifecycleActive(r)){this.clearPendingMediaCheck(e);return}if(!this.retryAttempts.has(e)){this.clearPendingMediaCheck(e);return}this.clearPendingMediaCheck(e),this.handleMediaRetryReconciliationTimeout(e,t)},o6);for(const{mediaEl:a}of n){const l=()=>{this.isLifecycleActive(r)&&this.retryAttempts.has(e)&&this.isMediaRetryRecovered(e)&&(this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t))};a.addEventListener("loadedmetadata",l),a.addEventListener("canplay",l),i.push({mediaEl:a,handler:l})}this.pendingMediaChecks.set(e,{cleanup:()=>{clearInterval(o),clearTimeout(s);for(const{mediaEl:a,handler:l}of i)a.removeEventListener("loadedmetadata",l),a.removeEventListener("canplay",l)}})}handleMediaRetryReconciliationTimeout(e,t){const r=this.truncateUrl(e);this.logger.warn(`⚠️ PIE Resource Retry Ready Timeout
1111
+ URL: ${r}
1112
+ Retry Attempt: ${t.retryCount}
1113
+ Status: Media did not become healthy after fetch success`),this.dispatchEvent("pie-resource-retry-failed",{...t,error:"Media fetch succeeded but did not become ready before timeout"}),this.trackInstrumentationError(new Error(`Resource retry reconciliation timed out before media was healthy: ${e}`),{resourceUrl:e,resourceType:t.resourceType,retryCount:t.retryCount,errorType:"MediaRetryReadyTimeout"});const n=this.getPrimaryRetryTarget(e);if(n){this.retryResourceLoad(n,e);return}this.handlePermanentFailure(e,t.resourceType,t.retryCount)}dispatchMediaRetryReady(e,t){const r=this.resolveMediaTargetsForUrl(e);if(r.length!==0)for(const{mediaEl:n,mediaTag:i}of r){const o=new CustomEvent("pie-media-retry-ready",{detail:{...t,mediaTag:i},bubbles:!0,composed:!0});n.dispatchEvent(o)}}handleFailedLoad(e,t,r,n,i){const o=this.truncateUrl(e);i?(this.logger.warn(`⚠️ PIE Resource Retry Failed
1114
+ URL: ${o}
1115
+ Retry Attempt: ${n}
1116
+ Remaining Attempts: ${this.config.maxRetries-n}
1117
+ Status: Will ${n>=this.config.maxRetries?"give up":"retry again"}`),this.dispatchEvent("pie-resource-retry-failed",{url:e,resourceType:t.initiatorType,duration:r,retryCount:n,maxRetries:this.config.maxRetries,error:"Resource load failed after retry"})):(this.logger.warn(`⚠️ PIE Resource Initial Load Failed
1118
+ URL: ${o}
1119
+ Status: Will attempt ${this.config.maxRetries} ${this.config.maxRetries===1?"retry":"retries"}`),this.dispatchEvent("pie-resource-load-failed",{url:e,resourceType:t.initiatorType,duration:r,retryCount:0,maxRetries:this.config.maxRetries,error:"Initial resource load failed"})),this.trackInstrumentationError(new Error(`Resource load failed: ${t.name}`),{resourceUrl:t.name,resourceType:t.initiatorType,duration:Math.round(r),wasRetried:i,retryCount:n})}isRelevantResource(e){const t=e.name;let r=this.containerResources.has(t);if(!r){for(const n of this.containerResources)if(t.endsWith(n)||n.endsWith(t))return!0;if(this.container&&this.isResourceInContainer(t,e.initiatorType))return this.containerResources.add(t),this.isDebugEnabled()&&this.logger.debug(`📌 Retroactively tracked resource: ${this.truncateUrl(t)}`),!0}return r}isResourceInContainer(e,t){if(!this.container)return!1;try{const r=new URL(e),n=r.pathname+r.search;if(t==="img"||t==="audio"||t==="video"){const i=this.container.querySelectorAll(`${t}[src]`);for(const o of i){const s=o;if(s.src&&(s.src===e||s.src.endsWith(n)))return!0}}if(t==="link"){const i=this.container.querySelectorAll("link[href]");for(const o of i){const s=o;if(s.href&&(s.href===e||s.href.endsWith(n)))return!0}}if(t==="source"){const i=this.container.querySelectorAll("source[src]");for(const o of i){const s=o;if(s.src&&(s.src===e||s.src.endsWith(n)))return!0}}}catch(r){this.isDebugEnabled()&&this.logger.debug(`Error checking if resource is in container: ${r}`)}return!1}setupErrorHandler(){this.container&&(this.errorHandler=e=>{const t=e.target;if(!this.isResourceElement(t))return;const r=t.tagName.toLowerCase(),n=this.getResourceSrc(t);if(!n)return;const i=this.getOriginalUrl(n),o=this.retryAttempts.get(i)||0,s=this.config.maxRetries-o,a=s>0,l=this.buildResourceErrorDiagnostics(t,{eventType:e.type,resourceUrl:n,originalUrl:i,currentRetries:o,remainingRetries:s,willRetry:a});if(this.isDebugEnabled()){const c=this.truncateUrl(n);(a?this.logger.warn.bind(this.logger):this.logger.error.bind(this.logger))(`${a?"⚠️":"❌"} PIE Resource Load Error
1120
+ Element: <${r}>
1121
+ URL: ${c}
1122
+ Current Attempts: ${o}
1123
+ Remaining Retries: ${s}/${this.config.maxRetries}
1124
+ Action: ${a?"Will retry with exponential backoff":"Max retries reached, giving up"}`,l)}else(a?this.logger.warn.bind(this.logger):this.logger.error.bind(this.logger))(`${a?"⚠️":"❌"} Resource error: ${r} failed to load ${n}`);this.trackInstrumentationEvent("pie-resource-load-error",l),this.trackInstrumentationError(new Error(`Resource load error: ${i}`),{resourceType:r,...l}),this.retryResourceLoad(t,i)},this.container.addEventListener("error",this.errorHandler,!0),this.logger.debug("Error handler attached to container"))}isResourceElement(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return["img","audio","video","link","source"].includes(t)}getResourceSrc(e){return e instanceof HTMLLinkElement?e.href:"src"in e&&e.src?e.src:null}handlePermanentFailure(e,t,r){if(this.clearPendingMediaCheck(e),this.clearRetryTracking(e),this.isDebugEnabled()){const n=this.truncateUrl(e);this.logger.error(`❌ PIE Resource Permanently Failed
1125
+ URL: ${n}
1126
+ Total Attempts: ${r+1} (initial + ${r} retries)
1127
+ Status: Giving up after ${this.config.maxRetries} retries
1128
+ ⚠️ This resource will not be available to the user`)}else this.logger.error(`❌ Failed to load resource after ${this.config.maxRetries} retries: ${e}`);this.dispatchEvent("pie-resource-load-error",{url:e,resourceType:t,retryCount:r,maxRetries:this.config.maxRetries,error:`Resource permanently failed after ${this.config.maxRetries} retries`}),this.trackInstrumentationError(new Error(`Resource permanently failed after ${this.config.maxRetries} retries: ${e}`),{resourceUrl:e,retryCount:r,resourceType:t})}logRetrySchedule(e,t,r,n){if(this.isDebugEnabled()){const i=this.truncateUrl(e),o=Math.min(this.config.initialRetryDelay*Math.pow(2,t+1),this.config.maxRetryDelay),s=n==="img"?"Cache-busting URL":n==="audio"||n==="video"?"element.load()":n==="link"?"Cache-busting URL":"URL update";this.logger.info(`🔄 PIE Resource Retry Scheduled
1129
+ URL: ${i}
1130
+ Attempt: ${t+1}/${this.config.maxRetries}
1131
+ ⏰ Wait Time: ${r}ms (exponential backoff)
1132
+ Next Retry Delay: ${o}ms (if this fails)
1133
+ Strategy: ${s}`)}else this.logger.info(`🔄 Retrying resource load (attempt ${t+1}/${this.config.maxRetries}) after ${r}ms: ${e}`)}performRetryLoadAttempt(e,t,r){try{if(e instanceof HTMLAudioElement||e instanceof HTMLVideoElement){const n=this.withRetryParams(t,r);if(e.src)e.src=n;else{const i=Array.from(e.querySelectorAll("source")).find(o=>typeof o.src=="string"&&this.getOriginalUrl(o.src)===t);i&&(i.src=n)}e.load(),this.isDebugEnabled()&&this.logger.debug(`✓ Triggered load() on <${e.tagName.toLowerCase()}> with cache-busting params`)}else if(e instanceof HTMLSourceElement){e.src=this.withRetryParams(t,r);const n=e.parentElement;(n instanceof HTMLAudioElement||n instanceof HTMLVideoElement)&&n.load(),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <source> src with cache-busting params and reloaded parent media: retry=${r}`)}else e instanceof HTMLImageElement?(e.src=this.withRetryParams(t,r),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <img> src with cache-busting params: retry=${r}, t=${Date.now()}`)):e instanceof HTMLLinkElement&&(e.href=this.withRetryParams(t,r),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <link> href with cache-busting params: retry=${r}, t=${Date.now()}`))}catch(n){const i=this.buildResourceErrorDiagnostics(e,{eventType:"retry",resourceUrl:this.getResourceSrc(e)||t,originalUrl:t,currentRetries:r,remainingRetries:Math.max(0,this.config.maxRetries-r),willRetry:r<this.config.maxRetries});this.isDebugEnabled()?this.logger.error(`❌ Error during retry attempt for ${t}:`,n,i):this.logger.error(`Error during retry for ${t}:`,n),this.trackInstrumentationError(new Error(`Retry attempt error for resource: ${t}`),{...i})}}retryResourceLoad(e,t){if(this.getRetryTargets(t).add(e),!this.started)return;if(this.retryInFlight.has(t)){this.isDebugEnabled()&&this.logger.debug(`Retry already scheduled for ${this.truncateUrl(t)}; skipping duplicate error-triggered schedule`);return}const r=this.retryAttempts.get(t)||0;if(r>=this.config.maxRetries){this.handlePermanentFailure(t,e.tagName.toLowerCase(),r);return}const n=Math.min(this.config.initialRetryDelay*Math.pow(2,r),this.config.maxRetryDelay),i=r+1;this.retryInFlight.add(t),this.retryAttempts.set(t,i),this.logRetrySchedule(t,r,n,e.tagName.toLowerCase()),this.trackInstrumentationEvent("pie-resource-retry",{url:t,attempt:i,delay:n});const o=this.lifecycleVersion,s=setTimeout(()=>{if(this.pendingRetryTimers.delete(t),this.retryInFlight.delete(t),!this.isLifecycleActive(o))return;const a=this.getPrimaryRetryTarget(t);a&&(this.isDebugEnabled()&&this.logger.debug(`⏱️ Retry wait completed (${n}ms), attempting reload now...`),this.performRetryLoadAttempt(a,t,i))},n);this.pendingRetryTimers.set(t,s)}dispatchEvent(e,t){if(!this.container)return;const r=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});this.container.dispatchEvent(r)}getStats(){const e=[];return this.retryAttempts.forEach((t,r)=>{e.push({url:r,attempts:t})}),{activeRetries:this.retryAttempts.size,failedResources:e.sort((t,r)=>r.attempts-t.attempts)}}},l6=5e3;function c6(e,t,r,n="pie-player"){const i=Xi("use-resource-monitor",r);let o=nr(null),s=nr(!1),a=nr(null),l=nr(""),c=nr(void 0);return Vr(()=>{e(),t(),r(),zn(()=>{const u=e(),d=t(),f=r(),h=d?.trackPageActions??!1,g=d?.maxResourceRetries??pm.maxResourceRetries,m=d?.resourceRetryDelay??pm.resourceRetryDelay,v=WP({player:{loaderConfig:d},component:n,debug:f}),b=JSON.stringify({trackPageActions:h,maxRetries:g,retryDelay:m,debugEnabled:f}),I=R(c)!==v,C=R(a)!==u,x=R(l)!==b,$=u&&R(s)&&(C||x||I);if(!u&&R(o)){i.debug(`Host element removed, stopping resource monitor for ${n}`),R(o).stop(),He(o,null),He(s,!1),He(a,null),He(c,void 0),He(l,"");return}$&&R(o)&&(i.debug(`Reinitializing resource monitor for ${n}`,{hostChanged:C,configChanged:x,providerChanged:I}),R(o).stop(),He(o,null),He(s,!1)),u&&!R(s)&&(i.debug(`Initializing resource monitor for ${n}`,{trackPageActions:h,maxRetries:g,retryDelay:m,provider:v?.providerId,hasContainer:!!u}),He(o,new a6({trackPageActions:h,instrumentationProvider:v,maxRetries:g,initialRetryDelay:m,maxRetryDelay:l6,debug:f}),!0),R(o).start(u),He(s,!0),He(a,u,!0),He(c,v,!0),He(l,b,!0),i.info(`✅ Resource monitoring enabled for ${n}`+(h&&v?` (tracking via ${v.providerName})`:" (retry only)")))})}),V0(()=>{if(R(o)){const u=R(o).getStats();i.debug(`Resource monitor stats at cleanup for ${n}:`,u),R(o).stop(),He(o,null),He(s,!1),He(a,null),He(c,void 0),He(l,"")}}),{get instance(){return R(o)},getStats(){return R(o)?.getStats()??{activeRetries:0,failedResources:[]}},get isActive(){return R(s)&&R(o)!==null}}}function tf(e){return e?e.trim().replace(/_/g,"-").split(/[.@]/)[0].toLowerCase():""}function u6(e){const t=tf(e);if(!t)return[];const r=t.split("-"),n=[];for(let i=r.length;i>0;i--){const o=r.slice(0,i);o.length>1&&o[o.length-1].length===1||n.push(o.join("-"))}return n}function d6(e,t){for(const r of u6(e)){const n=t.find(i=>tf(i)===r);if(n!=null)return n}}var f6={common:{close:"Close",cancel:"Cancel",save:"Save",reset:"Reset",retry:"Retry",back:"Back",next:"Next",previous:"Previous",submit:"Submit",continue:"Continue",finish:"Finish",yes:"Yes",no:"No",ok:"OK",any:"Any",off:"Off",auto:"Auto",all:"All",none:"None",loading:"Loading…",error:"Error",settings:"Settings",language:"Language",theme:"Theme",preview:"Preview",author:"Author",unknown:"Unknown",untitled:"Untitled",apply:"Apply",enabled:"Enabled",disabled:"Disabled",closeA11y:"Close",settingsA11y:"Open settings menu"},player:{passage:"Passage",passages:"Passages",question:"Question",questionNumbered:"Question {position}",questions:"Questions",items:"Items",section:"Section",loadingSection:"Loading section content…",sectionLoadError:"Section content could not be loaded.",loadingPassage:"Loading passage content…",configurationError:"Configuration Error",playerError:"Player Error",authoringBackendError:"Authoring Backend Configuration Error",itemLoadError:"Question could not be loaded.",sectionTabsA11y:"Section content tabs",passagesRegionA11y:"Passages",itemsRegionA11y:"Items",sectionToolsA11y:"Section tools",scrollDownA11y:"Scroll down",resizePanels:"Resize panels",resizePassagesAndItemsA11y:"Resize passages and items panels",resizeMediaRegion:"Resize media region",resizeQuestionAndMediaA11y:"Resize question and media panels",resizePassageAndMediaA11y:"Resize passage and media panels",assessment:{sectionPosition:"Section {position} of {total}",noSections:"No sections",loadFailed:"The assessment could not be loaded. Try again.",restoreFailed:"Your saved answers for this section could not be restored. Try again."},formative:{checkAnswer:"Check answer",tryAgain:"Try again",answerRecorded:"Answer recorded.",correct:"Correct.",partlyCorrect:"Partly correct.",notCorrect:"Not correct.",notAutoScored:"Answer recorded. This question is not scored automatically.",checkFailed:"This question could not be checked. Try again.",triesLeft:{one:"{count} try left.",other:"{count} tries left."}},timedMedia:{waitingForMedia:"Questions will appear as the media plays.",questionAvailable:"Question {position} is now available.",playbackPaused:"Playback paused. Answer question {position} to continue.",playbackAdvisory:"Answer question {position} before continuing with the media.",playbackReleased:"Answer accepted. Continue playing the media."}},toolkit:{toolsA11y:"Assessment tools",toolbarInitError:"Unable to initialize assessment toolkit.",settingsTitle:"Settings",closeSettingsA11y:"Close settings",dragPanelA11y:"Drag panel",closePanelA11y:"Close panel",resizeWindow:"Resize window",minimize:"Minimize",maximize:"Maximize",minimizePanelA11y:"Minimize panel",maximizePanelA11y:"Maximize panel",window:{moveLeftA11y:"Move tool left",moveRightA11y:"Move tool right",moveUpA11y:"Move tool up",moveDownA11y:"Move tool down",shrinkA11y:"Shrink tool window",growA11y:"Grow tool window",centerA11y:"Center tool window",closeA11y:"Close tool"},placement:{controlsA11y:"Move and rotate",rotateClockwiseA11y:"Rotate {degrees}° clockwise",rotateCounterclockwiseA11y:"Rotate {degrees}° counterclockwise"},announce:{movedUp:"Moved up to {position}",movedDown:"Moved down to {position}",movedLeft:"Moved left to {position}",movedRight:"Moved right to {position}",rotatedTo:"Rotated to {degrees} degrees"}},tools:{calculator:{name:"Calculator",nameBasic:"Basic Calculator",nameScientific:"Scientific Calculator",nameGraphing:"Graphing Calculator",description:"Multi-type calculator (basic, scientific, graphing)",openedBasic:"Basic calculator opened",openedScientific:"Scientific calculator opened",openedGraphing:"Graphing calculator opened",closedBasic:"Basic calculator closed",closedScientific:"Scientific calculator closed",closedGraphing:"Graphing calculator closed",toolA11y:"Calculator tool",loading:"Loading calculator…",providerUnavailable:"The calculator is unavailable."},graph:{name:"Graph",description:"Coordinate plane",buttonA11y:"Graph, coordinate plane",tooltip:"Graph",toolA11y:"Graph tool — draw points and lines on a coordinate grid",canvasA11y:"Graph canvas — use tools to add points and draw lines",grid:"Grid:",gridOpacityA11y:"Grid opacity",pointA11y:"Graph point {id}",modeSelector:"Selector",modeSelectorHint:"Selector: click and drag points to move them or associated lines.",modePoint:"Point",modePointHint:"Point: click on the grid to add points.",modeLine:"Line",modeLineHint:"Line: click a starting point, then an ending point to draw a line.",modeDelete:"Delete",modeDeleteHint:"Delete: click on a point to delete it and any connected lines."},periodicTable:{name:"Periodic Table",description:"Chemistry periodic table reference",buttonA11y:"Periodic Table, chemistry reference",tooltip:"Periodic Table",toolA11y:"Periodic table — select an element to view its details",elementsA11y:"Periodic table elements",showAllA11y:"Show all elements",allElements:"All Elements",atomicMass:"Atomic Mass",atomicNumber:"Atomic No",electronConfig:"Electron Config",phase:"Phase",filterByA11y:"Filter by {category}",elementA11y:"{name}, Symbol: {symbol}, Atomic number: {number}, Atomic mass: {mass}, Category: {category}",outsideFilterA11y:", outside the current filter",category:{unknown:"Unknown",alkaliMetal:"Alkali Metal",alkalineEarthMetal:"Alkaline Earth Metal",transitionMetal:"Transition Metal",postTransitionMetal:"Post-transition Metal",metalloid:"Metalloid",diatomicNonmetal:"Diatomic Nonmetal",polyatomicNonmetal:"Polyatomic Nonmetal",nobleGas:"Noble Gas",lanthanide:"Lanthanide",actinide:"Actinide"}},ruler:{name:"Ruler",description:"On-screen ruler for measurements",buttonA11y:"Ruler",tooltip:"Ruler",toolA11y:"Draggable and rotatable ruler measurement tool",unitSelectionA11y:"Ruler unit selection",inches:"Inches",centimeters:"Centimeters",inchesInSentence:"inches",centimetersInSentence:"centimeters",switchToInchesA11y:"Switch to inches",switchToCentimetersA11y:"Switch to centimeters",switchedTo:"Switched to {unit}",applicationA11y:"Ruler tool. Use arrow keys to move, Shift+arrows to rotate, PageUp or PageDown for fine rotation, U to toggle units. Current unit: {unit}",imageAlt:"Ruler showing {unit}"},protractor:{name:"Protractor",description:"On-screen protractor for angle measurements",buttonA11y:"Protractor",tooltip:"Protractor",toolA11y:"Protractor tool. Use arrow keys to move, Shift+arrows to rotate, and PageUp or PageDown for fine rotation.",roleA11y:"Draggable and rotatable protractor measurement tool",imageAlt:"Protractor with 180-degree semicircular scale marked from 0 to 180 degrees in both directions, with degree markings every 10 degrees"},dictionary:{name:"Dictionary",description:"Look up word definitions",buttonA11y:"Dictionary, look up word definitions",tooltip:"Dictionary",toolA11y:"Dictionary"},pictureDictionary:{name:"Picture Dictionary",description:"Look up pictures for words",buttonA11y:"Picture Dictionary, look up pictures for words",tooltip:"Picture Dictionary",toolA11y:"Picture Dictionary"},dictionarySpanish:{name:"Spanish Dictionary",description:"Look up word definitions in Spanish",buttonA11y:"Spanish Dictionary, look up word definitions in Spanish",tooltip:"Spanish Dictionary",toolA11y:"Spanish Dictionary"},pictureDictionarySpanish:{name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",buttonA11y:"Spanish Picture Dictionary, look up pictures for words in Spanish",tooltip:"Spanish Picture Dictionary",toolA11y:"Spanish Picture Dictionary"},lineReader:{name:"Line Reader",description:"Reading guide overlay",buttonA11y:"Line Reader, reading guide",tooltip:"Line Reader",roleA11y:"Draggable and resizable reading guide overlay",close:"Close line reader",resizeWindowA11y:"Drag to resize the reading window",resizeFrameA11y:"Drag to resize the frame and window width",windowHeightAnnounce:"Reading window height {pixels} pixels",frameHeightAnnounce:"Frame height {pixels} pixels",widthAnnounce:"Width {pixels} pixels",applicationA11y:"Line Reader tool. A clear reading window inside an obscuring frame. Use arrow keys to move, +/- to resize the reading window, Escape to close. Reading window height: {paneHeight} pixels, Frame height: {frameHeight} pixels",resizeWindowFullA11y:"Resize the reading window. Drag, or use the up and down arrow keys to change its height. Current height {paneHeight} pixels",resizeFrameFullA11y:"Resize the frame. Drag, or use the up and down arrow keys to change the frame height and the left and right arrow keys to change the width. Current frame height {frameHeight} pixels, width {width} pixels"},answerEliminator:{name:"Answer Eliminator",description:"Strike through answer choices",buttonA11y:"Strike Through, eliminate answer choices",tooltip:"Strike Through"},highlighter:{name:"Highlighter",description:"Highlight and annotate text",buttonA11y:"Highlight text",tooltip:"Highlight"},annotationToolbar:{name:"Annotation",description:"Highlight and annotate text",buttonA11y:"Annotate, highlight and mark up text",tooltip:"Annotate",toolbarA11y:"Text annotation toolbar",underline:"Underline",underlineA11y:"Underline selected text",readAloud:"Read Aloud",readAloudA11y:"Read selected text aloud",remove:"Remove",removeA11y:"Remove this annotation",clearAll:"Clear All",clearAllA11y:"Clear all annotations from document",highlightYellowA11y:"Yellow highlight",highlightPinkA11y:"Pink highlight",highlightBlueA11y:"Blue highlight",highlightGreenA11y:"Green highlight"},theme:{name:"Theme",description:"Accessible themes and contrast",buttonA11y:"Theme, change colors and contrast",tooltip:"Theme",selectorA11y:"Theme selector",hint:"Select a theme to improve readability and reduce eye strain.",selectA11y:"Select theme",selectCurrentA11y:"Select theme. Current theme: {name}",optionUnavailableA11y:"{name}, unavailable",unavailableName:"Unavailable theme: {id}",unavailableDescription:"PIE's managed base theme remains active until this theme becomes available again.",unavailableStatus:"The selected theme is unavailable. PIE's managed base theme is active until it becomes available again."},textToSpeech:{name:"Text to Speech",description:"Read content aloud",inline:{controlsA11y:"Reading controls",playbackSpeedA11y:"Playback speed",rewindA11y:"Rewind",fastForwardA11y:"Fast-forward",stopA11y:"Stop reading",initializing:"Initializing text-to-speech",initFailed:"Unable to initialize text-to-speech. Try again.",starting:"Starting reading",started:"Reading started",resumed:"Reading resumed",pausedAnnouncement:"Reading paused",stopped:"Reading stopped",switchedSection:"Reading switched to another section",startFailed:"Unable to start reading",skippedForward:"Skipped forward",skipForwardFailed:"Unable to skip forward",skippedBackward:"Skipped backward",skipBackwardFailed:"Unable to skip backward",speedChangeFailed:"Unable to change playback speed",speedAnnounce:"Playback speed {label}",playA11y:"Play reading",pauseA11y:"Pause reading",resumeA11y:"Resume reading"}},signLanguage:{name:"Sign Language",description:"Signed alternate for authored content",generic:"Sign language",unknown:"Sign language ({code})",ase:"American Sign Language",bfi:"British Sign Language",fsl:"French Sign Language",gss:"Greek Sign Language",mfs:"Mexican Sign Language",signedEnglish:"Signed English",regionA11y:"{language} translation"},audioTranscript:{name:"Audio Transcript",description:"Text transcript of audio content",regionA11y:"Transcript"}},debug:{session:"Session",sessionData:"Session Data",sessionDataPersistent:"PIE Session Data (Persistent)",noItemSessionYet:"No item session data yet. Interact with the item to see updates here.",itemSessionsSnapshot:"Item Sessions Snapshot",sectionControllerUnavailable:"Section controller not available for this section yet.",filteredModel:"Filtered Model",environment:"Environment",events:"Events",controllerEvents:"Controller Events",instrumentation:"Instrumentation",databaseState:"Database state",sessionDb:"Session DB (Server)",noRows:"No rows",noRecords:"No instrumentation records yet.",selectRecord:"Select a record to inspect details.",selectEvent:"Select an event to inspect payload details.",showRawTables:"Show raw tables",showReconstructedSnapshots:"Show reconstructed snapshots",showSectionRequest:"Show section request",showAssessmentRequest:"Show assessment request",liveUpdatesUnsupported:"Live updates are not supported in this browser",liveUpdatesDisconnected:"Live updates disconnected; retrying…",fieldType:"Type:",fieldTarget:"Target:",fieldItem:"Item:",fieldCanonical:"Canonical:",fieldIntent:"Intent:",fieldDuplicates:"Duplicates:",fieldSemanticRepeats:"Semantic Repeats:",dragItemSessionPanelA11y:"Drag item session panel",debuggerTabsA11y:"Debugger tabs",sessionDataJsonA11y:"Session data JSON",environmentJsonA11y:"Environment JSON",filteredModelJsonA11y:"Filtered model JSON",sectionSessionJsonA11y:"Section session snapshot JSON",eventLevelFilterA11y:"Event level filter",controllerEventDetailsA11y:"Controller event details",instrumentationFilterA11y:"Filter instrumentation record type",instrumentationDetailsA11y:"Instrumentation record details",toggleSessionPanelA11y:"Toggle session panel",toggleEventPanelA11y:"Toggle event broadcast panel",toggleDatabasePanelA11y:"Toggle database state panel",toggleInstrumentationPanelA11y:"Toggle instrumentation panel",pnp:{title:"PNP Profile",noAssessmentBound:"No assessment bound",determinationReadOnly:"Determination (read-only)",toolsEditor:"Tools Editor",enforcement:"PNP enforcement",allAvailableTools:"All available tools",clearPlacement:"Clear placement",tool:"Tool",placement:"Placement",provider:"Provider",simulation:"PNP simulation",resolvedTools:"Resolved Tools (toolkit)",provenanceSummary:"Tool Policy Provenance Summary",perToolDecisions:"Per-Tool Decisions",policyDiagnostics:"Policy Diagnostics",profileReadOnly:"PNP Profile (read-only)"},tts:{title:"TTS settings",closeA11y:"Close TTS settings",toolbarLayoutMode:"Toolbar layout mode",reservedRow:"Reserved row",expandingRow:"Expanding row",floatingOverlay:"Floating overlay",leftAlignedControls:"Left-aligned controls",inlineSpeedButtons:"Inline speed buttons",resetToDefaults:"Reset to defaults",mathHighlighting:"Math highlighting",checkingAvailability:"Checking availability…",recheck:"Recheck",voice:"Voice",bestAvailableVoice:"Best available voice (auto)",unnamedVoice:"Unnamed voice",apiEndpoint:"API endpoint",gender:"Gender",any:"Any",male:"Male",female:"Female",neutral:"Neutral",engine:"Engine",neural:"Neural",standard:"Standard",providerDefault:"Provider default",format:"Format",sampleRate:"Sample rate",speechMarks:"Speech marks",word:"Word",wordAndSentence:"Word + sentence",voiceType:"Voice type",wavenetVoiceType:"WaveNet",studioVoiceType:"Studio",plainText:"Plain text",sampleText:"Sample text",resetSample:"Reset sample",providerAvailable:"Provider available.",providerUnavailable:"Provider unavailable.",providerCheckFailed:"Provider availability check failed.",providerNotChecked:"Provider availability has not been checked yet.",webSpeechUnavailable:"Web Speech API is not available in this browser.",browserNoVoices:"Browser text-to-speech is available, but no voices were returned yet.",browserUnavailable:"Browser text-to-speech is not available.",googleUnavailable:"Google Cloud TTS is not available from the configured API.",pollyUnavailable:"AWS Polly is not available from the configured API.",recommendedVoices:"Recommended voices",allVoices:"All available voices",previewVoice:"Preview voice",stopPreview:"Stop preview",applying:"Applying…",ssmlPreviewUnsupported:"SSML preview is not supported in the Browser backend.",pollySsmlHint:"Some Polly neural voices reject certain SSML tags (for example emphasis). Use basic SSML tags if preview fails.",mathHighlightParts:"Highlighting each part of a formula as it is read, falling back to the whole formula when alignment is uncertain.",mathHighlightBlock:"Highlighting each formula as a single block instead of breaking it into parts.",previewFailed:"Failed to play preview audio.",previewNoAudio:"Preview response did not include audio content.",previewEnterText:"Enter preview text before starting playback.",previewUnavailable:"Cannot preview while this service is unavailable.",browserSynthesisUnavailable:"Browser speech synthesis is unavailable.",browserSynthesisEndedEarly:"Browser speech synthesis ended before audio started. Restart the browser and try again.",browserSynthesisQueueFailed:"Browser speech synthesis failed to queue preview audio.",browserPreviewFailed:"Failed to play browser voice preview.",ssmlWordTrackingDisabled:"Google SSML preview preserves authored SSML, so word tracking is disabled.",applyUnavailable:"Cannot apply settings while this service is unavailable.",coordinatorUnavailable:"Toolkit coordinator is not available for text-to-speech updates."}}},yv="en-US",h6=new Set(["ar","ckb","dv","fa","he","iw","ks","ku","nqo","ps","sd","syr","ug","ur","yi"]),p6=new Set(["zero","one","two","few","many","other"]);function rk(e){if(typeof e!="object"||e===null)return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>p6.has(r))}function nk(e){try{const r=new Intl.Locale(e).textInfo;if(r?.direction==="rtl"||r?.direction==="ltr")return r.direction}catch{}const t=tf(e).split("-")[0]??"";return h6.has(t)?"rtl":"ltr"}var JP=class op{constructor(t={}){Ee(this,"locale",void 0),Ee(this,"fallbackLocale",void 0),Ee(this,"catalogs",void 0),Ee(this,"customMessages",void 0),Ee(this,"loading",void 0),Ee(this,"listeners",new Set),Ee(this,"config",void 0),this.config={...t},this.fallbackLocale=zh(t.fallbackLocale)||"en-US",this.catalogs=new Map([[yv,f6]]),this.customMessages={...t.customMessages??{}},this.loading=new Map,this.locale=this.resolveLocaleTag(t.locale)??"en-US"}async initialize(t){if(this.config={...this.config,...t},t.customMessages)for(const[r,n]of Object.entries(t.customMessages))this.addCustomMessages(r,n);await this.setLocale(t.locale??this.locale)}getLocale(){return this.locale}async setLocale(t){const r=this.resolveLocaleTag(t);if(!r){this.locale=zh(t)||"en-US",this.notify();return}if(!this.catalogs.has(r)){const n=this.loading.get(r);if(n)await n;else{const i=this.loadCatalog(r);this.loading.set(r,i);try{await i}finally{this.loading.delete(r)}}}this.locale=r,this.notify()}t(t,r){const n=this.lookup(t);return n===void 0?(this.config.onMissingKey?.(t,this.locale),t):ik(n,r)}plural(t,r){const n=this.lookupNode(t);return n===void 0||!rk(n)?this.t(t,r):ik(n[this.selectPluralCategory(r.count)]??n.other,r)}getDirection(){return nk(this.locale)}getAvailableLocales(){return[...new Set([...this.catalogs.keys(),...this.config.availableLocales??[],...Object.keys(this.customMessages)])]}isLocaleLoaded(t){const r=this.resolveLocaleTag(t);return r!==void 0&&this.catalogs.has(r)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}hasKey(t){return this.lookup(t)!==void 0}addCustomMessages(t,r){const n=zh(t);this.customMessages[n]=QP(this.customMessages[n]??{},r),this.notify()}withLocale(t){const r=this.resolveLocaleTag(t)??zh(t);if(r===this.locale)return this;const n=new op({...this.config,locale:r});return n.locale=r||"en-US",n.catalogs=this.catalogs,n.customMessages=this.customMessages,n.loading=this.loading,n}formatNumber(t,r){try{return new Intl.NumberFormat(this.locale,r).format(t)}catch{return new Intl.NumberFormat(yv,r).format(t)}}formatDate(t,r){try{return new Intl.DateTimeFormat(this.locale,r).format(t)}catch{return new Intl.DateTimeFormat(yv,r).format(t)}}getBundle(t=this.locale){const r=this.resolveLocaleTag(t);if(!r)return;const n=this.catalogs.get(r);if(n)return{locale:r,translations:n,direction:nk(r)}}resolveLocaleTag(t){if(!t)return;const r=this.getAvailableLocales(),n=d6(t,r);if(n)return n;const i=tf(t).split("-")[0];if(i)return r.find(o=>tf(o).split("-")[0]===i)}async loadCatalog(t){const r=this.config.loadCatalog;if(r)try{this.catalogs.set(t,await r(t))}catch(n){throw new Error(`Failed to load i18n catalog for locale: ${t}`,{cause:n})}}lookupNode(t){const r=[this.customMessages[this.locale],this.catalogs.get(this.locale),this.customMessages[this.fallbackLocale],this.catalogs.get(this.fallbackLocale)];for(const n of r){const i=m6(n,t);if(i!==void 0)return i}}lookup(t){const r=this.lookupNode(t);if(typeof r=="string")return r;if(r!==void 0&&rk(r))return r.other}selectPluralCategory(t){let r=op.pluralRules.get(this.locale);if(!r){try{r=new Intl.PluralRules(this.locale)}catch{return t===1?"one":"other"}op.pluralRules.set(this.locale,r)}return r.select(t)}notify(){for(const t of this.listeners)t()}};Ee(JP,"pluralRules",new Map);function zh(e){return e?e.trim().replace(/_/g,"-"):""}function m6(e,t){if(!e)return;let r=e;for(const n of t.split("."))if(typeof r!="object"||r===null||(r=r[n],r===void 0))return;return r}function ik(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>{const i=t[n];return i==null?r:String(i)}):e}function QP(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];i&&typeof i=="object"&&o&&typeof o=="object"?r[n]=QP(o,i):r[n]=i}return r}var bv;function g6(){return bv||(bv=new JP),bv}function v6(e){const t=e?.i18n??g6();return{getLocale:()=>t.getLocale(),setLocale:r=>t.setLocale(r),t:(r,n)=>t.t(r,n),plural:(r,n)=>t.plural?.(r,n)??t.t(r,n),getDirection:()=>t.getDirection?.()??"ltr",hasKey:r=>t.hasKey?.(r)??!1,subscribe:r=>t.subscribe?.(r)??(()=>{})}}var ok=ca(`<div class="pie-player-error svelte-udi90b" style="
1134
+ padding: 20px;
1135
+ margin: 20px 0;
1136
+ border-radius: 4px;
1137
+ font-family: sans-serif;
1138
+ "><h3 style="margin: 0 0 10px 0"> </h3> <p style="margin: 0"> </p></div>`),sk=ca("<div></div>"),y6=ca("<div><!> <!> <!></div>"),b6={hash:"svelte-udi90b",code:`.pie-item-player.svelte-udi90b {display:block;width:100%;}.pie-passage-container.svelte-udi90b,
1139
+ .pie-item-container.svelte-udi90b {display:block;width:100%;}.pie-item-player--resize-allowed.svelte-udi90b .pie-passage-container:where(.svelte-udi90b) {max-width:100%;overflow:auto;resize:horizontal;}
1140
+
1141
+ /*
1142
+ * The error banner carries a fixed red encoding, so it behaves like any other
1143
+ * fixed hue: exact at 0% collapse, which is every Base Theme, folded into the
1144
+ * palette at 100%, which is every scheme. Pinned, a learner on White on Black
1145
+ * or Yellow on Navy got a pale pink box in the middle of the palette they
1146
+ * chose.
1147
+ *
1148
+ * The collapsed ink is \`--pie-text\`, not \`--pie-incorrect\`: that pairs with
1149
+ * this tint at 4.14:1 under Black on White, where the page's own ink holds at
1150
+ * 6.18:1 or better on every scheme, now a declared relationship. The tint
1151
+ * itself sits about 1.1:1 from the page, so the \`--pie-incorrect\` edge is what
1152
+ * makes this read as a banner at all -- the same division of labour the
1153
+ * periodic table's collapsed cells use, and that edge clears 4.53:1 against
1154
+ * every scheme's page.
1155
+ */.pie-player-error.svelte-udi90b {border:2px solid
1156
+ color-mix(
1157
+ in srgb,
1158
+ var(--pie-incorrect, #d32f2f) var(--pie-fixed-hue-collapse, 0%),
1159
+ #d32f2f
1160
+ );background-color:color-mix(
1161
+ in srgb,
1162
+ var(--pie-incorrect-secondary, #ffebee) var(--pie-fixed-hue-collapse, 0%),
1163
+ #ffebee
1164
+ );color:color-mix(
1165
+ in srgb,
1166
+ var(--pie-text, #c62828) var(--pie-fixed-hue-collapse, 0%),
1167
+ #c62828
1168
+ );}`};function ZP(e,t){Ym(t,!0),G0(e,b6);const r=Xi("pie-item-player",()=>ki());let n=nt(t,"itemConfig",7),i=nt(t,"passageConfig",7,null),o=nt(t,"env",23,()=>({mode:"gather",role:"student"})),s=nt(t,"session",23,()=>[]),a=nt(t,"addCorrectResponse",7,!1),l=nt(t,"onCorrectResponsesPopulated",7),c=nt(t,"allowedResize",7,!1),u=nt(t,"customClassName",7,""),d=nt(t,"passageContainerClass",7,""),f=nt(t,"containerClass",7,""),h=nt(t,"bundleType",23,()=>sc.player),g=nt(t,"loaderConfig",7,pm),m=nt(t,"markupMathAssetRoot",7,void 0),v=nt(t,"mode",7,"view"),b=nt(t,"configuration",23,()=>({})),I=nt(t,"authoringBackend",7,"demo"),C=nt(t,"trustMarkup",7,!1),x=nt(t,"sanitizeMarkup",7),$=nt(t,"onInsertImage",7),P=nt(t,"onDeleteImage",7),L=nt(t,"onInsertSound",7),J=nt(t,"onDeleteSound",7),V=nt(t,"onLoadComplete",7),Y=nt(t,"onPlayerError",7),Pe=nt(t,"onSessionChanged",7),M=nt(t,"onModelUpdated",7),H=nt(t,"onModelLoaded",7),ne=nt(t,"onElementSessionUpdate",7),ae=nt(t,"baseHeadingLevel",7,void 0),ye=nt(t,"includeSrHeading",7,!0),te=nt(t,"i18n",7);const z=Ct(()=>v6({i18n:te()}));let A=nr(!1),K=nr(null),Q=nr(null),_=nr(null),B=nr(null);const U=Ct(()=>{const j=n()?.elements??{};return OI(Object.keys(j))}),fe=Ct(()=>{const j=i()?.elements??{};return OI(Object.keys(j))});function W(j,ke){return j?C()?j:x()?x()(j):q8({allowedCustomElements:ke})(j):""}const se=Ct(()=>n()?.markup?W(v()==="author"&&n().elements?zI(n().markup,n().elements):n().markup,R(U)):""),_e=Ct(()=>i()?.markup?W(v()==="author"&&i().elements?zI(i().markup,i().elements):i().markup,R(fe)):"");function Ue(j,ke="ITEM_PLAYER_RUNTIME_ERROR"){if(j&&typeof j=="object"){const Fe=j,Ve=typeof Fe.message=="string"&&Fe.message.trim().length>0?Fe.message:"Unknown PIE runtime error",Ft=typeof Fe.code=="string"&&Fe.code.trim().length>0?Fe.code:ke,Pr=Fe.recoverable===!0;return{...Fe,message:Ve,code:Ft,recoverable:Pr}}return{code:ke,message:typeof j=="string"&&j.trim().length>0?j:"Unknown PIE runtime error",recoverable:!1}}function it(j){const ke=WP({player:{loaderConfig:g()},component:"pie-item-player",debug:ki()});!Q0(ke)||!ke.isReady()||ke.trackError(new Error(j.message),{component:"pie-item-player",errorType:j.code,...j})}function le(j,ke="ITEM_PLAYER_RUNTIME_ERROR"){const Fe=Ue(j,ke);He(B,Fe.message,!0),r.error("[PieItemPlayer] Runtime error:",Fe),it(Fe),de("player-error",Fe)}const de=(j,ke)=>{j==="load-complete"&&typeof V()=="function"?V()(ke):j==="player-error"&&typeof Y()=="function"?Y()(ke):j==="session-changed"&&typeof Pe()=="function"?Pe()(ke):j==="model-updated"&&typeof M()=="function"?M()(ke):j==="model-loaded"&&typeof H()=="function"&&H()(ke)},Ne=["onInsertImage","onDeleteImage","onInsertSound","onDeleteSound"];function Ae(j){R(_)!==j&&(He(_,j,!0),le({code:"AUTHORING_BACKEND_CONFIG_ERROR",message:j}))}function ce(){if(I()==="required"){const j=[];if($()||j.push("onInsertImage"),P()||j.push("onDeleteImage"),L()||j.push("onInsertSound"),J()||j.push("onDeleteSound"),j.length>0){const ke=`Authoring backend is required but missing handlers: ${j.join(", ")}. Provide all ${Ne.join(", ")} callbacks.`;return He(Q,ke),Ae(ke),null}return{onInsertImage:$(),onDeleteImage:P(),onInsertSound:L(),onDeleteSound:J()}}return $()||P()||L()||J()?{onInsertImage:$(),onDeleteImage:P(),onInsertSound:L(),onDeleteSound:J()}:(r.warn("[PieItemPlayer] Authoring backend mode is 'demo'. Using non-production media handlers."),{onInsertImage:G8(j=>{r.debug("[PieItemPlayer] Demo image insert completed:",j)}),onDeleteImage:K8(),onInsertSound:Y8(j=>{r.debug("[PieItemPlayer] Demo sound insert completed:",j)}),onDeleteSound:X8()})}async function ie(){if(v()!=="author"||!n())return{hasErrors:!1,validatedModels:[]};const j=await Promise.all([jI(n(),b(),{container:R(re)??void 0}),i()?jI(i(),b(),{container:R(re)??void 0}):Promise.resolve({hasErrors:!1,validatedModels:[]})]);return{hasErrors:j.some(ke=>ke.hasErrors),validatedModels:j.flatMap(ke=>ke.validatedModels)}}async function De(j=!1){if(!a()||!n()||R(A)&&!j)return;if(!vF(o())){r.debug("[PieItemPlayer] Skipping populateCorrectResponses - env not suitable (mode=%s)",o().mode);return}const ke=yF(o()),Fe=[];for(const Ve of n().models){const Ft=Zm(Ve.element,h());if(r.debug("[PieItemPlayer] Controller lookup for %s: %s (createCorrectResponseSession=%s)",Ve.element,Ft?"FOUND":"NOT FOUND",Ft?"YES":"NO"),Ft&&Ft.createCorrectResponseSession)try{const Pr=await Ft.createCorrectResponseSession(Ve,ke);if(!Pr){r.debug("[PieItemPlayer] createCorrectResponseSession returned null for %s (env=%j)",Ve.element,ke);continue}const{id:en,...En}=Pr;Fe.push({id:Ve.id,element:Ve.element,...En})}catch(Pr){r.warn("[PieItemPlayer] Failed to create correct response for %s",Ve.element,Pr)}}if(s().length=0,s().push(...Fe),Fe.length>0){He(A,!0);try{Tc(n(),s(),o(),R(re)??void 0,ne(),h()),i()&&Tc(i(),s(),o(),R(re)??void 0,ne(),h())}catch(Ve){r.warn("[PieItemPlayer] Failed to update PIE elements after populating correct responses",Ve)}r.debug("[PieItemPlayer] Correct responses added to session:",s());for(const Ve of Fe)de("session-changed",{component:Ve.element,complete:!0,elementId:Ve.id,session:{id:"",data:s()}});l()?.({itemId:n().id,mode:o()?.mode,role:o()?.role,bundleType:h(),populatedCount:Fe.length,elements:Fe.map(Ve=>String(Ve.element??""))})}else r.debug("[PieItemPlayer] No correct responses returned (likely wrong env). Will retry if env/addCorrectResponse changes.")}const Je=Ct(()=>["pie-passage-container",u(),d()].filter(Boolean).join(" ")),At=Ct(()=>["pie-item-container",u(),f()].filter(Boolean).join(" ")),pt=Ct(()=>["pie-item-player",c()?"pie-item-player--resize-allowed":""].filter(Boolean).join(" "));let Et=nr(!1);function Re(j){if(!j||typeof j!="object"||Array.isArray(j))return;const ke=j;if(Array.isArray(ke.data))return;const Fe=typeof ke.id=="string"?ke.id:"";if(!Fe)return;const Ve=s().find(Ft=>Ft&&typeof Ft=="object"&&Ft.id===Fe);if(Ve!==ke){if(Ve){Object.assign(Ve,ke);return}s().push({...ke})}}function Ze(j){const ke=j,Fe=typeof ke?.id=="string"?ke.id:"";return Fe&&[n(),i()].some(Ve=>Ve?.models?.some(Ft=>Ft?.id===Fe))?Fe:""}function Ye(j){try{return j?.session}catch{return}}function yt(j){return s().find(ke=>ke&&typeof ke=="object"&&ke.id===j)}let re=nr(null),Qe=nr(null),lt=nr(null);const zt=new WeakSet,Vt=cF();function ur(j){!R(Et)||zt.has(j)||(zt.add(j),r.debug("[PieItemPlayer] model-updated event received from configure element"),de("model-updated",j.detail))}function st(j){if(j.stopPropagation(),zt.has(j))return;zt.add(j);const ke=j;r.debug("[PieItemPlayer] session-changed event received from PIE element",ke.detail);const Fe=j.target,Ve=Ze(Fe),Ft=!!ke.detail?.sessionCommitReason;if(!R(Et)&&!Ft&&Ve&&uF(Ye(Fe),yt(Ve)))return;Re(ke.detail?.session),R(Et)&&Ve&&Re(Ye(Fe)),r6(Fe);const Pr=Ve?Ye(Fe)??yt(Ve):Ye(Fe)??ke.detail?.session??s();Vt({element:Fe,complete:ke.detail?.complete,session:Pr,commit:Ft})&&de("session-changed",{...ke.detail||{},...Ve?{elementId:Ve}:{},session:{id:"",data:s()}})}Vr(()=>{if(!R(re))return;const j=R(re);return v()==="author"?(j.addEventListener("model.updated",ur,!0),()=>{j.removeEventListener("model.updated",ur,!0)}):(j.addEventListener("session-changed",st),()=>{j.removeEventListener("session-changed",st)})}),c6(()=>R(re),()=>g(),()=>ki(),"pie-item-player"),Vr(()=>{!n()||R(Et)||(r.debug("[PieItemPlayer] Item config received, initializing after DOM renders..."),r.debug("[PieItemPlayer] Mode:",v()),Jd().then(async()=>{try{if(He(B,null),r.debug("[PieItemPlayer] DOM ready, initializing PIE elements"),r.debug("[PieItemPlayer] Config:",{itemElements:Object.keys(n().elements||{}),itemModels:(n().models||[]).length,passageElements:i()?Object.keys(i().elements||{}):[],passageModels:i()?(i().models||[]).length:0,sessionLength:s().length,addCorrectResponse:a(),env:o(),mode:v()}),v()==="author"){r.debug("[PieItemPlayer] Initializing in authoring mode"),He(Q,null);const j=ce();if(R(Q)||!j){He(Et,!1);return}const ke={...o(),mode:"author",configuration:b()},Fe=BI(n(),b(),{env:ke,container:R(re)??void 0});r.debug("[PieItemPlayer] Configure elements initialized"),i()&&(Fe.push(...BI(i(),b(),{env:ke,container:R(re)??void 0})),r.debug("[PieItemPlayer] Passage configure elements initialized")),de("model-loaded",{models:Fe,configuration:b()}),R(re)&&j&&(He(K,aF(R(re),j,(Ve,Ft)=>{r.error(`[PieItemPlayer] ${Ve} failed:`,Ft)}),!0),R(K).attach(),r.debug("[PieItemPlayer] Asset event manager attached"))}else r.debug("[PieItemPlayer] Initializing in view mode"),YI(n(),[],{env:o(),bundleType:h(),container:R(re)??void 0}),r.debug("[PieItemPlayer] Item bundle initialized (bundle type: %s)",h()),i()&&(YI(i(),[],{env:o(),bundleType:h(),container:R(re)??void 0}),r.debug("[PieItemPlayer] Passage bundle initialized (bundle type: %s)",h())),r.debug("[PieItemPlayer] Updating elements with session (length="+s().length+")"),await Tc(n(),s(),o(),R(re)??void 0,ne(),h()),i()&&await Tc(i(),s(),o(),R(re)??void 0,ne(),h()),n6(R(re)??void 0);if(He(Et,!0),await Jd(),await vr(),Rt)return;r.debug("[PieItemPlayer] Initialization complete, dispatching load-complete event"),de("load-complete")}catch(j){le({code:"ITEM_PLAYER_INITIALIZATION_ERROR",message:j instanceof Error?j.message:String(j),cause:j instanceof Error?j.stack||j.message:String(j)},"ITEM_PLAYER_INITIALIZATION_ERROR")}}))});let Rt=!1;V0(()=>{Rt=!0;try{R(K)?.detach()}catch{}}),Vr(()=>{R(Et)&&(o(),a()&&!R(A)?zn(async()=>{await De()}):!a()&&R(A)&&zn(()=>{s().length=0,He(A,!1)}))});let bt=!1,ft=!1;function me(){if(R(re)?.isConnected){if(bt){ft=!0;return}bt=!0,zn(()=>{Tc(n(),s(),o(),R(re)??void 0,ne(),h()).then(()=>i()?Tc(i(),s(),o(),R(re)??void 0,ne(),h()):void 0).catch(j=>{le({code:"ITEM_PLAYER_UPDATE_ERROR",message:j instanceof Error?j.message:String(j),recoverable:!0,cause:j instanceof Error?j.stack||j.message:String(j)},"ITEM_PLAYER_UPDATE_ERROR")}).finally(()=>{bt=!1,ft&&(ft=!1,setTimeout(()=>{me()},0))})})}}Vr(()=>{!R(Et)||!o()||!n()||!s()||(r.debug("[PieItemPlayer] Dependencies changed, updating elements"),r.debug("[PieItemPlayer] Env:",o()),r.debug("[PieItemPlayer] Session (length="+s().length+"):",s()),me())}),Vr(()=>{if(!R(re))return;const j=ke=>{le(ke.detail,"PIE_CONTROLLER_RUNTIME_ERROR")};return R(re).addEventListener("pie-controller-error",j),()=>{R(re)?.removeEventListener("pie-controller-error",j)}}),Vr(()=>{if(!R(re)||v()==="author")return;const j=R(re);let ke=!1;const Fe=()=>{const en=C8(j)+_8(j);ke=en>0,r.debug("[PieItemPlayer] Post-render wrap pass wrapped",en)};if(Fe(),typeof MutationObserver>"u")return;let Ve=null;const Ft=()=>{Ve===null&&(Ve=setTimeout(()=>{Ve=null,Fe()},0))},Pr=new MutationObserver(en=>{ke&&(ke=!1,en.every(En=>R8(En)||$8(En)))||Ft()});return Pr.observe(j,{childList:!0,subtree:!0}),ke=!1,()=>{Pr.disconnect(),Ve!==null&&(clearTimeout(Ve),Ve=null)}}),Vr(()=>{if(!R(re)||v()==="author"||!n())return;const j=R(re),ke=!!i(),Fe=zn(()=>{const Ve=[HI(j,()=>({config:n(),session:s(),env:o(),bundleType:h()}))];return ke&&Ve.push(HI(j,()=>({config:i(),session:s(),env:o(),bundleType:h()}))),Ve});return()=>{for(const Ve of Fe)Ve()}});const Nt=Ct(()=>[...new Set([...R(U),...R(fe)])].join(" "));let tr=Promise.resolve();const mt=2e3;function vr(){let j;const ke=new Promise(Pr=>{j=setTimeout(Pr,mt)}),Fe=new AbortController,Ve=[n(),i()].filter(Pr=>!!Pr),Ft=v()==="author"||!R(re)?void 0:gF(R(re),Ve,Fe.signal);return Promise.race([Promise.all([tr,Ft]),ke]).then(()=>{}).finally(()=>{clearTimeout(j),Fe.abort()})}Vr(()=>{if(!R(Et)||v()==="author")return;const j=[R(Qe),R(lt)].filter(Fe=>Fe!==null);if(!(R(_e)+R(se))||j.length===0)return;const ke=new Set(R(Nt).split(" ").filter(Boolean));tr=tr.then(()=>{const Fe=IF();return HF(j.filter(Ve=>Ve.isConnected),ke,typeof Fe?.renderMath=="function"?Ve=>Fe.renderMath(Ve):Ve=>VF(Ve,m()))}).catch(Fe=>{r.warn("[PieItemPlayer] Typesetting the markup's math failed:",Fe)})});var dr={validateModels:ie,get itemConfig(){return n()},set itemConfig(j){n(j),rt()},get passageConfig(){return i()},set passageConfig(j=null){i(j),rt()},get env(){return o()},set env(j={mode:"gather",role:"student"}){o(j),rt()},get session(){return s()},set session(j=[]){s(j),rt()},get addCorrectResponse(){return a()},set addCorrectResponse(j=!1){a(j),rt()},get onCorrectResponsesPopulated(){return l()},set onCorrectResponsesPopulated(j){l(j),rt()},get allowedResize(){return c()},set allowedResize(j=!1){c(j),rt()},get customClassName(){return u()},set customClassName(j=""){u(j),rt()},get passageContainerClass(){return d()},set passageContainerClass(j=""){d(j),rt()},get containerClass(){return f()},set containerClass(j=""){f(j),rt()},get bundleType(){return h()},set bundleType(j=sc.player){h(j),rt()},get loaderConfig(){return g()},set loaderConfig(j=pm){g(j),rt()},get markupMathAssetRoot(){return m()},set markupMathAssetRoot(j=void 0){m(j),rt()},get mode(){return v()},set mode(j="view"){v(j),rt()},get configuration(){return b()},set configuration(j={}){b(j),rt()},get authoringBackend(){return I()},set authoringBackend(j="demo"){I(j),rt()},get trustMarkup(){return C()},set trustMarkup(j=!1){C(j),rt()},get sanitizeMarkup(){return x()},set sanitizeMarkup(j){x(j),rt()},get onInsertImage(){return $()},set onInsertImage(j){$(j),rt()},get onDeleteImage(){return P()},set onDeleteImage(j){P(j),rt()},get onInsertSound(){return L()},set onInsertSound(j){L(j),rt()},get onDeleteSound(){return J()},set onDeleteSound(j){J(j),rt()},get onLoadComplete(){return V()},set onLoadComplete(j){V(j),rt()},get onPlayerError(){return Y()},set onPlayerError(j){Y(j),rt()},get onSessionChanged(){return Pe()},set onSessionChanged(j){Pe(j),rt()},get onModelUpdated(){return M()},set onModelUpdated(j){M(j),rt()},get onModelLoaded(){return H()},set onModelLoaded(j){H(j),rt()},get onElementSessionUpdate(){return ne()},set onElementSessionUpdate(j){ne(j),rt()},get baseHeadingLevel(){return ae()},set baseHeadingLevel(j=void 0){ae(j),rt()},get includeSrHeading(){return ye()},set includeSrHeading(j=!0){ye(j),rt()},get i18n(){return te()},set i18n(j){te(j),rt()}},Ir=y6(),Qt=Ca(Ir),Nr=j=>{var ke=ok(),Fe=Ca(ke),Ve=Il(Fe,!0),Ft=Jc(Fe,2),Pr=Il(Ft,!0);ys(ke),$o(en=>{Tl(Ve,en),Tl(Pr,R(B))},[()=>R(z).t("player.playerError")]),lo(j,ke)};Rd(Qt,j=>{R(B)&&j(Nr)});var on=Jc(Qt,2),Or=j=>{var ke=ok(),Fe=Ca(ke),Ve=Il(Fe,!0),Ft=Jc(Fe,2),Pr=Il(Ft,!0);ys(ke),$o(en=>{Tl(Ve,en),Tl(Pr,R(Q))},[()=>R(z).t("player.authoringBackendError")]),lo(j,ke)},yr=j=>{var ke=sk();jS(ke,()=>R(_e),!0),ys(ke),Pd(ke,Fe=>He(Qe,Fe),()=>R(Qe)),$o(()=>Qc(ke,1,Xg(R(Je)),"svelte-udi90b")),lo(j,ke)};Rd(on,j=>{R(Q)?j(Or):R(_e)&&j(yr,1)});var fn=Jc(on,2),or=j=>{var ke=sk();jS(ke,()=>R(se),!0),ys(ke),Pd(ke,Fe=>He(lt,Fe),()=>R(lt)),$o(()=>Qc(ke,1,Xg(R(At)),"svelte-udi90b")),lo(j,ke)};return Rd(fn,j=>{!R(Q)&&R(se)&&j(or)}),ys(Ir),Pd(Ir,j=>He(re,j),()=>R(re)),$o(()=>Qc(Ir,1,Xg(R(pt)),"svelte-udi90b")),lo(e,Ir),Km(dr)}Y0(ZP,{itemConfig:{},passageConfig:{},env:{},session:{},addCorrectResponse:{},onCorrectResponsesPopulated:{},allowedResize:{},customClassName:{},passageContainerClass:{},containerClass:{},bundleType:{},loaderConfig:{},markupMathAssetRoot:{},mode:{},configuration:{},authoringBackend:{},trustMarkup:{},sanitizeMarkup:{},onInsertImage:{},onDeleteImage:{},onInsertSound:{},onDeleteSound:{},onLoadComplete:{},onPlayerError:{},onSessionChanged:{},onModelUpdated:{},onModelLoaded:{},onElementSessionUpdate:{},baseHeadingLevel:{},includeSrHeading:{},i18n:{}},[],["validateModels"],{mode:"open"});var w6=ca("<div></div>"),S6={hash:"svelte-18lyvta",code:`.pie-loading.svelte-18lyvta {
1169
+ /* Same spinner as the .pie-loading rules in pie-theme components.css.
1170
+ The Figma indigo is --pie-primary at 90%, so the ring follows the
1171
+ theme's primary instead of pinning MD indigo on every page. */--pie-loading-accent: color-mix(in srgb, var(--pie-primary, #3f51b5) 90%, transparent);position:absolute;height:100%;width:100%;background-color:var(--pie-white, #fff);bottom:0;left:0;right:0;top:0;z-index:9999;opacity:0.4;}.pie-loading.fixed.svelte-18lyvta {position:fixed;}.pie-loading.svelte-18lyvta:before {content:"";background-color:rgba(0, 0, 0, 0);border:5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));opacity:0.9;border-right:5px solid rgba(0, 0, 0, 0);border-left:5px solid rgba(0, 0, 0, 0);border-radius:50px;box-shadow:0 0 35px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));width:50px;height:50px;
1172
+ animation: svelte-18lyvta-spinPulse 1s infinite linear;margin:-25px 0 0 -25px;position:absolute;top:50%;left:50%;}.pie-loading.svelte-18lyvta:after {content:"";background-color:rgba(0, 0, 0, 0);border:5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));opacity:0.9;border-left:5px solid rgba(0, 0, 0, 0);border-right:5px solid rgba(0, 0, 0, 0);border-radius:50px;box-shadow:0 0 15px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));width:30px;height:30px;
1173
+ animation: svelte-18lyvta-spinoffPulse 1s infinite linear;margin:-15px 0 0 -15px;position:absolute;top:50%;left:50%;}
1174
+
1175
+ @keyframes svelte-18lyvta-spinPulse {
1176
+ 0% {
1177
+ transform: rotate(160deg);
1178
+ opacity: 0;
1179
+ box-shadow: 0 0 1px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
1180
+ }
1181
+ 50% {
1182
+ transform: rotate(145deg);
1183
+ opacity: 1;
1184
+ }
1185
+ 100% {
1186
+ transform: rotate(-320deg);
1187
+ opacity: 0;
1188
+ }
1189
+ }
1190
+
1191
+ @keyframes svelte-18lyvta-spinoffPulse {
1192
+ 0% {
1193
+ transform: rotate(0deg);
1194
+ }
1195
+ 100% {
1196
+ transform: rotate(360deg);
1197
+ }
1198
+ }`};function e_(e,t){Ym(t,!0),G0(e,S6);let r=nt(t,"fixed",7,!1);var n={get fixed(){return r()},set fixed(o=!1){r(o),rt()}},i=w6();return $o(()=>Qc(i,1,`pie-loading ${r()?"fixed":""}`,"svelte-18lyvta")),lo(e,i),Km(n)}Y0(e_,{fixed:{}},[],[],{mode:"open"});function yu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function eb(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>eb(t));if(!yu(e))return!1;for(const[t,r]of Object.entries(e))if(t==="value"||eb(r))return!0;return!1}function I6(e,t){return e.id||!t.id?e:{...e,id:t.id}}function k6(e,t){if(!yu(e)||"session"in e)return e;let r;try{r=t?.session}catch{return e}if(!yu(r))return e;let n;try{n=JSON.parse(JSON.stringify(r))}catch{return e}return{...e,session:n}}function T6(e,t,r){const n=k6(e,t);return!yu(n)||"sessionCommitReason"in n?n:{...n,sessionCommitReason:r}}function E6(e){const t=yu(e.detail)?e.detail:null;if(!t)return{action:"ignore"};if(!("session"in t)&&!ef(t)&&!eb(t))return{action:"ignore"};const r=dP({itemId:e.itemId,sessionDetail:t,previousItemSession:e.currentSession}),n=r.intent==="metadata-only",i=I6(r.session??e.currentSession,e.currentSession),o=JSON.stringify(i),s=o!==e.currentSignature;if(!s&&!n)return{action:"ignore"};const a=r.elementId&&!("elementId"in t)?{...t,elementId:r.elementId}:t;return{action:"forward",changed:s,detail:n&&!s?{...a,intent:"metadata-only",session:null}:{...a,session:i},metadataOnly:n,session:i,signature:o}}function C6(e,t){if(!e||!Array.isArray(e.data))return;const r=e.data.filter(yu);return typeof t=="string"&&t?r.find(n=>n.id===t):r.length===1?r[0]:void 0}function x6(e,t,r){const n=typeof e.component=="string",i=typeof e.complete=="boolean";if(n&&i)return e;const o=typeof e.elementId=="string"&&e.elementId?e.elementId:void 0,s=C6(t,o),a=typeof s?.id=="string"?s.id:o;return{...e,...n?{}:{component:typeof s?.element=="string"&&s.element||r(a)||""},...i?{}:{complete:X0(s??t?.data??null)}}}var R6=ca(`<div class="pie-player-error svelte-r0yfjj" style="
1199
+ padding: 20px;
1200
+ margin: 20px;
1201
+ border-radius: 4px;
1202
+ font-family: sans-serif;
1203
+ "><h3 style="margin: 0 0 10px 0"> </h3> <p style="margin: 0"> </p></div>`),P6=ca('<p class="pie-item-player-build-warning svelte-r0yfjj" role="status" aria-live="polite" aria-atomic="true"> </p>'),_6=ca('<div class="pie-item-player-loading svelte-r0yfjj"><!> <!></div>'),A6=ca("<div><!></div>"),$6=ca('<div data-pie-content=""><!></div>'),M6={hash:"svelte-r0yfjj",code:`:host {display:block;}.pie-item-player {width:100%;}.pie-player-item-container {width:100%;}.pie-item-player-loading.svelte-r0yfjj {display:flex;flex-direction:column;align-items:center;gap:12px;}.pie-item-player-build-warning.svelte-r0yfjj {margin:0;
1204
+ /* A learner can be the one reading this, so it follows the accommodation
1205
+ like any other text. Stated explicitly rather than left to inherit from
1206
+ the scaled host, to match the other content-path rules. */font-size:calc(0.95rem * var(--pie-font-scale, 1));color:var(--pie-missing, #9a6700);text-align:center;}
1207
+
1208
+ /*
1209
+ * Fixed red encoding, folded into the palette once a scheme asks for one: exact
1210
+ * pinned values at 0% collapse, which is every Base Theme. The ink collapses to
1211
+ * \`--pie-text\` rather than \`--pie-incorrect\`, which pairs with this tint at only
1212
+ * 4.14:1 under Black on White; the tint is roughly 1.1:1 from the page, so the
1213
+ * \`--pie-incorrect\` edge is what marks the banner out. Kept in step with the
1214
+ * same rule in \`players-shared\`'s \`PieItemPlayer\`.
1215
+ */.pie-player-error.svelte-r0yfjj {border:2px solid
1216
+ color-mix(
1217
+ in srgb,
1218
+ var(--pie-incorrect, #d32f2f) var(--pie-fixed-hue-collapse, 0%),
1219
+ #d32f2f
1220
+ );background-color:color-mix(
1221
+ in srgb,
1222
+ var(--pie-incorrect-secondary, #ffebee) var(--pie-fixed-hue-collapse, 0%),
1223
+ #ffebee
1224
+ );color:color-mix(
1225
+ in srgb,
1226
+ var(--pie-text, #c62828) var(--pie-fixed-hue-collapse, 0%),
1227
+ #c62828
1228
+ );}`};function t_(e,t){Ym(t,!0),G0(e,M6);let r=nt(t,"config",7,null),n=nt(t,"session",23,()=>({id:"",data:[]})),i=nt(t,"env",23,()=>({mode:"gather",role:"student"})),o=nt(t,"addCorrectResponse",7,!1),s=nt(t,"showBottomBorder",7,!1),a=nt(t,"hosted",7,void 0),l=nt(t,"debug",7,""),c=nt(t,"customClassName",7,""),u=nt(t,"containerClass",7,""),d=nt(t,"passageContainerClass",7,""),f=nt(t,"externalStyleUrls",7,""),h=nt(t,"renderStimulus",7,!0),g=nt(t,"allowedResize",7,!1),m=nt(t,"autoplayAudioEnabled",7,void 0),v=nt(t,"baseHeadingLevel",7,void 0),b=nt(t,"locale",7,""),I=nt(t,"includeSrHeading",7,!0),C=nt(t,"loaderConfig",7,WS),x=nt(t,"strategy",7,void 0),$=nt(t,"mode",7,"view"),P=nt(t,"configuration",23,()=>({})),L=nt(t,"authoringBackend",7,"demo"),J=nt(t,"backend",7,null),V=nt(t,"sessionSnapshot",7,null),Y=nt(t,"allowedStyleOrigins",7,""),Pe=nt(t,"loaderOptions",23,()=>({})),M=nt(t,"trustMarkup",7,!1),H=nt(t,"sanitizeMarkup",7,null),ne=nt(t,"onInsertImage",7,null),ae=nt(t,"onDeleteImage",7,null),ye=nt(t,"onInsertSound",7,null),te=nt(t,"onDeleteSound",7,null);const z=typeof window<"u"&&typeof document<"u",A=Ct(()=>ez(x())),K=Ct(()=>$()==="author"?"author":"view"),Q=Ct(()=>Pe()?.bundleHost||"https://proxy.pie-api.com/bundles/"),_=Ct(()=>Pe()?.esmCdnUrl||"https://cdn.jsdelivr.net/npm"),B=Ct(()=>R(A)==="esm"?a$({cdnBaseUrl:R(_),cdnProvider:Pe()?.esmCdnProvider}):void 0),U=Ct(()=>JSON.stringify(C()?.iifeBundleRetry||{})),fe=3e4,W=new Map,se=new Map;function _e(E,ue="off"){return E==="off"||E==="on"?E:ue}function Ue(E){return c$(E,{cdnBaseUrl:R(_),cdnProvider:Pe()?.esmCdnProvider})}function it(E,ue,Le){const Ge=E.supports?.[ue];if(!Ge)return!0;const ut=Ge[Le];return ut===void 0?!0:ut}function le(E){const ue=String(E||"").toLowerCase();return ue.includes("cannot find module")||ue.includes("failed to fetch dynamically imported module")||ue.includes("404")||ue.includes("runtime-support")}async function de(E,ue){if(ue!=="on")return;const Le=E,Ge=W.get(Le);if(Ge)return Ge;const ut=se.get(Le);if(ut&&Date.now()-ut<fe)return;const Ht=Ue(E);if(Ht)try{const _t=await Mr(()=>import(Ht),[],import.meta.url),rr=_t.default||_t.runtimeSupport||_t;if(!rr||typeof rr!="object")throw new Error(`Invalid runtime-support export for ${E}`);return W.set(Le,rr),se.delete(Le),rr}catch(_t){if(le(_t)){se.set(Le,Date.now());return}return}}async function Ne(E,ue,Le){if(Le!=="on")return{unsupportedPackages:[]};const Ge=[];for(const ut of Object.values(E||{})){const Ht=await de(ut,Le);if(!Ht||it(Ht,"esm",ue))continue;const{name:_t}=Sm(ut);Ge.push(_t)}return{unsupportedPackages:Ge}}const Ae=Ct(()=>{if(l()!==void 0&&l()!==null){const E=String(l()),ue=!(E.toLowerCase()==="false"||E==="0"||E==="");if(z)try{window.PIE_DEBUG=ue}catch{}return ue}return cf()}),ce=lf("pie-item-player",()=>R(Ae)),ie=Ct(()=>JB({player:{loaderConfig:C()},component:"pie-item-player",debug:R(Ae)}));let De=nr(!0),Je=nr(null),At=nr(null),pt=nr(null),Et=nr(null),Re=nr(null),Ze=nr(null),Ye=nr(null),yt=nr("pie-item-player"),re=nr(""),Qe=nr(0),lt=!1,zt=0,Vt=null,ur="",st=null,Rt=null,bt=null,ft=null,me=null;function Nt(E){let ue=E.parentElement;for(;ue;){if(ue.tagName.includes("-"))return ue;ue=ue.parentElement}return null}Vr(()=>{!R(Re)||ft||(ft=Nt(R(Re)))});function tr(E){const ue=R(Re);if(!ue)return;const Le=[],Ge=ut=>{ut.stopPropagation(),Le.push(T6(ut.detail,ut.target,E))};ue.addEventListener("session-changed",Ge,!0);try{yd(ue,{reason:E,logger:ce})}finally{ue.removeEventListener("session-changed",Ge,!0)}me=ft??R(Re);try{for(const ut of Le)try{Fr(ut)}catch(Ht){ce.warn("[pie-item-player] forwarding a committed session failed",Ht)}}finally{me=null}}V0(()=>{try{tr("teardown")}catch(E){ce.warn("[pie-item-player] session commit on teardown failed",E)}});const mt=f8({getBackend:()=>J(),getItemConfig:()=>R(pt),getPassageConfig:()=>R(Et),getEnv:()=>gt(i()),getSessionContainer:()=>Pt(),loadPlayerConfig:E=>Cr(E),dispatchPlayerEvent:E=>Mt(E),applyRefreshedConfigs:Gn}),vr=Ct(()=>mt.configOverride??r()),dr=Ct(()=>mt.sessionOverride??n());function Ir(E){const ue=E?.resources;return ue&&typeof ue=="object"?ue:null}const Qt=Ct(()=>Ir(R(pt))),Nr=Ct(()=>typeof R(Qt)?.containerClass=="string"?R(Qt).containerClass:u()),on=Ct(()=>typeof R(Qt)?.passageContainerClass=="string"?R(Qt).passageContainerClass:d());function Or(){return zt+=1,zt}function yr(E){return E===zt}const fn=Ct(()=>{const E=R(At)?.state;if(!R(At)||E!=="retrying")return null;const ue=Math.max(1,Math.ceil(R(At).elapsedMs/1e3)),Le=Math.max(1,Math.ceil(R(At).timeoutMs/1e3));return`Bundle is still building. Retrying load attempt ${R(At).attempt} (elapsed ${ue}s of ${Le}s).`});function or(E){if(typeof E=="string")try{return JSON.parse(E)}catch{return{id:"",data:[]}}return E}function j(E,ue){return(!R(Ye)||R(yt)!==E)&&(He(Ye,new d4({itemId:E,initialSession:ue}),!0),He(yt,E,!0),He(re,JSON.stringify(R(Ye).getSession()),!0),lt=!1),R(Ye)}function ke(E,ue,Le){const Ge=E.setSession(ue,{persist:!1,allowMetadataOverwrite:Le.allowMetadataOverwrite}),ut=JSON.stringify(Ge);return ut===R(re)?!1:(He(re,ut,!0),He(Qe,R(Qe)+1),lt=!1,!0)}function Fe(E){return Un(E)&&typeof E.id=="string"?E.id:""}function Ve(E){if(!R(Ye))return!1;const ue=Fe(R(Ye).getSession()),Le=Fe(E);return ue!==""&&Le!==""&&ue!==Le}function Ft(){bt=Rt;try{yd(R(Re),{reason:"navigate",logger:ce})}catch(E){ce.warn("[pie-item-player] session commit on session swap failed",E)}finally{bt=null}}function Pr(E){if(!Un(E))return!1;const ue=E.shuffledValues;if(!Un(ue))return!1;const Le="partA"in ue,Ge="partB"in ue;return(Le||Ge)&&!(Le&&Ge)}function en(E){let ue=!1;const Le=E.map(Ge=>{if(!Pr(Ge)||!Un(Ge))return Ge;const{shuffledValues:ut,...Ht}=Ge;return ue=!0,Ht});return ue?Le:E}const En=Ct(()=>(R(Qe),en(R(Ye)?R(Ye).getSession().data:EI(or(R(dr))).data)));function ri(E){return E?.markup??""}const ko=Ct(()=>ne()??mt.authoringMedia?.onInsertImage??null),ge=Ct(()=>ae()??mt.authoringMedia?.onDeleteImage??null),fr=Ct(()=>ye()??mt.authoringMedia?.onInsertSound??null),Nn=Ct(()=>te()??mt.authoringMedia?.onDeleteSound??null),_r=Ct(()=>R(K)!=="author"?"":[dm(P()),L(),Lh(R(ko)),Lh(R(ge)),Lh(R(fr)),Lh(R(Nn))].join("|")),Ji=Ct(()=>[ri(R(pt)),h()?ri(R(Et)):"",h()?"stimulus":"item-only",R(K),R(_r)].join("|")),ni=Ct(()=>c().trim()),Os=q4(),Vn=Ct(()=>c()?R(ni):Os),ua=Ct(()=>R(Vn)===R(ni)?"":R(Vn));let ns="",Qi="",Zi="",Ls="",is="";function Ri(E){if(!z||R(A)!=="preloaded")return E;const ue=_B(E);return ue!==E&&ce.debug("[pie-item-player] Normalized preloaded config.elements to bundled versions"),ue}function Un(E){return!!E&&typeof E=="object"&&!Array.isArray(E)}function O(E){return Un(E)?typeof E.markup=="string"&&Un(E.elements)&&Array.isArray(E.models):!1}function ee(E){return O(E)?{item:E,passage:null}:Un(E)&&O(E.pie)?{item:E.pie,passage:O(E.passage)?E.passage:null}:{item:E,passage:null}}function X(E){const ue=H4(Ri(E),m());return _7({config:ue}).config}function he(...E){return E.reduce((ue,Le)=>Le?.elements?{...ue,...Le.elements}:ue,{})}function gt(E){if(typeof E=="string")try{return JSON.parse(E)}catch{return{mode:"gather",role:"student"}}return E||{mode:"gather",role:"student"}}const kr=X7();let Ie=nr(0);Vr(()=>kr.subscribe(()=>{He(Ie,R(Ie)+1)})),Vr(()=>{const E=typeof b()=="string"?b().trim():"";zn(()=>{Promise.resolve(kr.setLocale(E||"en-US")).catch(()=>{})})});const et=Ct(()=>(R(Ie),kr)),jr=Ct(()=>{if(typeof v()=="number"&&Number.isInteger(v())&&v()>=1&&v()<=6)return v()}),$t=Ct(()=>a()??yP(J()));function $e(){return R(K)==="author"?Ro.editor:R($t)?Ro.player:Ro.clientPlayer}function Ar(){return PB({loadControllers:Pe()?.loadControllers,author:R(K)==="author",hosted:R($t)})}function Kr(E,ue){const Le=E===Ro.editor||E===Ro.clientPlayer&&!R($t);return{kind:"iife",bundleHost:R(Q),bundleType:E,needsControllers:Le,debugEnabled:()=>R(Ae),bundleRetry:C()?.iifeBundleRetry,trackPageActions:C()?.trackPageActions,instrumentationProvider:R(ie),onBundleRetryStatus:Ge=>{yr(ue)&&(He(At,Ge,!0),Mt(new CustomEvent("bundle-retry-status",{detail:Ge})))}}}function br(E){const ue=Pe()?.moduleResolution==="import-map"?"import-map":"url";return{kind:"esm",cdnBaseUrl:R(_),cdnProvider:Pe()?.esmCdnProvider,moduleResolution:ue,view:E||"delivery",loadControllers:Ar(),trackPageActions:C()?.trackPageActions,instrumentationProvider:R(ie)}}function Xr(){return Pe()?.view||(R(K)==="author"?"author":"delivery")}function wr(E,ue){return ue!==Ro.editor?E:Object.fromEntries(Object.entries(E).map(([Le,Ge])=>[`${Le}-config`,Ge]))}async function Cr(E){const ue=dm(E),Le=JSON.stringify({bundleHost:R(Q),esmCdnUrl:R(_),loadControllers:Ar(),moduleResolution:Pe()?.moduleResolution??"url",runtimeSupportCheck:Pe()?.runtimeSupportCheck??"off",view:Pe()?.view??null,elementPackagePolicy:Pe()?.elementPackagePolicy??null});if(ue===ns&&R(A)===Qi&&R(K)===Zi&&R(U)===Ls&&Le===is)return!0;yd(R(Re),{reason:"navigate",logger:ce});const Ge=Or(),ut=rr=>yr(Ge)?(rr(),!0):!1;if(!E)return ns=ue,Qi=R(A),Zi=R(K),Ls=R(U),is=Le,ut(()=>{He(pt,null),He(Et,null),mt.noteConfigChanged(),He(De,!0),He(Je,null),He(At,null)}),!0;ns=ue,Qi=R(A),Zi=R(K),Ls=R(U),is=Le,ut(()=>{He(De,!0),He(Je,null),He(At,null)});let Ht="start",_t=null;try{Ht="parse-config";const rr=ee(typeof E=="string"?JSON.parse(E):E);Ht="validate-config";for(const[Pi,eo]of[["item",rr.item],["passage",rr.passage]]){if(!eo)continue;P7(eo);const bc=zR(eo).warnings,Yf=Array.isArray(bc)?bc.filter(wc=>typeof wc=="string"):[];for(const wc of Yf)ce.warn(`[pie-item-player] ${Pi}: ${wc}`)}Ht="normalize-config";const Wn=X(rr.item),Yn=rr.passage?X(rr.passage):null,qa=_e(Pe()?.runtimeSupportCheck,"off"),Ns=z4(R(A),qa)?qa:"off",da=Xr(),sn=he(Wn,Yn);PT(sn,Pe()?.elementPackagePolicy);const Ds=await Ne(sn,da,Ns);if(!yr(Ge)||(_t=Ds.unsupportedPackages.length>0?` Runtime support metadata indicates esm/${da} is unsupported for ${Ds.unsupportedPackages.join(", ")}.`:null,R(A)==="iife"&&(Ht="math-rendering-init",await r$(),!yr(Ge))))return!1;if(R(A)==="preloaded"){Ht="preloaded-readiness";const Pi=$e(),eo=wr(sn,da==="author"?Ro.editor:Pi);if(MB(eo),gB(eo),Pi===Ro.clientPlayer)for(const bc of B4(Object.keys(eo)))ce.warn(F4(bc))}else if(R(A)==="iife"){Ht="iife-load";const Pi=$e();await pI(wr(sn,Pi),{backend:Kr(Pi,Ge),elementPackagePolicy:Pe()?.elementPackagePolicy})}else{Ht="esm-load";const Pi=Xr();await pI(u$(sn,Pi),{backend:br(Pi),elementPackagePolicy:Pe()?.elementPackagePolicy})}return yr(Ge)?(Ht="set-item-config",ut(()=>{He(pt,Wn,!0),He(Et,Yn,!0),mt.noteConfigChanged(),He(De,!1),He(Je,null),He(At,null)}),!0):!1}catch(rr){if(!yr(Ge))return!1;const Wn=`${rr?.message||String(rr)}${_t||""}`;ut(()=>{He(Je,`Error loading elements (${Ht}): ${Wn}`),He(De,!1),He(At,null)}),ce.error("[pie-item-player] failed loading:",rr);const Yn=aB(rr);return Mt(new CustomEvent($I.error,{detail:{code:"ITEM_PLAYER_LOAD_ERROR",message:Wn,recoverable:!1,stage:Ht,strategy:R(A),mode:R(K),...Yn?{cause:Yn}:{}}})),!1}}Vr(()=>{const E=R(vr);R(A),R(K),R(Q),R(_),R(U),Pe(),g(),m(),queueMicrotask(()=>{zn(()=>{Cr(E)})})}),Vr(()=>{const E=R(dr),ue=or(E),Le=mt.hasPendingSessionReplacement(),Ge=R(pt)?.id||"pie-item-player";zn(()=>{Ve(ue)&&Ft(),Rt=E,ke(j(Ge,ue),ue,{allowMetadataOverwrite:Le}),Le&&mt.markSessionReplacementApplied()})});const Dt=Ct(()=>Jz(Y()));Vr(()=>{if(!z)return;const E=typeof f()=="string"?f().split(",").map(_t=>_t.trim()):[],ue=R(pt)?.resources?.stylesheets;if(Array.isArray(ue))for(const _t of ue)typeof _t?.url=="string"&&E.push(_t.url);const Le=new AbortController,Ge=new Set,ut=new Set,Ht=R(Vn);for(const _t of E){if(!_t)continue;const rr=Xz(_t,{baseUrl:window.location.href,allowedOrigins:R(Dt)});if(!rr.ok){ce.error(`[pie-item-player] ${rr.message} (url=${_t})`);continue}const Wn=rr.resolvedUrl.toString();if(!ut.has(Wn)){if(ut.add(Wn),rr.resolvedUrl.origin!==window.location.origin){K4(document,_t,Wn);continue}G4({document,resolvedUrl:Wn,scopeClass:Ht,signal:Le.signal,sourceUrl:_t}).then(Yn=>{if(Yn){if(Le.signal.aborted){Yn();return}Ge.add(Yn)}}).catch(Yn=>{Le.signal.aborted||ce.error(`Failed to load external stylesheet: ${_t}`,Yn)})}}return()=>{Le.abort();for(const _t of Ge)_t();Ge.clear()}}),Vr(()=>{if(!R(Re))return;const E=R(Re);return GB({host:E,instrumentationProvider:R(ie),component:"pie-item-player",eventMap:QB,staticAttributes:{instrumentationLayer:"item"},shouldTrackEvent:ue=>ue.target===E,debug:R(Ae)})}),Vr(()=>{if(R(A)!=="preloaded"||!C()?.trackPageActions||typeof window>"u")return;const E=R(ie);return n$(window,()=>E?.isReady()?E:void 0)}),Vr(()=>{const E=R(pt);s()&&i().mode==="evaluate"&&E?.elements&&Jd().then(()=>{const ue=Object.keys(E.elements);for(const Le of ue){const Ge=R(Re)?.querySelectorAll(Le)??[];for(const ut of Ge)ut instanceof HTMLElement&&(ut.style.borderBottom="1px solid var(--pie-border-light, #ddd)",ut.style.paddingBottom="20px",ut.style.marginBottom="20px")}})});const Mt=E=>{E.type==="backend-session-saved"&&(Vt?.clear(),st=null);const ue=new CustomEvent(E.type,{detail:E.detail,bubbles:!0,composed:!0});(me??R(Re))?.dispatchEvent(ue)};function Hr(E){try{l4(bt??n(),E)}catch(ue){ce.warn("[pie-item-player] could not project the session onto the host container",ue)}}function zr(){const E=(R(pt)?.models??[]).map(ue=>typeof ue?.id=="string"?ue.id:"").filter(ue=>ue.length>0);if(E.length!==0)try{a4(n(),E)}catch(ue){ce.warn("[pie-item-player] could not seed host session entries",ue)}}function Pt(){const E=EI(or(R(dr)));return R(Ye)?R(Ye).getSession():E}function hr(){const E=J()?.delivery;return{itemId:E?.itemId||R(pt)?.id||"",sessionId:E?.sessionId||"",assignmentId:E?.assignmentId||""}}function Ur(){if(Vt)try{Vt.write(Pt())}catch(E){ce.warn("[pie-item-player] session snapshot write failed",E)}}Vr(()=>{const E=V(),ue=hr();zn(()=>{const Le=R4({config:E,identity:ue});if(Vt=Le,!Le||Le.key===ur)return;ur=Le.key;const Ge=Le.read();Ge&&(st=Ge,Mt(new CustomEvent("session-snapshot-available",{detail:{key:Ge.key,session:Ge.session,timestamp:Ge.timestamp}})))})}),Vr(()=>{if(!z)return;const E=R(Re);if(E)return I4({root:()=>E,onHidden:()=>{Ur(),mt.flushPendingSave({keepalive:!0})},logger:ce})}),Vr(()=>{if(!z)return;const E=R(Re);if(!E)return;const ue=Le=>{const Ge=Le.relatedTarget;Ge instanceof Node&&E.contains(Ge)||S4(E,{logger:ce})};return E.addEventListener("focusout",ue),()=>E.removeEventListener("focusout",ue)});async function Gn(E){He(pt,E.itemConfig,!0),He(Et,E.passageConfig,!0),await Jd(),E.itemChanged&&R(pt)&&wI(R(pt),R(En),gt(i()),R(Re)??void 0,qr,$e()),E.passageChanged&&R(Et)&&wI(R(Et),R(En),gt(i()),R(Re)??void 0,qr,$e())}async function xr(E="delivery"){return mt.load(E)}function gn(){return st}function qn(){yd(R(Re),{reason:"teardown",logger:ce})}async function S(){return mt.saveSession()}async function Z(E){return mt.score(E)}async function oe(E){return mt.saveContent(E)}async function we(E){return mt.releaseContent(E)}async function qe(){const E=R(pt);if(!E?.models?.length)return!1;const ue=gt(i()),{results:Le}=await O7(E,R(En),{container:R(Re)??document,env:{...ue,mode:"evaluate",partialScoring:ue.partialScoring},includeMissingResults:!0,bundleType:$e()});return Le}function We(E,ue=!1){if(!R(pt))throw new Error("Cannot update element model before the item config has loaded.");const Le=typeof E?.id=="string"?E.id:"";if(!Le)throw new Error("A model update requires update.id.");const Ge=R(pt).models?.findIndex(rr=>rr.id===Le)??-1;if(Ge<0)throw new Error(`No PIE model found for id "${Le}".`);const ut=R(pt).models[Ge],Ht=[...R(pt).models];Ht[Ge]=ue?{...E,id:ut.id,element:ut.element}:{...ut,...E,id:ut.id,element:ut.element};const _t={...R(pt),models:Ht};return He(pt,_t,!0),_t}function ot(E){const ue=E&&typeof E=="object"?E:null;if(ue?.update&&typeof ue.update=="object")try{We(ue.update,ue.reset===!0)}catch(Le){ce.warn("[pie-item-player] ignored model-updated state sync:",Le)}Mt(new CustomEvent("model-updated",{detail:E}))}async function Rr(){if(R(K)!=="author")return{hasErrors:!1,validatedModels:[]};if(typeof R(Ze)?.validateModels!="function")throw new Error("Cannot validate models before the authoring player has loaded.");return R(Ze).validateModels()}const qr=(E,ue,Le)=>{const Ge=j(R(pt)?.id||"pie-item-player",or(R(dr))),ut=R(re),Ht=Ge.mergeElementSession(E,Le,{persist:!1}),_t=JSON.stringify(Ht);_t!==ut&&(He(re,_t,!0),Hr(Ht),lt=!0)};function Br(E){const ue=[...R(pt)?.models??[],...R(Et)?.models??[]],Le=E?ue.find(Ge=>Ge.id===E):ue.length===1?ue[0]:void 0;return typeof Le?.element=="string"?Le.element:void 0}const Gt=(E,ue)=>{Mt(new CustomEvent("session-changed",{detail:x6(E,ue,Br)}))},Fr=E=>{const ue=R(pt)?.id||"pie-item-player",Le=j(ue,or(R(dr))),Ge=E6({detail:E,itemId:ue,currentSession:Le.getSession(),currentSignature:R(re)});if(Ge.action!=="ignore"){if(Ge.changed){const ut=Le.setSession(Ge.session,{persist:!1,allowMetadataOverwrite:!1});He(re,JSON.stringify(ut),!0),He(Qe,R(Qe)+1),lt=!1,Hr(ut),Gt({...Ge.detail,session:ut},ut),Ur(),mt.scheduleAutosave();return}if(lt){lt=!1;const{intent:ut,...Ht}=Ge.detail,_t=Le.getSession();Gt({...Ht,session:_t},_t);return}Gt(Ge.detail,Le.getSession())}};var sr={loadFromBackend:xr,getPendingSessionSnapshot:gn,commitPendingElementSessions:qn,saveSession:S,score:Z,saveContent:oe,releaseContent:we,provideScore:qe,validateModels:Rr,get config(){return r()},set config(E=null){r(E),rt()},get session(){return n()},set session(E={id:"",data:[]}){n(E),rt()},get env(){return i()},set env(E={mode:"gather",role:"student"}){i(E),rt()},get addCorrectResponse(){return o()},set addCorrectResponse(E=!1){o(E),rt()},get showBottomBorder(){return s()},set showBottomBorder(E=!1){s(E),rt()},get hosted(){return a()},set hosted(E=void 0){a(E),rt()},get debug(){return l()},set debug(E=""){l(E),rt()},get customClassName(){return c()},set customClassName(E=""){c(E),rt()},get containerClass(){return u()},set containerClass(E=""){u(E),rt()},get passageContainerClass(){return d()},set passageContainerClass(E=""){d(E),rt()},get externalStyleUrls(){return f()},set externalStyleUrls(E=""){f(E),rt()},get renderStimulus(){return h()},set renderStimulus(E=!0){h(E),rt()},get allowedResize(){return g()},set allowedResize(E=!1){g(E),rt()},get autoplayAudioEnabled(){return m()},set autoplayAudioEnabled(E=void 0){m(E),rt()},get baseHeadingLevel(){return v()},set baseHeadingLevel(E=void 0){v(E),rt()},get locale(){return b()},set locale(E=""){b(E),rt()},get includeSrHeading(){return I()},set includeSrHeading(E=!0){I(E),rt()},get loaderConfig(){return C()},set loaderConfig(E=WS){C(E),rt()},get strategy(){return x()},set strategy(E=void 0){x(E),rt()},get mode(){return $()},set mode(E="view"){$(E),rt()},get configuration(){return P()},set configuration(E={}){P(E),rt()},get authoringBackend(){return L()},set authoringBackend(E="demo"){L(E),rt()},get backend(){return J()},set backend(E=null){J(E),rt()},get sessionSnapshot(){return V()},set sessionSnapshot(E=null){V(E),rt()},get allowedStyleOrigins(){return Y()},set allowedStyleOrigins(E=""){Y(E),rt()},get loaderOptions(){return Pe()},set loaderOptions(E={}){Pe(E),rt()},get trustMarkup(){return M()},set trustMarkup(E=!1){M(E),rt()},get sanitizeMarkup(){return H()},set sanitizeMarkup(E=null){H(E),rt()},get onInsertImage(){return ne()},set onInsertImage(E=null){ne(E),rt()},get onDeleteImage(){return ae()},set onDeleteImage(E=null){ae(E),rt()},get onInsertSound(){return ye()},set onInsertSound(E=null){ye(E),rt()},get onDeleteSound(){return te()},set onDeleteSound(E=null){te(E),rt()}},k=$6(),F=Ca(k),Oe=E=>{var ue=R6(),Le=Ca(ue),Ge=Il(Le,!0),ut=Jc(Le,2),Ht=Il(ut,!0);ys(ue),$o(_t=>{Tl(Ge,_t),Tl(Ht,R(Je))},[()=>R(et).t("player.configurationError")]),lo(E,ue)},je=E=>{var ue=_6(),Le=Ca(ue);e_(Le,{});var Ge=Jc(Le,2),ut=Ht=>{var _t=P6(),rr=Il(_t,!0);$o(()=>Tl(rr,R(fn))),lo(Ht,_t)};Rd(Ge,Ht=>{R(fn)&&Ht(ut)}),ys(ue),lo(E,ue)},Se=E=>{var ue=A6(),Le=Ca(ue);g7(Le,()=>R(Ji),Ge=>{{let ut=Ct(()=>h()?R(Et):null),Ht=Ct(()=>gt(i())),_t=Ct($e),rr=Ct(()=>H()??void 0),Wn=Ct(()=>typeof P()=="string"?JSON.parse(P()):P()),Yn=Ct(()=>R(ko)??void 0),qa=Ct(()=>R(ge)??void 0),Ns=Ct(()=>R(fr)??void 0),da=Ct(()=>R(Nn)??void 0);Pd(ZP(Ge,{get itemConfig(){return R(pt)},get passageConfig(){return R(ut)},get env(){return R(Ht)},get session(){return R(En)},get addCorrectResponse(){return o()},get allowedResize(){return g()},get customClassName(){return R(ni)},get passageContainerClass(){return R(on)},get baseHeadingLevel(){return R(jr)},get includeSrHeading(){return I()},get i18n(){return R(et)},get bundleType(){return R(_t)},get loaderConfig(){return C()},get markupMathAssetRoot(){return R(B)},get mode(){return R(K)},get authoringBackend(){return L()},get trustMarkup(){return M()},get sanitizeMarkup(){return R(rr)},get configuration(){return R(Wn)},get onInsertImage(){return R(Yn)},get onDeleteImage(){return R(qa)},get onInsertSound(){return R(Ns)},get onDeleteSound(){return R(da)},onLoadComplete:sn=>{zr(),Mt(new CustomEvent("load-complete",{detail:sn}))},onPlayerError:sn=>Mt(new CustomEvent($I.error,{detail:sn})),onSessionChanged:sn=>Fr(sn),onElementSessionUpdate:qr,onModelUpdated:sn=>ot(sn),onModelLoaded:sn=>Mt(new CustomEvent("model-loaded",{detail:sn})),onCorrectResponsesPopulated:sn=>Mt(new CustomEvent("correct-responses-populated",{detail:sn}))}),sn=>He(Ze,sn,!0),()=>R(Ze))}}),ys(ue),$o(()=>Qc(ue,1,`pie-player-item-container ${R(Nr)??""}`,"svelte-r0yfjj")),lo(E,ue)};return Rd(F,E=>{R(Je)?E(Oe):R(De)||!R(pt)?E(je,1):E(Se,-1)}),ys(k),Pd(k,E=>He(Re,E),()=>R(Re)),$o(()=>Qc(k,1,`pie-item-player ${R(ni)??""} ${R(ua)??""}`,"svelte-r0yfjj")),lo(e,k),Km(sr)}Y0(t_,{config:{attribute:"config",type:"Object"},session:{attribute:"session",type:"Object"},env:{attribute:"env",type:"Object"},addCorrectResponse:{attribute:"add-correct-response",type:"Boolean"},showBottomBorder:{attribute:"show-bottom-border",type:"Boolean"},hosted:{attribute:"hosted",type:"Boolean"},debug:{attribute:"debug",type:"String"},customClassName:{attribute:"custom-class-name",type:"String"},containerClass:{attribute:"container-class",type:"String"},passageContainerClass:{attribute:"passage-container-class",type:"String"},externalStyleUrls:{attribute:"external-style-urls",type:"String"},renderStimulus:{attribute:"render-stimulus",type:"Boolean"},allowedResize:{attribute:"allowed-resize",type:"Boolean"},autoplayAudioEnabled:{attribute:"autoplay-audio-enabled",type:"Boolean"},baseHeadingLevel:{attribute:"base-heading-level",reflect:!0,type:"Number"},includeSrHeading:{attribute:"include-sr-heading",reflect:!0,type:"Boolean"},locale:{attribute:"locale",type:"String"},loaderConfig:{attribute:"loader-config",type:"Object"},strategy:{attribute:"strategy",type:"String"},mode:{attribute:"mode",type:"String"},configuration:{attribute:"configuration",type:"Object"},authoringBackend:{attribute:"authoring-backend",type:"String"},backend:{type:"Object"},sessionSnapshot:{attribute:"session-snapshot",type:"Object"},allowedStyleOrigins:{attribute:"allowed-style-origins",type:"String"},loaderOptions:{type:"Object"},trustMarkup:{attribute:"trust-markup",type:"Boolean"},sanitizeMarkup:{type:"Object"},onInsertImage:{type:"Object"},onDeleteImage:{type:"Object"},onInsertSound:{type:"Object"},onDeleteSound:{type:"Object"}},[],["loadFromBackend","getPendingSessionSnapshot","commitPendingElementSessions","saveSession","score","saveContent","releaseContent","provideScore","validateModels"],void 0,x7);D7(J7,"pie-item-player");B7("pie-item-player");var O6="pie-item-player";function L6(e=O6){const t=o$(e,t_.element,"pie-item-player tagName",{allowWrappedFallback:!0});if(t.outcome==="error"||t.outcome==="wrapped-error")throw t.error}L6();var sp=class extends Error{constructor(e,t){super(eg(t)),this.name="PreloadStageError",this.stage=e,this.cause=t}};function r_(e){return ei(e,()=>za())}function tb(e,t){return String(e?.mode??"").toLowerCase()==="author"||t?.mode==="author"}function n_(e,t){const r=e?.loaderOptions?.view;return typeof r=="string"&&r?r:tb(e,t)?"author":"delivery"}function N6(e){const t=r=>{const n=r.config?.elements||{};return!n||typeof n!="object"?"":Object.entries(n).filter(([i,o])=>typeof i=="string"&&i.trim().length>0&&typeof o=="string"&&o.trim().length>0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}=${o}`).join(",")};return e.map((r,n)=>{const i=r?.entity||{};return`${typeof i.id=="string"&&i.id||`renderable-${n}`}:${typeof i.version=="string"&&i.version||(typeof i.version=="number"?String(i.version):"")||(typeof i.config?.version=="string"?i.config.version:"")}:${t(i)}`}).join("|")}function rb(e,t){return`Error loading elements (${e}): ${eg(t)}`}function eg(e){return e instanceof Error?e.message:String(e)}function D6(e){for(const[t,r]of e.entries())try{cO(r?.config)}catch(n){const i=typeof r?.id=="string"?r.id:`renderable-${t}`,o=eg(n);throw new Error(`${i}: ${o}`)}}function j6(e,t){for(const[r,n]of e.entries()){const i=typeof n?.id=="string"?n.id:`renderable-${r}`,o=VE(n?.config).warnings,s=Array.isArray(o)?o.filter(a=>typeof a=="string"):[];for(const a of s)t.warn(rb("validate-config",`${i}: ${a}`))}}function nb(e){const t=e.resolvedPlayerProps?.loaderOptions,r=e.resolvedPlayerProps?.loaderConfig,n={trackPageActions:r?.trackPageActions,instrumentationProvider:Au({player:{loaderConfig:r},component:"pie-section-player"})};if(e.strategy==="esm"){const s=z6(t?.esmCdnProvider),a=n_(e.resolvedPlayerProps,e.resolvedPlayerEnv);return{kind:"esm",cdnBaseUrl:String(t?.esmCdnUrl||"https://cdn.jsdelivr.net/npm"),cdnProvider:s,moduleResolution:t?.moduleResolution==="import-map"?"import-map":"url",view:a,loadControllers:m5({loadControllers:typeof t?.loadControllers=="boolean"?t.loadControllers:void 0,author:tb(e.resolvedPlayerProps,e.resolvedPlayerEnv),hosted:e.resolvedPlayerProps?.hosted===!0}),...n}}const i=String(t?.bundleHost||e.iifeBundleHost||"").trim();if(!i)throw new Error("Missing iifeBundleHost for element preloading");const o=tb(e.resolvedPlayerProps,e.resolvedPlayerEnv)?qs.editor:e.resolvedPlayerProps?.hosted===!0?qs.player:qs.clientPlayer;return{kind:"iife",bundleHost:i,bundleType:o,needsControllers:o!==qs.player,bundleRetry:r?.iifeBundleRetry,onBundleRetryStatus:e.onBundleRetryStatus,...n}}function z6(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;const t=e;return typeof t.name=="string"&&typeof t.packageJsonUrl=="function"&&typeof t.browserViewUrl=="function"&&typeof t.browserControllerUrl=="function"&&typeof t.sharedDependencyUrl=="function"?e:void 0}function ak(e){return!e||e.kind!=="iife"?null:e.bundleType?String(e.bundleType):null}function lk(e){return!e||e.kind!=="iife"?"":e.bundleHost}async function B6(e){const t=e.logger??r_("pie-section-player-items-pane");try{D6(e.renderables),j6(e.renderables,t)}catch(s){throw new sp("validate-config",s)}if(e.renderables.length===0)return;const r=e.resolvedPlayerProps?.loaderOptions?.elementPackagePolicy;if(e.strategy==="preloaded"){try{const s=T1(e.renderables.map(F6));hx(s,r);const a=n_(e.resolvedPlayerProps,e.resolvedPlayerEnv)==="author"?Object.fromEntries(Object.entries(s).map(([l,c])=>[BA(l,"author"),c])):s;b5(a),r5(a)}catch(s){throw new sp("preloaded-assert",s)}return}const n=T1(e.renderables),i=nb({strategy:e.strategy,resolvedPlayerProps:e.resolvedPlayerProps,resolvedPlayerEnv:e.resolvedPlayerEnv,iifeBundleHost:e.iifeBundleHost,onBundleRetryStatus:e.onBundleRetryStatus}),o=e.strategy==="esm"?"esm-load":"iife-load";try{e.strategy==="iife"&&await l$(),await ZN(n,{backend:i,elementPackagePolicy:r})}catch(s){throw new sp(o,s)}}function F6(e){const t=e?.config;if(!t)return e;const r=g5(t);return r===t?e:{...e,config:r}}function iw(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},readinessMode:"progressive",effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,itemCount:0}}function _d(e,t){return e===t?!0:!e||!t?!1:e.sectionId===t.sectionId&&e.attemptId===t.attemptId}function ck(e){const t=e.sectionId??"";return t?{sectionId:t,attemptId:e.attemptId??""}:null}function i_(e,t){const r=t.sectionReady&&t.allLoadingComplete;return{interactionReady:e==="strict"?r:t.interactionReady,allLoadingComplete:r}}function H6(e){switch(e){case"idle":case"failed":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function Oa(e,t,r,n="entered"){const i=H6(t);i&&e.push({kind:"stage-change",stage:i,status:n,cohort:r})}function uk(e){const t={...iw(),phase:"booting-section",cohort:e.cohort,readinessMode:e.state.readinessMode,effectiveRuntime:e.effectiveRuntime,effectiveToolsConfig:e.effectiveToolsConfig,itemCount:e.itemCount},r=[];return Oa(r,"booting-section",e.cohort),{state:t,outputs:r}}function U6(e,t,r){return t==="booting-section"?(Oa(e,"engine-ready",r,"failed"),Oa(e,"interactive",r,"skipped")):Oa(e,"interactive",r,"failed"),"failed"}function q6(e,t){if(e.phase==="idle"||e.phase==="disposed")return{state:e,outputs:[]};const r=i_(t.mode,t.signals),n=[];let i=e.phase,o=e.loadingCompleteEmitted;return t.signals.runtimeError&&(i==="booting-section"||i==="engine-ready")?i=U6(n,i,e.cohort):i==="engine-ready"&&r.interactionReady&&(i="interactive",Oa(n,i,e.cohort)),r.allLoadingComplete&&e.cohort&&!o&&(o=!0,n.push({kind:"loading-complete",cohort:e.cohort,itemCount:t.itemCount})),{state:{...e,phase:i,readinessSignals:t.signals,readinessMode:t.mode,itemCount:t.itemCount,loadingCompleteEmitted:o},outputs:n}}function ap(e,t){switch(t.kind){case"initialize":return e.phase==="disposed"?{state:e,outputs:[]}:e.phase!=="idle"?_d(e.cohort,t.cohort)?ap(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig}):ap(e,{kind:"cohort-change",cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount}):uk({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});case"update-runtime":return e.phase==="idle"||e.phase==="disposed"?{state:e,outputs:[]}:{state:{...e,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig},outputs:[]};case"cohort-change":{if(e.phase==="disposed")return{state:e,outputs:[]};if(_d(e.cohort,t.cohort))return ap(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig});const r=[];e.phase!=="idle"&&r.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:e.cohort});const n=uk({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});return{state:n.state,outputs:[...r,...n.outputs]}}case"section-controller-resolved":{if(e.phase!=="booting-section")return{state:{...e,controllerResolved:!0},outputs:[]};const r=[];Oa(r,"engine-ready",e.cohort);let n="engine-ready";return i_(e.readinessMode,e.readinessSignals).interactionReady&&(n="interactive",Oa(r,n,e.cohort)),{state:{...e,phase:n,controllerResolved:!0},outputs:r}}case"update-readiness-signals":return q6(e,{signals:t.signals,mode:t.mode,itemCount:t.itemCount});case"dispose":{if(e.phase==="disposed")return{state:e,outputs:[]};const r=[];return e.phase!=="idle"&&Oa(r,"disposed",e.cohort),{state:{...e,phase:"disposed"},outputs:r}}default:return{state:e,outputs:[]}}}var W6=class{constructor(){T(this,"state",iw()),T(this,"listeners",new Set)}getState(){return this.state}dispatch(e){const t=ap(this.state,e);return this.state=t.state,t.outputs.length>0&&this.fanOut(t.outputs),t.outputs}subscribe(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}disposeListeners(){this.listeners.clear()}fanOut(e){const t=Array.from(this.listeners),r=Object.freeze(e.slice());for(const n of t)try{n(r)}catch(i){console.warn("[SectionEngineCore] listener failed:",i)}}};function V6(e){const{runtimeId:t,sourceCe:r}=e;let n=e.host;const i=e.now??(()=>new Date().toISOString());function o(c){const u={stage:c.stage,status:c.status,runtimeId:t,sectionId:c.cohort?.sectionId,attemptId:c.cohort?.attemptId?c.cohort.attemptId:void 0,timestamp:i(),sourceCe:r};Vl(n,"pie-stage-change",u)}function s(c){const u={runtimeId:t,sectionId:c.cohort.sectionId,attemptId:c.cohort.attemptId?c.cohort.attemptId:void 0,itemCount:c.itemCount,timestamp:i(),sourceCe:r};Vl(n,"pie-loading-complete",u)}function a(c){switch(c.kind){case"stage-change":o(c);return;case"loading-complete":s(c);return;default:return}}function l(c){n=c}return{dispatch:a,setHost:l}}function G6(){const e=new Set;function t(o){if(o.length===0)return;const s=Array.from(e),a=Object.freeze(o.slice());for(const l of s)try{l(a)}catch(c){console.warn("[SubscriberFanout] listener failed:",c)}}function r(o){e.add(o);let s=!0;return()=>{s&&(s=!1,e.delete(o))}}function n(){e.clear()}function i(){return e.size}return{emit:t,subscribe:r,dispose:n,getListenerCount:i}}var Y6=class{constructor(e){T(this,"core",void 0),T(this,"domEventBridge",void 0),T(this,"subscriberFanout",void 0),T(this,"unsubscribeCore",void 0),T(this,"disposed",!1),this.core=e.core??new W6,this.domEventBridge=V6({host:e.host,runtimeId:e.runtimeId,sourceCe:e.sourceCe,now:e.now}),this.subscriberFanout=G6(),this.unsubscribeCore=this.core.subscribe(t=>{this.routeOutputs(t)})}getState(){return this.core.getState()}dispatchInput(e){return this.disposed?[]:this.core.dispatch(e)}subscribe(e){return this.subscriberFanout.subscribe(e)}setHost(e){this.domEventBridge.setHost(e)}dispose(){this.disposed||(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose())}routeOutputs(e){for(const t of e)this.routeOne(t);this.subscriberFanout.emit(e)}routeOne(e){switch(e.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(e)}}};function K6(e="runtime"){return`${e}-${Math.random().toString(16).slice(2)}-${Date.now()}`}var X6=class{constructor(){T(this,"runtimeId",K6("section-engine")),T(this,"adapter",null)}attachHost(e){if(this.adapter){this.adapter.setHost(e.host);return}this.adapter=new Y6({host:e.host,runtimeId:this.runtimeId,sourceCe:e.sourceCe,now:e.now})}dispatchInput(e){return this.adapter?.dispatchInput(e)??[]}subscribe(e){return this.adapter?.subscribe(e)??J6}getState(){return this.adapter?.getState()??iw()}getRuntimeId(){return this.runtimeId}dispose(){const e=this.adapter;e&&(this.adapter=null,e.dispose())}},J6=()=>{};var o_={mode:"gather",role:"student"};function ju(e){const t=e.section?.identifier;return e.sectionId||(typeof t=="string"?t:"")||`section-${e.assessmentId||"default"}`}function Q6(e){const t=e.runtime?.tools||{},r=t.placement||{};return{...t,placement:{...r}}}function Z6(e){const t=e.runtime||{},r=t.player?{...t.player}:null;return{...t,playerType:t.playerType??"iife",player:r,lazyInit:t.lazyInit??!1,accessibility:t.accessibility??null,coordinator:t.coordinator??null,createSectionController:t.createSectionController,isolation:t.isolation??"inherit",env:t.env??o_,toolConfigStrictness:e.toolConfigStrictness??"error",tools:e.effectiveToolsConfig}}function eH(e,t){const r=Q6({runtime:e.runtime}),n=Z6({runtime:e.runtime,effectiveToolsConfig:r,toolConfigStrictness:e.toolConfigStrictness});return{effectiveToolsConfig:r,effectiveRuntime:n,playerRuntime:t.resolvePlayerRuntime({effectiveRuntime:n,playerType:String(n.playerType??"iife"),env:n.env??null})}}var dk={iife:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"iife"},props:{loaderOptions:{bundleHost:uO}}},esm:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"esm"},props:{loaderOptions:{esmCdnUrl:dO}}},preloaded:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"preloaded"}}};function tH(e){return e.hosted!==void 0}function rH(e){const t=e.backend;return!!t?.delivery&&t.delivery.enabled!==!1}function nH(e){const t=String(e.effectiveRuntime?.playerType||e.playerType||"iife"),r=dk[t]||dk.iife,n=r?.tagName||"pie-item-player",i=r?.attributes||{},o=r?.props||{},s=e.effectiveRuntime?.player||{},a=o.loaderOptions||{},l=s.loaderOptions||{},c=!tH(s)&&rH(s)?{hosted:!0}:{};return{effectivePlayerType:t,resolvedPlayerDefinition:r,resolvedPlayerTag:n,resolvedPlayerAttributes:i,resolvedPlayerProps:{...o,...c,...s,loaderOptions:{...a,...l}},resolvedPlayerEnv:e.effectiveRuntime?.env||e.env||{},strategy:DL(i?.strategy||t,"iife")}}function iH(e){return e.map(t=>t?.entity)}function oH(e){return eH(e,{resolvePlayerRuntime:nH})}function ib(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ia(e){return e&&{...e}}function sH(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:e}function bu(e){return e&&Object.fromEntries(Object.entries(e).map(([t,r])=>[t,sH(r)]))}function Sa(e){if(e)return{...e,auth:ia(e.auth),endpoints:bu(e.endpoints),request:e.request?{...e.request,headers:e.request.headers?{...e.request.headers}:void 0}:void 0,options:e.options?{...e.options,overrides:e.options.overrides?{...e.options.overrides}:void 0}:void 0,autosave:e.autosave&&typeof e.autosave=="object"?{...e.autosave}:e.autosave,client:e.client?{...e.client}:void 0}}function bd(e){if(e)return{...e,auth:ia(e.auth),endpoints:bu(e.endpoints),request:e.request?{...e.request,headers:e.request.headers?{...e.request.headers}:void 0}:void 0,media:e.media?{...e.media}:void 0,client:e.client?{...e.client}:void 0}}function rf(e){return{...e,auth:ia(e.auth),delivery:Sa(e.delivery),authoring:bd(e.authoring)}}function aH(e,t){if(!e)return Sa(t);if(!t)return Sa(e);const r=e.client,n=t.client,i=r||n?{...r||{},...n||{}}:void 0;return{...Sa(e),...Sa(t),auth:t.auth?ia(t.auth):ia(e.auth),endpoints:{...bu(e.endpoints)||{},...bu(t.endpoints)||{}},request:e.request||t.request?{...e.request||{},...t.request||{},headers:{...e.request?.headers||{},...t.request?.headers||{}}}:void 0,options:e.options||t.options?{...e.options||{},...t.options||{},overrides:{...e.options?.overrides||{},...t.options?.overrides||{}}}:void 0,autosave:t.autosave!==void 0?Sa({autosave:t.autosave})?.autosave:Sa({autosave:e.autosave})?.autosave,client:i}}function lH(e,t){return e?t?{...bd(e),...bd(t),auth:t.auth?ia(t.auth):ia(e.auth),endpoints:{...bu(e.endpoints)||{},...bu(t.endpoints)||{}},request:e.request||t.request?{...e.request||{},...t.request||{},headers:{...e.request?.headers||{},...t.request?.headers||{}}}:void 0,media:e.media||t.media?{...e.media||{},...t.media||{}}:void 0,client:e.client||t.client?{...e.client||{},...t.client||{}}:void 0}:bd(e):bd(t)}function cH(e,t){return{...rf(e),...rf(t),auth:t.auth?ia(t.auth):ia(e.auth),delivery:aH(e.delivery,t.delivery),authoring:lH(e.authoring,t.authoring)}}function uH(e){const t=rf(e.backend);if(!t.delivery||t.delivery.enabled===!1)return t;const r=Sa(t.delivery);r.itemId=e.canonicalItemId||e.itemId;const n=e.itemSession?.id;return typeof n=="string"&&n?r.sessionId=n:delete r.sessionId,t.delivery=r,t}function dH(e){const{backend:t,resolveBackend:r,...n}=e.resolvedPlayerProps;if(!t||!ib(t))return n;const i=String(e.item?.id||""),o=uH({backend:t,itemId:i,canonicalItemId:e.canonicalItemId,itemSession:e.itemSession});let s=o;if(typeof r=="function"){const a=rf(o),l=r({itemId:i,canonicalItemId:e.canonicalItemId,item:e.item,itemIndex:e.itemIndex??0,itemSession:e.itemSession,sectionId:e.sectionId,env:e.env,baseBackend:a},a);l&&ib(l)&&(s=cH(o,l))}return{...n,backend:s}}function fH(e){const{backend:t,resolveBackend:r,...n}=e;if(!t||!ib(t))return n;const{delivery:i,...o}=rf(t);return Object.keys(o).length===0?n:{...n,backend:o}}var hH=4,fk=new Set;function ow(e){const t=typeof e=="number"?e:Number.parseInt(String(e??""),10);return!Number.isInteger(t)||t<1||t>6?2:(t>hH&&!fk.has(t)&&(fk.add(t),console.warn(`[pie-section-player] baseHeadingLevel=${t} leaves no room to nest: passage sub-content clamps at h6 and the outline flattens. Levels 1-4 keep the full structure.`)),t)}function pH(e){return{baseHeadingLevel:e,includeSrHeading:!1}}function mH(e){return{baseHeadingLevel:Math.min(6,e+1)}}function gH(e){return e.detail?.composition||$0}function s_(e){const t=iH(e.renderables||[]);return{compositionModel:e,passages:e.passages||[],items:e.items||[],renderables:t,renderablesSignature:N6(e.renderables||[])}}function vH(e){return s_(gH(e))}function yH(e){return{config:e.passage.config||{},env:e.resolvedPlayerEnv,attributes:{...e.resolvedPlayerAttributes||{},strategy:e.playerStrategy},props:{...mH(e.baseHeadingLevel??2),...fH(e.resolvedPlayerProps||{})}}}function bH(e){const t=e.compositionModel?.formative;if(!t?.enabled)return null;const r=t.policies?.[e.canonicalItemId];return r?.enabled?Lj({policy:r,state:t.states?.[e.canonicalItemId]}):null}function wH(e){const t=e.compositionModel?.timedMedia;if(!t)return null;const r=t.sequencedItemIds.includes(e.canonicalItemId)&&!t.revealedItemIds.includes(e.canonicalItemId),n=t.gate,i=n?.holding===!0&&n.itemRefs.includes(e.canonicalItemId);return{pending:r,isGateTarget:i,gateEnforced:i&&n?.enforcement==="enforced"}}function SH(e,t){const r=t?.envOverride;return r?{...e,...r}:e}function IH(e){const t=Array.isArray(e.data)?e.data:[];return{...e,data:t.map(r=>r&&typeof r=="object"?{...r}:r)}}function kH(e){const t=Fx(e.compositionModel,e.item),r=Vj(e.compositionModel,e.item),n=Bx(e.compositionModel,e.item),i=SH(e.resolvedPlayerEnv,e.formativeView);return{config:e.item.config||{},env:i,session:IH(r),attributes:{...e.resolvedPlayerAttributes||{},strategy:e.playerStrategy},props:dH({resolvedPlayerProps:{...pH(e.baseHeadingLevel??2),...e.resolvedPlayerProps||{}},item:e.item,canonicalItemId:n,itemSession:t&&typeof t=="object"?t:void 0,itemIndex:e.itemIndex,sectionId:e.compositionModel.section?.identifier,env:e.resolvedPlayerEnv})}}function hk(e){return Bx(e.compositionModel,e.item)}function TH(e){return Wj(e.compositionModel,e.item)}var a_=Cu(Symbol.for("@pie-players/pie-section-player/card-render-context"));function l_(e,t){return af(e,a_,t)}function EH(e,t){const r=new Ql(e,{context:a_,initialValue:t});return r.connect(),{setValue:n=>r.setValue(n),disconnect:()=>r.disconnect()}}function oa(e){if(!e)return null;const t=e.parentNode;return t?.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t?t.host:e.parentElement}var pk="content-media",c_="content-lead";function nf(e,t=20,r=55){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):34}function CH(e){const t=e.containerWidthPx;if(!Number.isFinite(t)||t<=0)return nf(e.startPercent,e.min,e.max);const r=e.deltaX/t*100;return nf(e.startPercent-r,e.min,e.max)}var xH=Wt('<div role="separator" aria-orientation="vertical" tabindex="0"><span class="pie-section-player-card-split-divider__handle svelte-xekreg"></span></div>'),RH={hash:"svelte-xekreg",code:`.pie-section-player-card-split-divider.svelte-xekreg {align-self:stretch;position:relative;display:flex;align-items:center;justify-content:center;
1229
+ /* Wide enough for a 24px pointer target while the visible rule stays
1230
+ hairline; the grid track is sized to match. */min-width:24px;cursor:col-resize;background:transparent;user-select:none;touch-action:none;}.pie-section-player-card-split-divider.svelte-xekreg:focus {outline:none;}.pie-section-player-card-split-divider.svelte-xekreg:focus-visible {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:-2px;border-radius:999px;}.pie-section-player-card-split-divider__handle.svelte-xekreg {width:4px;height:48px;max-height:60%;border-radius:2px;background:var(--pie-border-light, #e5e7eb);transition:background 0.2s ease;pointer-events:none;}.pie-section-player-card-split-divider.svelte-xekreg:hover .pie-section-player-card-split-divider__handle:where(.svelte-xekreg),
1231
+ .pie-section-player-card-split-divider.svelte-xekreg:focus-visible .pie-section-player-card-split-divider__handle:where(.svelte-xekreg),
1232
+ .pie-section-player-card-split-divider--dragging.svelte-xekreg .pie-section-player-card-split-divider__handle:where(.svelte-xekreg) {background:var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));}
1233
+
1234
+ @media (prefers-reduced-motion: reduce) {.pie-section-player-card-split-divider__handle.svelte-xekreg {transition:none;}
1235
+ }`};function u_(e,t){pn(t,!0),Ln(e,RH);let r=D(t,"value",7,34),n=D(t,"min",7,20),i=D(t,"max",7,55),o=D(t,"step",7,5),s=D(t,"container",7,null),a=D(t,"ariaLabel",7,"Resize media region"),l=D(t,"ariaControls",7,""),c=D(t,"ariaValueText",7,""),u=D(t,"onresize",7,(L,J)=>{}),d=Be(!1),f=0,h=0,g=0,m=0;function v(L){L.button!==0&&L.pointerType==="mouse"||(L.preventDefault(),be(d,!0),f=L.clientX,h=r(),m=r(),g=s()?.getBoundingClientRect().width??0,L.currentTarget?.setPointerCapture?.(L.pointerId))}function b(L){p(d)&&u()(CH({startPercent:h,deltaX:L.clientX-f,containerWidthPx:g,min:n(),max:i()}),"pointer")}function I(){p(d)&&be(d,!1)}function C(){p(d)&&(be(d,!1),u()(nf(m,n(),i()),"pointer"))}function x(L){if(L.key!=="ArrowLeft"&&L.key!=="ArrowRight"&&L.key!=="Home"&&L.key!=="End"&&L.key!=="Escape")return;if(L.preventDefault(),L.key==="Escape"){C();return}let J=r();L.key==="Home"?J=i():L.key==="End"?J=n():J=nf(r()+(L.key==="ArrowLeft"?o():-o()),n(),i()),u()(J,"keyboard")}vt(()=>{if(!(!p(d)||typeof window>"u"))return window.addEventListener("pointermove",b),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",C),()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",C)}});var $={get value(){return r()},set value(L=34){r(L),N()},get min(){return n()},set min(L=20){n(L),N()},get max(){return i()},set max(L=55){i(L),N()},get step(){return o()},set step(L=5){o(L),N()},get container(){return s()},set container(L=null){s(L),N()},get ariaLabel(){return a()},set ariaLabel(L="Resize media region"){a(L),N()},get ariaControls(){return l()},set ariaControls(L=""){l(L),N()},get ariaValueText(){return c()},set ariaValueText(L=""){c(L),N()},get onresize(){return u()},set onresize(L=(J,V)=>{}){u(L),N()}},P=xH();return ve(L=>{yn(P,1,`pie-section-player-card-split-divider ${p(d)?"pie-section-player-card-split-divider--dragging":""}`,"svelte-xekreg"),at(P,"aria-label",a()),at(P,"aria-controls",l()||void 0),at(P,"aria-valuemin",n()),at(P,"aria-valuemax",i()),at(P,"aria-valuenow",L),at(P,"aria-valuetext",c()||void 0)},[()=>Math.round(r())]),fo("pointerdown",P,v),fo("keydown",P,x),ht(e,P),mn($)}Pu(["pointerdown","keydown"]);Tn(u_,{value:{},min:{},max:{},step:{},container:{},ariaLabel:{},ariaControls:{},ariaValueText:{},onresize:{}},[],[],{mode:"open"});var PH={calculator:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm0 2v4h10V4H7Zm0 6v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Z" fill="currentColor"/></svg>',"volume-up":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 3.23v2.06A7.002 7.002 0 0 1 19 12a7 7 0 0 1-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77Zm-2 17.75V3L7 8H3v8h4l5 5Zm4.5-9a4.5 4.5 0 0 0-2.5-4.03v8.05A4.5 4.5 0 0 0 16.5 12Z" fill="currentColor"/></svg>',swatch:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 3a9 9 0 1 0 9 9c0-.55-.45-1-1-1h-2.5a1.5 1.5 0 0 1 0-3H20a1 1 0 0 0 1-1 8.99 8.99 0 0 0-9-4Zm-5.5 9A1.5 1.5 0 1 1 8 13.5 1.5 1.5 0 0 1 6.5 12Zm3-4A1.5 1.5 0 1 1 11 9.5 1.5 1.5 0 0 1 9.5 8Zm5 0A1.5 1.5 0 1 1 16 9.5 1.5 1.5 0 0 1 14.5 8Z" fill="currentColor"/></svg>',"chart-bar":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4.75 5a.76.76 0 0 1 .75.75v11c0 .438.313.75.75.75h13a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-13C5 19 4 18 4 16.75v-11A.74.74 0 0 1 4.75 5ZM8 8.25a.74.74 0 0 1 .75-.75h6.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-6.5A.722.722 0 0 1 8 8.25Zm.75 2.25h4.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-4.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Zm0 3h8.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-8.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Z" fill="currentColor"/></svg>',beaker:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 21c-.85 0-1.454-.38-1.813-1.137-.358-.759-.27-1.463.263-2.113L9 11V5H8a.968.968 0 0 1-.713-.287A.968.968 0 0 1 7 4c0-.283.096-.52.287-.712A.968.968 0 0 1 8 3h8c.283 0 .52.096.712.288.192.191.288.429.288.712s-.096.52-.288.713A.968.968 0 0 1 16 5h-1v6l5.55 6.75c.533.65.62 1.354.262 2.113C20.454 20.62 19.85 21 19 21H5Zm2-3h10l-3.4-4h-3.2L7 18Zm-2 1h14l-6-7.3V5h-2v6.7L5 19Z" fill="currentColor"/></svg>',protractor:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m6.75 21-.25-2.2 2.85-7.85a3.95 3.95 0 0 0 1.75.95l-2.75 7.55L6.75 21Zm10.5 0-1.6-1.55-2.75-7.55a3.948 3.948 0 0 0 1.75-.95l2.85 7.85-.25 2.2ZM12 11a2.893 2.893 0 0 1-2.125-.875A2.893 2.893 0 0 1 9 8c0-.65.188-1.23.563-1.737A2.935 2.935 0 0 1 11 5.2V3h2v2.2c.583.2 1.063.554 1.438 1.063C14.812 6.77 15 7.35 15 8c0 .833-.292 1.542-.875 2.125A2.893 2.893 0 0 1 12 11Zm0-2c.283 0 .52-.096.713-.287A.967.967 0 0 0 13 8a.967.967 0 0 0-.287-.713A.968.968 0 0 0 12 7a.968.968 0 0 0-.713.287A.967.967 0 0 0 11 8c0 .283.096.52.287.713.192.191.43.287.713.287Z" fill="currentColor"/></svg>',"bars-3":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.85 15c.517 0 .98-.15 1.388-.45.408-.3.695-.692.862-1.175l.375-1.15c.267-.8.2-1.537-.2-2.213C8.875 9.337 8.3 9 7.55 9H4.025l.475 3.925c.083.583.346 1.075.787 1.475.442.4.963.6 1.563.6Zm10.3 0c.6 0 1.12-.2 1.563-.6.441-.4.704-.892.787-1.475L19.975 9h-3.5c-.75 0-1.325.342-1.725 1.025-.4.683-.467 1.425-.2 2.225l.35 1.125c.167.483.454.875.862 1.175.409.3.871.45 1.388.45Zm-10.3 2c-1.1 0-2.063-.363-2.887-1.088a4.198 4.198 0 0 1-1.438-2.737L2 9H1V7h6.55c.733 0 1.404.18 2.013.537A3.906 3.906 0 0 1 11 9h2.025c.35-.617.83-1.104 1.438-1.463A3.892 3.892 0 0 1 16.474 7H23v2h-1l-.525 4.175a4.198 4.198 0 0 1-1.438 2.737A4.238 4.238 0 0 1 17.15 17c-.95 0-1.804-.27-2.562-.813A4.234 4.234 0 0 1 13 14.026l-.375-1.125a21.35 21.35 0 0 1-.1-.363 4.926 4.926 0 0 1-.1-.537h-.85c-.033.2-.067.363-.1.488a21.35 21.35 0 0 1-.1.362L11 14a4.3 4.3 0 0 1-1.588 2.175A4.258 4.258 0 0 1 6.85 17Z" fill="currentColor"/></svg>',ruler:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m8.8 10.95 2.15-2.175-1.4-1.425-1.1 1.1-1.4-1.4 1.075-1.1L7 4.825 4.825 7 8.8 10.95Zm8.2 8.225L19.175 17l-1.125-1.125-1.1 1.075-1.4-1.4 1.075-1.1-1.425-1.4-2.15 2.15L17 19.175ZM7.25 21H3v-4.25l4.375-4.375L2 7l5-5 5.4 5.4 3.775-3.8c.2-.2.425-.35.675-.45a2.068 2.068 0 0 1 1.55 0c.25.1.475.25.675.45L20.4 4.95c.2.2.35.425.45.675.1.25.15.508.15.775a1.975 1.975 0 0 1-.6 1.425l-3.775 3.8L22 17l-5 5-5.375-5.375L7.25 21ZM5 19h1.4l9.8-9.775L14.775 7.8 5 17.6V19Z" fill="currentColor"/></svg>',"book-open":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 6.25a6.6 6.6 0 0 0-2.3-1.32A8.6 8.6 0 0 0 7 4.5c-.63 0-1.25.06-1.85.18-.6.12-1.19.3-1.76.54a1.5 1.5 0 0 0-.93 1.4v10.1c0 .52.26.98.68 1.24.42.26.92.28 1.35.06.36-.18.75-.31 1.18-.4.42-.09.86-.13 1.33-.13.78 0 1.53.14 2.24.42.7.28 1.35.7 1.93 1.24l.83-.75.83.75c.58-.54 1.22-.96 1.93-1.24a6.1 6.1 0 0 1 2.24-.42c.47 0 .91.04 1.33.13.43.09.82.22 1.18.4.43.22.93.2 1.35-.06.42-.26.68-.72.68-1.24V6.62c0-.6-.36-1.15-.93-1.4a9.3 9.3 0 0 0-1.76-.54A9.8 9.8 0 0 0 17 4.5a8.6 8.6 0 0 0-2.7.43A6.6 6.6 0 0 0 12 6.25Zm1 10.06V8.02c.55-.5 1.16-.88 1.84-1.13A6 6 0 0 1 17 6.5c.45 0 .89.04 1.32.11.43.08.85.19 1.26.34v9.24a8.2 8.2 0 0 0-1.28-.24A10 10 0 0 0 17 15.85c-.72 0-1.42.09-2.09.26a7.7 7.7 0 0 0-1.91.8Zm-2 0a7.7 7.7 0 0 0-1.91-.8 8.4 8.4 0 0 0-2.09-.26c-.44 0-.87.02-1.3.07-.43.05-.86.13-1.28.24V6.95c.41-.15.83-.26 1.26-.34A7.7 7.7 0 0 1 7 6.5c.76 0 1.48.13 2.16.39.68.25 1.29.63 1.84 1.13Z" fill="currentColor"/></svg>',photo:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 21c-.55 0-1.02-.2-1.41-.59A1.93 1.93 0 0 1 2 19V5c0-.55.2-1.02.59-1.41A1.93 1.93 0 0 1 4 3h16c.55 0 1.02.2 1.41.59.39.39.59.86.59 1.41v14c0 .55-.2 1.02-.59 1.41-.39.39-.86.59-1.41.59H4Zm0-2h16V5H4v14Zm1.5-2.5h13l-4.1-5.47-3.4 4.47-2.5-3.25L5.5 16.5ZM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z" fill="currentColor"/></svg>'};function _H(e){return PH[e]||null}function AH(e,t){let r=null;try{const o=t.policyFor(e.toolId);if(o.outcome==="denied")return null;o.outcome==="granted"&&(r=o)}catch(o){return t.onError?.(e,"policy",o),null}if(!r&&!e.resolvesWithoutGrant)return null;if(!e.requiresAuthoredContent)return r?{registration:e,granted:!0,parameters:r.parameters,content:null}:null;const n={parameters:r?.parameters,catalogs:t.catalogs,granted:!!r};let i;try{i=e.requiresAuthoredContent.resolve(n)}catch(o){return t.onError?.(e,"content",o),null}return i==null?null:{registration:e,granted:n.granted,parameters:n.parameters,content:i}}function $H(e){return e.registrations.flatMap(t=>{const r=AH(t,e);return r?[r]:[]})}function MH(e){if(e.ownerKind==="itemModel")return{level:"item",scopeId:e.canonicalItemId||e.itemId,itemId:e.itemId,canonicalItemId:e.canonicalItemId}}var OH=["section","item","passage"];function d_(e){const t=new Set;function r(i,o){if(i===null||typeof i=="string"||typeof i=="boolean")return i;if(typeof i=="number")return Number.isFinite(i)?i:null;if(!(typeof i>"u")){if(typeof i=="function"||typeof i=="symbol")throw new TypeError(`${o} is not JSON-serializable`);if(typeof i=="bigint")throw new TypeError(`${o} is not JSON-serializable`);if(typeof i!="object")throw new TypeError(`${o} is not JSON-serializable`);if(t.has(i))throw new TypeError(`${o} contains a cycle`);t.add(i);try{if(Array.isArray(i))return i.map((c,u)=>r(c,`${o}[${u}]`)??null);const s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new TypeError(`${o} must contain only plain objects and arrays`);const a=i,l={};for(const c of Object.keys(a).sort()){const u=r(a[c],`${o}.${c}`);u!==void 0&&(l[c]=u)}return l}finally{t.delete(i)}}}const n=JSON.stringify(r(e,"content"));if(n===void 0)throw new TypeError("content is not JSON-serializable");return n}function f_(e,t){if(e.kind!==t.kind)return!1;if(e.kind==="section"&&t.kind==="section")return e.assessmentId===t.assessmentId&&e.sectionId===t.sectionId;if(e.kind==="content"&&t.kind==="content"){const r=e.ownerContext,n=t.ownerContext;return r.ownerKind===n.ownerKind&&r.assessmentId===n.assessmentId&&r.sectionId===n.sectionId&&r.canonicalItemId===n.canonicalItemId&&r.itemId===n.itemId&&r.passageId===n.passageId&&r.modelId===n.modelId}return!1}function LH(e,t){return e.anchor===t.anchor&&e.surface===t.surface&&e.registry===t.registry&&e.services.toolkitCoordinator===t.services.toolkitCoordinator&&e.services.ttsService===t.services.ttsService&&e.services.catalogResolver===t.services.catalogResolver&&f_(e.scope,t.scope)}function NH(e,t){return e.registry===t.registry&&e.services.toolkitCoordinator===t.services.toolkitCoordinator&&e.services.catalogResolver===t.services.catalogResolver&&f_(e.scope,t.scope)}function mk(e){try{return d_({toolId:e.toolId,granted:e.granted,surface:e.surface,parameters:e.parameters??null,content:e.content??null})}catch{return null}}function DH(e,t){return e.contextSignature===null||t.contextSignature===null||e.contextSignature!==t.contextSignature?!1:e.context.services.toolkitCoordinator===t.context.services.toolkitCoordinator&&e.context.services.ttsService===t.context.services.ttsService&&e.context.services.catalogResolver===t.context.services.catalogResolver}function sw(e,t){const{hostLabel:r}=t;let n=null,i=!1,o={mountable:!1,occupied:!1},s=null,a=null,l=null,c=null;const u=new Map,d=new Map,f=new Map,h=new Set;function g(M){M.mountable===o.mountable&&M.occupied===o.occupied||(o=M,e({...M}))}function m(M,H,ne,ae){const ye=n,te=`${ye?.surface??"unknown"}\0${M}\0${H}\0${ne}`;if(h.has(te))return;h.add(te);const z=P0({kind:"tool-surface",severity:"warning",source:`${r}/tool-surface-host`,message:ne,details:[`surface=${ye?.surface??"unknown"}`,`toolId=${M}`,`phase=${H}`],recoverable:!0,cause:ae}),A=ye?.services.toolkitCoordinator;if(typeof A?.reportFrameworkError=="function")try{A.reportFrameworkError(z);return}catch(K){console.warn(`[${r}] tool surface warning reporter failed:`,K)}if(ye?.anchor&&typeof CustomEvent=="function"){ye.anchor.dispatchEvent(new CustomEvent("framework-error",{detail:z,bubbles:!0,composed:!0}));return}console.warn(`[${r}] ${ne}`,ae)}function v(M){const H=u.get(M);if(H){u.delete(M);try{H.destroy?.()}catch(ne){m(M,"destroy",`Tool "${M}" failed while leaving the "${n?.surface??"unknown"}" surface.`,ne)}finally{try{H.element.remove()}catch(ne){try{H.element.parentNode?.removeChild(H.element)}catch{}m(M,"destroy",`Tool "${M}" failed DOM removal from the "${n?.surface??"unknown"}" surface.`,ne)}}}}function b(){for(const M of[...u.keys()])v(M)}function I(M,H,ne){if(M.scope.kind!=="content")return null;const ae=M.services.toolkitCoordinator,ye=MH(M.scope.ownerContext),[te]=$H({registrations:[H],catalogs:ne,policyFor:A=>{const K=ae?.decideFeaturePolicy?.(A,ye);return gj(K)?{outcome:"denied"}:K?.granted===!0?{outcome:"granted",parameters:K.parameters}:{outcome:"silent"}},onError:(A,K,Q)=>{m(A.toolId,"resolve",K==="policy"?`Tool "${A.toolId}" failed policy resolution for the "${M.surface}" surface.`:`Tool "${A.toolId}" failed authored-content resolution for the "${M.surface}" surface.`,Q)}});if(!te)return null;if(te.content!==null)try{d_(te.content)}catch(A){return m(H.toolId,"resolve",`Tool "${H.toolId}" failed authored-content resolution for the "${M.surface}" surface.`,A),null}const z={toolId:H.toolId,granted:te.granted,surface:M.surface,parameters:te.parameters,content:te.content,services:M.services};return{registration:H,context:z,contextSignature:mk(z)}}function C(M,H){if(M.scope.kind!=="section")return null;if(H.requiresAuthoredContent)return m(H.toolId,"resolve",`Tool "${H.toolId}" declares authored content that the section-scoped "${M.surface}" surface cannot resolve.`),null;const ne=M.services.toolkitCoordinator;if(!ne)return null;let ae=!1,ye;try{if(H.activation==="region"){const z=ne.decideFeaturePolicy?.(H.toolId);if(z?.granted!==!0)return null;ae=!0,ye=z.parameters}else{const z=M.scope.sectionId||"*";let A=!1;for(const K of OH){const Q=ne.decideToolPolicy({level:K,scope:{level:K,scopeId:z,assessmentId:M.scope.assessmentId,sectionId:M.scope.sectionId||void 0}}).visibleTools.find(_=>_.toolId===H.toolId);if(Q){A=!0,ae=Q.required||Q.alwaysAvailable,ye=Q.settings;break}}if(!A)return null}}catch(z){return m(H.toolId,"resolve",`Tool "${H.toolId}" failed policy resolution for the "${M.surface}" surface.`,z),null}const te={toolId:H.toolId,granted:ae,surface:M.surface,parameters:ye,services:M.services};return{registration:H,context:te,contextSignature:mk(te)}}function x(M){const H=M.registry;if(!H||!M.surface)return[];let ne;try{ne=H.getToolsBySurface(M.surface)}catch(ye){return m("registry","resolve",`The tool registry failed discovery for the "${M.surface}" surface.`,ye),[]}let ae=null;if(M.scope.kind==="content"&&c&&ne.some(ye=>ye.requiresAuthoredContent))try{ae=c.snapshot()}catch(ye){m("catalog-owner","resolve",`Catalog owner resolution failed for the "${M.surface}" surface; catalog-dependent capabilities were omitted.`,ye)}return ne.flatMap(ye=>{const te=M.scope.kind==="content"?I(M,ye,ae):C(M,ye);return te?[te]:[]})}function $(M,H){const ne=M.registry;if(!ne)return!1;const ae=H.registration.toolId;if(d.get(ae)===H.registration)return!0;const ye=f.get(ae);if(ye?.registry===ne&&ye.registration===H.registration)return!1;const te=ne.ensureToolModuleLoaded(ae),z={registry:ne,registration:H.registration};return f.set(ae,z),te.then(()=>{f.get(ae)===z&&f.delete(ae),!(i||n?.registry!==ne)&&ne.get(ae)===H.registration&&(d.set(ae,H.registration),L())}).catch(A=>{f.get(ae)===z&&f.delete(ae),!(i||n?.registry!==ne)&&ne.get(ae)===H.registration&&m(ae,"load",`Tool "${ae}" failed to load for the "${M.surface}" surface.`,A)}),!1}function P(M,H){const ne=M.registry,ae=M.anchor;if(!ne||!ae)return;const ye=H.registration.toolId;let te=null;try{if(te=ne.renderForSurface(ye,H.context),!te?.element)return;te.ariaLabel&&te.element.setAttribute("aria-label",te.ariaLabel),ae.appendChild(te.element),u.set(ye,{registration:H.registration,element:te.element,sync:te.sync,destroy:te.destroy,context:H.context,contextSignature:H.contextSignature})}catch(z){if(te?.element.parentNode===ae)try{ae.removeChild(te.element)}catch{}m(ye,"render",`Tool "${ye}" failed to render into the "${M.surface}" surface.`,z);return}}function L(){if(i||!n)return;const M=n,H=x(M),ne=new Map(H.map(ae=>[ae.registration.toolId,ae]));for(const[ae,ye]of[...u]){const te=ne.get(ae);(!M.anchor||!te||te.registration!==ye.registration)&&v(ae)}if(M.anchor&&M.registry){for(const ae of H){const ye=ae.registration.toolId,te=u.get(ye);if(te){if(DH(te,ae))continue;try{te.sync?.(ae.context),te.context=ae.context,te.contextSignature=ae.contextSignature}catch(z){m(ye,"sync",`Tool "${ye}" failed to synchronize in the "${M.surface}" surface.`,z)}continue}$(M,ae)&&P(M,ae)}for(const ae of H){const ye=u.get(ae.registration.toolId);if(ye)try{M.anchor.appendChild(ye.element)}catch(te){m(ae.registration.toolId,"sync",`Tool "${ae.registration.toolId}" failed DOM reconciliation in the "${M.surface}" surface.`,te)}}}g({mountable:H.length>0,occupied:!!(M.anchor&&u.size>0)})}function J(){i||(h.clear(),L())}function V(M){if(M.kind==="module-loaders")for(const H of M.toolIds)d.delete(H);M.kind==="component-overrides"&&b(),J()}function Y(){for(const M of[s,a,l])try{M?.()}catch{}s=null,a=null,l=null,c=null}function Pe(M){Y(),s=typeof M.registry?.onRegistryChange=="function"?M.registry.onRegistryChange(V):null;const H=M.services.toolkitCoordinator;H&&(a=typeof H.onPolicyChange=="function"?H.onPolicyChange(J):null),M.scope.kind==="content"&&M.services.catalogResolver&&(c=M.services.catalogResolver.forOwner(M.scope.ownerContext),l=c.onChange(J))}return{update(M){if(i)return;const H=n;let ne=!0;try{ne=H?!LH(H,M):!0}catch{ne=!0}const ae=H?!NH(H,M):!0;n=M,ae&&Pe(M),ne&&(h.clear(),L())},destroy(){i||(Y(),b(),i=!0,n=null,f.clear(),d.clear())}}}function aw(e,t){return{fullToolId:xb(e,t.scope.level,t.scope.scopeId),isActive:()=>t.isToolVisible(e),subscribeActive:r=>t.subscribeVisibility?t.subscribeVisibility(()=>{r(t.isToolVisible(e))}):()=>{}}}function lw(e){const t=e.isActive();e.button.active=t,e.overlay.visible=t,e.onActiveChange?.(t)}function jH(e,t){e.setAttribute("data-pie-tool-surface",t)}var zH=Wt('<div class="pie-section-player-card-media svelte-1ms6ug7" data-region="media"><div class="pie-section-player-card-media-surface svelte-1ms6ug7"></div></div>'),BH=Wt("<div><!> <!> <!></div>"),FH={hash:"svelte-1ms6ug7",code:`
1236
+ /* Content and its docked catalog media, side by side. One column until a media
1237
+ card resolves, so the content region keeps its position in the layout either
1238
+ way. */.pie-section-player-card-media-split.svelte-1ms6ug7 {display:grid;align-items:start;min-width:0;min-height:0;}
1239
+
1240
+ /* \`:global\` because the content body is authored by the card and arrives here
1241
+ as a snippet, so it carries the card's scoping rather than this component's. */.pie-section-player-card-media-split.svelte-1ms6ug7 > * {min-width:0;min-height:0;}
1242
+
1243
+ /* Below the stacking breakpoint the grid is single-column, so the media region
1244
+ flows under the content instead of being squeezed beside it. */.pie-section-player-card-media-split--stacked.svelte-1ms6ug7 {grid-template-columns:minmax(0, 1fr);}.pie-section-player-card-media.svelte-1ms6ug7 {padding:1rem 1rem 1rem 0;}
1245
+
1246
+ /* Granted but nothing mounted: the region is in the DOM only to give the
1247
+ capability an anchor, so it must not claim a grid column or reach the
1248
+ accessibility tree. */.pie-section-player-card-media.svelte-1ms6ug7:not([data-occupied]) {display:none;}
1249
+
1250
+ /* Layout-transparent, so the capability's element is a direct child of the
1251
+ region as it was before the region became a host surface. An anchor that
1252
+ generated its own box broke any \`height: 100%\` chain through it, and the
1253
+ sizing tokens hosts set on the region are being tested against that chain. */.pie-section-player-card-media-surface.svelte-1ms6ug7 {display:contents;}.pie-section-player-card-media-split--stacked.svelte-1ms6ug7 .pie-section-player-card-media:where(.svelte-1ms6ug7) {padding:0 1rem 1rem;}
1254
+
1255
+ /* A docked alternate is consulted while an answer is being formed, not read
1256
+ once beforehand, so it follows long content down the scroll rather than
1257
+ disappearing above it. */.pie-section-player-card-media-split--with-media.svelte-1ms6ug7:not(
1258
+ .pie-section-player-card-media-split--stacked
1259
+ )
1260
+ .pie-section-player-card-media:where(.svelte-1ms6ug7) {position:sticky;top:0;align-self:start;}`};function cw(e,t){pn(t,!0),Ln(e,FH);let r=D(t,"regionId",7),n=D(t,"ownerContext",7),i=D(t,"runtimeContext",7,null),o=D(t,"toolRegistry",7,null),s=D(t,"dividerAriaLabel",7),a=D(t,"dividerValueTextSuffix",7,"% media width"),l=D(t,"content",7),c=Be(null),u=Be(null),d=Be(0),f=Be(ui(34)),h=Be(ui({mountable:!1,occupied:!1}));const g=sw(M=>{be(h,M,!0)},{hostLabel:"pie-section-player"});vt(()=>{g.update({anchor:p(c),surface:pk,registry:o(),services:{toolkitCoordinator:i()?.toolkitCoordinator??null,ttsService:i()?.ttsService??null,catalogResolver:i()?.catalogResolver??null,i18n:Ba(i())},scope:{kind:"content",ownerContext:n()}})}),_m(()=>g.destroy()),vt(()=>{const M=p(u);if(!M||typeof ResizeObserver>"u")return;const H=()=>{be(d,M.getBoundingClientRect().width,!0)};H();const ne=new ResizeObserver(H);return ne.observe(M),()=>ne.disconnect()});const m=q(()=>p(h).mountable),v=q(()=>p(h).occupied),b=q(()=>p(d)>0&&p(d)<560),I=q(()=>p(v)&&!p(b)),C=q(()=>p(I)?`minmax(0, ${100-p(f)}fr) auto minmax(0, ${p(f)}fr)`:"minmax(0, 1fr)");function x(M){be(f,nf(M),!0)}var $={get regionId(){return r()},set regionId(M){r(M),N()},get ownerContext(){return n()},set ownerContext(M){n(M),N()},get runtimeContext(){return i()},set runtimeContext(M=null){i(M),N()},get toolRegistry(){return o()},set toolRegistry(M=null){o(M),N()},get dividerAriaLabel(){return s()},set dividerAriaLabel(M){s(M),N()},get dividerValueTextSuffix(){return a()},set dividerValueTextSuffix(M="% media width"){a(M),N()},get content(){return l()},set content(M){l(M),N()}},P=BH(),L=Er(P);BM(L,l);var J=mr(L,2),V=M=>{{let H=q(()=>`${Math.round(p(f))}${a()}`);u_(M,{get value(){return p(f)},get min(){return 20},get max(){return 55},get container(){return p(u)},get ariaLabel(){return s()},get ariaControls(){return r()},get ariaValueText(){return p(H)},onresize:x})}};cn(J,M=>{p(I)&&M(V)});var Y=mr(J,2),Pe=M=>{var H=zH(),ne=Er(H);$r(ne,ae=>be(c,ae),()=>p(c)),Tr(H),ve(()=>{at(H,"id",r()),at(H,"data-occupied",p(v)?"":void 0),at(ne,"data-pie-tool-surface",pk)}),ht(M,H)};return cn(Y,M=>{p(m)&&M(Pe)}),Tr(P),$r(P,M=>be(u,M),()=>p(u)),ve(()=>{yn(P,1,`pie-section-player-card-media-split ${p(v)?"pie-section-player-card-media-split--with-media":""} ${p(b)?"pie-section-player-card-media-split--stacked":""}`,"svelte-1ms6ug7"),Xl(P,`grid-template-columns: ${p(C)};`)}),ht(e,P),mn($)}Tn(cw,{regionId:{},ownerContext:{},runtimeContext:{},toolRegistry:{},dividerAriaLabel:{},dividerValueTextSuffix:{},content:{}},[],[],{mode:"open"});var HH=Wt('<div class="pie-section-player-card-surface-stack svelte-mqy0q4" data-region="surface-stack"><div class="pie-section-player-card-surface-stack-anchor svelte-mqy0q4"></div></div>'),UH={hash:"svelte-mqy0q4",code:`.pie-section-player-card-surface-stack.svelte-mqy0q4 {padding:1rem 1rem 0;}
1261
+
1262
+ /* Granted but nothing mounted: in the DOM only to give the capability an
1263
+ anchor, so it must not claim space or reach the accessibility tree. */.pie-section-player-card-surface-stack.svelte-mqy0q4:not([data-occupied]) {display:none;}
1264
+
1265
+ /* Layout-transparent, so a capability's element is a direct child of the
1266
+ region and any height chain through it stays intact. */.pie-section-player-card-surface-stack-anchor.svelte-mqy0q4 {display:contents;}`};function uw(e,t){pn(t,!0),Ln(e,UH);let r=D(t,"regionId",7),n=D(t,"surface",7),i=D(t,"ownerContext",7),o=D(t,"runtimeContext",7,null),s=D(t,"toolRegistry",7,null),a=Be(null),l=Be(ui({mountable:!1,occupied:!1}));const c=sw(m=>{be(l,m,!0)},{hostLabel:"pie-section-player"});vt(()=>{c.update({anchor:p(a),surface:n(),registry:s(),services:{toolkitCoordinator:o()?.toolkitCoordinator??null,ttsService:o()?.ttsService??null,catalogResolver:o()?.catalogResolver??null,i18n:Ba(o())},scope:{kind:"content",ownerContext:i()}})}),_m(()=>c.destroy());const u=q(()=>p(l).mountable);var d={get regionId(){return r()},set regionId(m){r(m),N()},get surface(){return n()},set surface(m){n(m),N()},get ownerContext(){return i()},set ownerContext(m){i(m),N()},get runtimeContext(){return o()},set runtimeContext(m=null){o(m),N()},get toolRegistry(){return s()},set toolRegistry(m=null){s(m),N()}},f=Ys(),h=bn(f),g=m=>{var v=HH(),b=Er(v);$r(b,I=>be(a,I),()=>p(a)),Tr(v),ve(()=>{at(v,"id",r()),at(v,"data-pie-tool-surface",n()),at(v,"data-occupied",p(l).occupied?"":void 0)}),ht(m,v)};return cn(h,m=>{p(u)&&m(g)}),ht(e,f),mn(d)}Tn(uw,{regionId:{},surface:{},ownerContext:{},runtimeContext:{},toolRegistry:{}},[],[],{mode:"open"});var qH=Wt('<div class="pie-section-player-content-card-body pie-section-player-item-content pie-section-player__item-content svelte-1rzb80u" data-region="content"><!></div>'),WH=Wt('<button type="button" class="pie-section-player-formative__button svelte-1rzb80u"> </button>'),VH=Wt('<div class="pie-section-player-formative svelte-1rzb80u"><p class="pie-section-player-formative__status svelte-1rzb80u" data-pie-formative-status="" aria-live="polite"> </p> <!></div>'),GH=Wt('<div class="pie-section-player-item-card-anchor svelte-1rzb80u" aria-hidden="true"></div> <pie-item-scope><div class="pie-section-player-content-card svelte-1rzb80u" data-section-item-card="" data-pie-tool-overlay-boundary=""><div class="pie-section-player-content-card-header pie-section-player-item-header pie-section-player__item-header svelte-1rzb80u" data-region="header"><!> <pie-item-toolbar></pie-item-toolbar></div> <!> <!> <div data-region="footer"><!></div></div></pie-item-scope>',3),YH={hash:"svelte-1rzb80u",code:`.pie-section-player-item-card-anchor.svelte-1rzb80u {display:none;}pie-section-player-item-card {display:block;border-radius:var(--pie-section-player-card-radius, 8px);}
1267
+
1268
+ /* A cue-gated card stays mounted and is hidden, which keeps its shell
1269
+ registration, its session and the section's loading accounting intact —
1270
+ mounting on the cue instead would tear an item player down on every seek
1271
+ backwards. The rule is needed because the \`display: block\` above would
1272
+ otherwise beat the UA stylesheet's \`[hidden]\`. */pie-section-player-item-card[hidden] {display:none;}.pie-section-player-content-card.svelte-1rzb80u {
1273
+ /*
1274
+ * Containing block for frameless tool overlays. The toolkit appends them to
1275
+ * this element (see \`resolveOverlayMountParent\` in the assessment toolkit),
1276
+ * so the card's box is the frame a line reader or a ruler positions and
1277
+ * clamps against. Without it those overlays resolve against whichever
1278
+ * ancestor happens to be positioned, and a tool placed on this card can open
1279
+ * outside it.
1280
+ */position:relative;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);}.pie-section-player-content-card-header.svelte-1rzb80u {position:relative;display:flex;flex-wrap:wrap;align-items:center;gap:0.75rem;padding:0.75rem 1rem;overflow:visible;border-bottom:1px solid var(--pie-border-light, #e5e7eb);
1281
+
1282
+ /* Header fill is intentionally transparent by default. Hosts/themes
1283
+ opt-in to a solid color via --pie-section-player-card-header-background
1284
+ (e.g. a brand Bluegreen tint) without this framework encoding a palette. */background:var(--pie-section-player-card-header-background, transparent);
1285
+ /* Default just inside the card radius to avoid a double-radius effect with the border. */border-top-left-radius:var(
1286
+ --pie-section-player-card-header-radius,
1287
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1288
+ );border-top-right-radius:var(
1289
+ --pie-section-player-card-header-radius,
1290
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1291
+ );}
1292
+
1293
+ /*
1294
+ * Dark themes get their own opt-in fill: a host's light-theme brand tint
1295
+ * surviving into a dark theme is the failure this avoids. Unset, it falls
1296
+ * back to the single light hook, so a host that sets only that one is
1297
+ * unaffected. Keyed off the selectors the theme package writes its dark
1298
+ * tokens under — see renderTokensCss in packages/theme/src/theme-css.ts.
1299
+ */[data-theme="dark"] .pie-section-player-content-card-header.svelte-1rzb80u,
1300
+ pie-theme[theme="dark"] .pie-section-player-content-card-header.svelte-1rzb80u {background:var(
1301
+ --pie-section-player-card-header-background-dark,
1302
+ var(--pie-section-player-card-header-background, transparent)
1303
+ );}
1304
+
1305
+ /* Any heading level, not \`h2\`: the card renders at \`base-heading-level\`, so
1306
+ the tag is composition context rather than a fixed choice, and a host that
1307
+ nests the player deeper got an unstyled title. */.pie-section-player-content-card-header.svelte-1rzb80u :is(h1:where(.svelte-1rzb80u), h2:where(.svelte-1rzb80u), h3:where(.svelte-1rzb80u), h4:where(.svelte-1rzb80u), h5:where(.svelte-1rzb80u), h6:where(.svelte-1rzb80u)) {position:relative;
1308
+ /* Was supplied by the content stylesheet's heading reset, which now
1309
+ applies inside a player's content root only. */line-height:1.2;min-width:0;overflow-wrap:anywhere;z-index:0;margin:0;
1310
+ /* Reads the scale rather than inheriting it: the card wraps the item scope
1311
+ that \`font-sizes.css\` scales, so nothing above this rule carries the
1312
+ scaled size. Root-relative, so it does not compound with the shell. */font-size:calc(0.95rem * var(--pie-font-scale, 1));font-weight:600;
1313
+ /* Default to the themed body text color so titles stay legible across
1314
+ DaisyUI themes; --pie-header-text remains a host opt-in override. */color:var(--pie-header-text, var(--pie-text, #111827));}.pie-section-player-content-card-header.svelte-1rzb80u pie-item-toolbar:where(.svelte-1rzb80u) {position:relative;min-width:0;max-width:100%;z-index:1;margin-left:auto;}
1315
+
1316
+ /* Floating reading controls must paint above the pane's scroll hint (10). */.pie-section-player-content-card-header.svelte-1rzb80u pie-item-toolbar[data-pie-header-overlay-active="true"] {z-index:11;}.pie-section-player-content-card-body.svelte-1rzb80u {padding:1rem;color:var(--pie-text, #111827);}
1317
+
1318
+ /* Formative control. Painted only from \`--pie-*\` chains so it follows every
1319
+ base theme, provider and colour scheme without a hook of its own. */.pie-section-player-formative.svelte-1rzb80u {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;flex-wrap:wrap;padding:0.75rem 1rem;border-top:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-formative__status.svelte-1rzb80u {margin:0;
1320
+ /* Tries remaining and correctness, and the only signal carrying either —
1321
+ the note below is why no colour accompanies it. So it follows the font
1322
+ accommodation for the same reason the item body does. */font-size:calc(0.9rem * var(--pie-font-scale, 1));
1323
+ /* Correctness is carried by the text itself, so no state colour is needed
1324
+ and none is applied — a colour here would be the only signal at exactly
1325
+ the moment it must not be (WCAG 1.4.1). */color:var(--pie-text, #111827);}
1326
+
1327
+ /* Empty until a Try lands; collapse so the footer does not reserve a blank
1328
+ row before there is anything to announce. */.pie-section-player-formative__status.svelte-1rzb80u:empty {display:none;}
1329
+
1330
+ /* Canonical button-family chains, no component-scoped hook: this control is an
1331
+ ordinary button and a host that restyles ordinary buttons should get it for
1332
+ free. Geometry stays literal, as it does on the scroll hint — the contract
1333
+ certifies colour pairs, not radii. */.pie-section-player-formative__button.svelte-1rzb80u {
1334
+ /* Comfortably past the 24x24 minimum in WCAG 2.5.8, and the padding keeps
1335
+ it there at the smallest supported text size. */min-height:2.25rem;padding:0.4rem 0.9rem;margin-left:auto;border:1px solid var(--pie-button-border, var(--pie-border, #8f8f8f));border-radius:4px;background:var(--pie-button-bg, var(--pie-white, #fff));color:var(--pie-button-color, var(--pie-text, #374151));font:inherit;cursor:pointer;}.pie-section-player-formative__button.svelte-1rzb80u:hover {background:var(--pie-button-hover-bg, var(--pie-background-dark, #f9fafb));border-color:var(--pie-button-hover-border, var(--pie-border, #8b919c));color:var(--pie-button-hover-color, var(--pie-text, #111827));}.pie-section-player-formative__button.svelte-1rzb80u:active {
1336
+ /* \`--pie-button-color\` is the only ink the contract certifies against this
1337
+ fill, so the pair stays together. */background:var(--pie-button-active-bg, var(--pie-background-dark, #f3f4f6));color:var(--pie-button-color, var(--pie-text, #374151));}.pie-section-player-formative__button.svelte-1rzb80u:focus-visible {outline:2px solid
1338
+ var(--pie-button-focus-outline, var(--pie-primary, #3b82f6));outline-offset:2px;}.pie-section-player-formative__button[aria-busy="true"].svelte-1rzb80u {cursor:progress;}`};function KH(e,t){pn(t,!0),Ln(e,YH);let r=D(t,"item",7),n=D(t,"itemIndex",7,0),i=D(t,"itemCount",7,1),o=D(t,"isCurrent",7,!1),s=D(t,"canonicalItemId",7),a=D(t,"itemSettings",7,null),l=D(t,"baseHeadingLevel",7,2),c=D(t,"resolvedPlayerTag",7,"div"),u=D(t,"playerAction",7,(re,Qe)=>{}),d=D(t,"playerParams",7),f=D(t,"itemToolbarTools",7),h=D(t,"toolRegistry",7,null),g=D(t,"hostButtons",23,()=>[]),m=D(t,"formativeView",7,null),v=D(t,"timedMediaView",7,null);const b=q(()=>ow(l()));let I=Be(null);const C=q(()=>Ba(p(I)));let x=Be(null),$=Be(null),P=Be(null),L=Be(null),J=Be(!1);const V=Dr(()=>`pie-section-player-item-card-heading-${r()?.id??s()??Math.random().toString(36).slice(2,10)}`),Y=q(()=>(p(J)?p($):null)||c()),Pe=q(()=>(p(J)?p(P):null)||u()),M=q(()=>Number.isFinite(n())?Math.max(0,Number(n()))+1:1),H=q(()=>Number.isFinite(i())?Math.max(1,Number(i())):1),ne=q(()=>p(H)>1?p(C).t("player.questionNumbered",{position:p(M)}):p(C).t("player.question")),ae=q(()=>(p(J)?p(L):null)||null),ye=q(()=>{if(!p(ae))return p(ne);try{const re=p(ae)({kind:"item",item:r(),itemIndex:p(M)-1,itemCount:p(H),canonicalItemId:s(),defaultTitle:p(ne)});return typeof re!="string"?p(ne):re.trim()||p(ne)}catch{return p(ne)}}),te=q(()=>`${V}-media`),z=q(()=>`${V}-lead`),A=q(()=>CT({kind:"item",itemId:r()?.id??"",canonicalItemId:s(),assessmentId:p(I)?.assessmentId,sectionId:p(I)?.sectionId}));vt(()=>{if(p(x))return sf(p(x),re=>{be(I,re,!0)})});function K(){be(J,!1),be($,null),be(P,null),be(L,null)}function Q(re){!re||typeof re!="object"||(typeof re.resolvedPlayerTag=="string"&&re.resolvedPlayerTag.trim()&&be($,re.resolvedPlayerTag,!0),typeof re.playerAction=="function"&&be(P,re.playerAction,!0),typeof re.cardTitleFormatter=="function"&&be(L,re.cardTitleFormatter,!0))}let _=Be(null),B=Be(!1),U=Be(!1);const fe=q(()=>m()?.enabled===!0),W=q(()=>p(fe)&&(m()?.canCheck||m()?.canRetry)),se=q(()=>p(C).t(m()?.canRetry?"player.formative.tryAgain":"player.formative.checkAnswer"));function _e(re){return re.triesRemaining==="unlimited"||re.triesRemaining<=0?"":p(C).plural?.("player.formative.triesLeft",{count:re.triesRemaining})??""}function Ue(re){if(!re.revealed)return re.tryCount>0?p(C).t("player.formative.answerRecorded"):"";switch(re.lastOutcome?.correctness){case"correct":return p(C).t("player.formative.correct");case"partial":return p(C).t("player.formative.partlyCorrect");case"incorrect":return p(C).t("player.formative.notCorrect");case"unknown":return p(C).t("player.formative.notAutoScored");default:return p(C).t("player.formative.answerRecorded")}}const it=q(()=>{if(p(U))return p(C).t("player.formative.checkFailed");if(!m()?.enabled)return"";const re=Ue(m());if(!re)return"";const Qe=m().canRetry?_e(m()):"";return Qe?`${re} ${Qe}`:re});function le(re,Qe){const lt=oa(p(x));if(!lt||!r()?.id)return;const zt={itemId:r().id,canonicalItemId:s()||r().id,action:re,outcomes:Qe};Vl(lt,dD,zt)}async function de(){if(!m()?.enabled||p(B))return;if(be(U,!1),m().canRetry){le("retry");return}if(!m().canCheck)return;const re=p(_)?.provideScore;if(typeof re!="function"){be(U,!0);return}be(B,!0);try{const Qe=await re.call(p(_));le("check",Array.isArray(Qe)?Qe:[])}catch(Qe){be(U,!0),console.warn(`[pie-section-player] provideScore() failed for item ${r()?.id}:`,Qe)}finally{be(B,!1)}}Pm(()=>{const re=oa(p(x));if(!re)return;be(J,!0);const Qe=l_(re,Q);return()=>{Qe(),K()}});var Ne={get item(){return r()},set item(re){r(re),N()},get itemIndex(){return n()},set itemIndex(re=0){n(re),N()},get itemCount(){return i()},set itemCount(re=1){i(re),N()},get isCurrent(){return o()},set isCurrent(re=!1){o(re),N()},get canonicalItemId(){return s()},set canonicalItemId(re){s(re),N()},get itemSettings(){return a()},set itemSettings(re=null){a(re),N()},get baseHeadingLevel(){return l()},set baseHeadingLevel(re=2){l(re),N()},get resolvedPlayerTag(){return c()},set resolvedPlayerTag(re="div"){c(re),N()},get playerAction(){return u()},set playerAction(re=(Qe,lt)=>{}){u(re),N()},get playerParams(){return d()},set playerParams(re){d(re),N()},get itemToolbarTools(){return f()},set itemToolbarTools(re){f(re),N()},get toolRegistry(){return h()},set toolRegistry(re=null){h(re),N()},get hostButtons(){return g()},set hostButtons(re=[]){g(re),N()},get formativeView(){return m()},set formativeView(re=null){m(re),N()},get timedMediaView(){return v()},set timedMediaView(re=null){v(re),N()}},Ae=GH(),ce=bn(Ae);$r(ce,re=>be(x,re),()=>p(x));var ie=mr(ce,2);ve(()=>Ce(ie,"item-id",r().id)),ve(()=>Ce(ie,"canonical-item-id",s())),Ce(ie,"content-kind","assessment-item"),ve(()=>Ce(ie,"item",r())),ve(()=>Ce(ie,"settings",a()));var De=Er(ie),Je=Er(De),At=Er(Je);Cp(At,()=>`h${p(b)}`,!1,(re,Qe)=>{FE(re,()=>({id:V,"data-pie-tool-overlay-protect":!0,class:""}),void 0,void 0,void 0,"svelte-1rzb80u");var lt=xE();ve(()=>ks(lt,p(ye))),ht(Qe,lt)});var pt=mr(At,2);ve(()=>Ce(pt,"item-id",r().id)),ve(()=>Ce(pt,"catalog-id",r().id)),ve(()=>Ce(pt,"tools",f())),Ce(pt,"content-kind","assessment-item"),Ce(pt,"size","md"),ve(()=>Ce(pt,"toolRegistry",h())),ve(()=>Ce(pt,"hostButtons",g())),yn(pt,1,"svelte-1rzb80u"),Tr(Je);var Et=mr(Je,2);uw(Et,{get regionId(){return p(z)},get surface(){return c_},get ownerContext(){return p(A)},get runtimeContext(){return p(I)},get toolRegistry(){return h()}});var Re=mr(Et,2);{const re=lt=>{var zt=qH(),Vt=Er(zt);Cp(Vt,()=>p(Y),!1,(ur,st)=>{$r(ur,Rt=>be(_,Rt,!0),()=>p(_)),OE(ur,(Rt,bt)=>p(Pe)?.(Rt,bt),d),yn(ur,0,"svelte-1rzb80u")}),Tr(zt),ht(lt,zt)};let Qe=q(()=>p(C).t("player.resizeQuestionAndMediaA11y"));cw(Re,{get regionId(){return p(te)},get ownerContext(){return p(A)},get runtimeContext(){return p(I)},get toolRegistry(){return h()},get dividerAriaLabel(){return p(Qe)},content:re,$$slots:{content:!0}})}var Ze=mr(Re,2),Ye=Er(Ze),yt=re=>{var Qe=VH(),lt=Er(Qe),zt=La(lt,!0),Vt=mr(lt,2),ur=st=>{var Rt=WH(),bt=La(Rt,!0);ve(()=>{at(Rt,"data-pie-formative-action",m()?.canRetry?"retry":"check"),at(Rt,"aria-busy",p(B)?"true":void 0),ks(bt,p(se))}),fo("click",Rt,de),ht(st,Rt)};cn(Vt,st=>{p(W)&&st(ur)}),Tr(Qe),ve(()=>ks(zt,p(it))),ht(re,Qe)};return cn(Ye,re=>{p(fe)&&re(yt)}),Tr(Ze),Tr(De),Tr(ie),ve(()=>{at(De,"data-canonical-item-id",s()),at(De,"aria-current",o()?"true":void 0),at(De,"data-pie-timed-media-gate",v()?.isGateTarget?"holding":void 0),at(De,"tabindex",v()?.isGateTarget?-1:void 0)}),ht(e,Ae),mn(Ne)}Pu(["click"]);XH("pie-section-player-item-card",Tn(KH,{item:{type:"Object"},itemIndex:{attribute:"item-index",type:"Number"},itemCount:{attribute:"item-count",type:"Number"},isCurrent:{attribute:"is-current",reflect:!0,type:"Boolean"},canonicalItemId:{attribute:"canonical-item-id",type:"String"},itemSettings:{attribute:"item-settings",type:"Object"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},resolvedPlayerTag:{attribute:"resolved-player-tag",type:"String"},playerAction:{type:"Object"},playerParams:{attribute:"player-params",type:"Object"},itemToolbarTools:{attribute:"item-toolbar-tools",type:"String"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"},formativeView:{attribute:"formative-view",type:"Object"},timedMediaView:{attribute:"timed-media-view",type:"Object"}},[],[],void 0,ja));function XH(e,t){customElements.get(e)||customElements.define(e,t)}var JH=Wt('<div class="pie-passage-shell-anchor svelte-1fzqxck" aria-hidden="true"></div> <!>',1),QH={hash:"svelte-1fzqxck",code:".pie-passage-shell-anchor.svelte-1fzqxck {display:none;}"};function ZH(e,t){pn(t,!0),Ln(e,QH);let r=D(t,"itemId",7,""),n=D(t,"canonicalItemId",7,""),i=D(t,"contentKind",7,"rubric-block-stimulus"),o=D(t,"regionPolicy",7,"default"),s=D(t,"scopeElement",7,null),a=D(t,"ttsHighlightTargetResolver",7,null),l=D(t,"item",7,null),c=Be(null);function u(){if(!p(c))return null;const b=p(c).getRootNode();return b&&"host"in b?b.host:p(c).parentElement}const d=q(()=>u()),f=wD();vt(()=>{if(!p(d))return;const b=kD({host:p(d),kind:"passage",identity:()=>({itemId:r(),canonicalItemId:n(),contentKind:i()}),mode:()=>"section",send:f.send});return()=>{try{b.disconnect()}finally{f.retire(),f.disconnect()}}}),vt(()=>{f.publish(p(d)?{host:p(d),kind:"passage",itemId:r(),canonicalItemId:n(),contentKind:i(),regionPolicy:o(),scopeElement:s(),ttsHighlightTargetResolver:a(),item:l()}:null)});var h={get itemId(){return r()},set itemId(b=""){r(b),N()},get canonicalItemId(){return n()},set canonicalItemId(b=""){n(b),N()},get contentKind(){return i()},set contentKind(b="rubric-block-stimulus"){i(b),N()},get regionPolicy(){return o()},set regionPolicy(b="default"){o(b),N()},get scopeElement(){return s()},set scopeElement(b=null){s(b),N()},get ttsHighlightTargetResolver(){return a()},set ttsHighlightTargetResolver(b=null){a(b),N()},get item(){return l()},set item(b=null){l(b),N()}},g=JH(),m=bn(g);$r(m,b=>be(c,b),()=>p(c));var v=mr(m,2);return _u(v,t,"default",{},null),ht(e,g),mn(h)}e9("pie-passage-shell",Tn(ZH,{itemId:{attribute:"item-id",type:"String"},canonicalItemId:{attribute:"canonical-item-id",type:"String"},contentKind:{attribute:"content-kind",type:"String"},regionPolicy:{attribute:"region-policy",type:"String"},scopeElement:{type:"Object"},ttsHighlightTargetResolver:{type:"Object"},item:{type:"Object"}},["default"],[],{mode:"open"}));function e9(e,t){customElements.get(e)||customElements.define(e,t)}var ed={allowSeekAhead:!1,pauseOnRequiredCue:!0,requireMediaCompletion:!1},gk=["reveal","gate","metadata"],vk=["responded","correct","partial-or-better"],t9=["release","hold"],yk=["sum-child-outcomes","average-child-outcomes","host-defined"];function r9(e){return e==="correct"||e==="partial-or-better"}function wv(e){return typeof e=="string"?e.trim():""}function n9(e){if(e==null)return{policy:{...ed},error:null};if(typeof e!="object")return{policy:{...ed},error:{code:"invalid-playback-policy",message:"timedMedia.playbackPolicy must be an object."}};const t=e;return{policy:{allowSeekAhead:typeof t.allowSeekAhead=="boolean"?t.allowSeekAhead:ed.allowSeekAhead,pauseOnRequiredCue:typeof t.pauseOnRequiredCue=="boolean"?t.pauseOnRequiredCue:ed.pauseOnRequiredCue,requireMediaCompletion:typeof t.requireMediaCompletion=="boolean"?t.requireMediaCompletion:ed.requireMediaCompletion},error:null}}function i9(e){if(e==null)return{policy:void 0,error:null};const t=e&&typeof e=="object"?e.strategy:void 0,r=yk.find(n=>n===t);return r?{policy:{strategy:r},error:null}:{policy:void 0,error:{code:"invalid-scoring-policy",message:`timedMedia.scoringPolicy.strategy must be one of ${yk.join(", ")}.`}}}function o9(e){const t=[];if(!e.timedMedia||typeof e.timedMedia!="object")return{data:null,errors:[{code:"missing-stimulus-ref",message:"timedMedia must be an object carrying a stimulusRef."}]};const r=e.timedMedia,n=wv(r.stimulusRef);n||t.push({code:"missing-stimulus-ref",message:"timedMedia.stimulusRef is required."});const i=n?e.resolveStimulusRenderableId(n):void 0;n&&!i&&t.push({code:"unresolved-stimulus-ref",message:`timedMedia.stimulusRef "${n}" does not name a renderable in this section.`});const{policy:o,error:s}=n9(r.playbackPolicy);s&&t.push(s);const{policy:a,error:l}=i9(r.scoringPolicy);l&&t.push(l);const c=new Set(e.itemIdentifiers),u=Array.isArray(r.cues)?r.cues:[];u.length===0&&t.push({code:"no-cues",message:"timedMedia.cues must hold at least one cue."});const d=new Set,f=[];for(const[h,g]of u.entries()){const m=g??{},v=wv(m.identifier);if(!v){t.push({code:"invalid-cue-identifier",message:`timedMedia.cues[${h}] has no identifier.`});continue}if(d.has(v)){t.push({code:"duplicate-cue-identifier",message:`Cue identifier "${v}" appears more than once.`,cueIdentifier:v});continue}d.add(v);const b=Lx(m.range);if(!b){t.push({code:"invalid-cue-range",message:`Cue "${v}" needs a range with a finite, non-negative startSeconds.`,cueIdentifier:v});continue}const I=m.policy??{},C=gk.find(J=>J===I.activation);if(!C){t.push({code:"invalid-cue-activation",message:`Cue "${v}" needs policy.activation of ${gk.join(", ")}.`,cueIdentifier:v});continue}const x=Array.isArray(m.itemRefs)?m.itemRefs:[],$=[];for(const J of x){const V=wv(J);if(V){if(!c.has(V)){t.push({code:"unknown-item-ref",message:`Cue "${v}" names item ref "${V}", which is not in this section.`,cueIdentifier:v});continue}$.includes(V)||$.push(V)}}if($.length===0&&C!=="metadata"){t.push({code:"missing-item-refs",message:`Cue "${v}" activates no item; only a metadata cue may name none.`,cueIdentifier:v});continue}let P,L;if(C==="gate"){if(P=vk.find(J=>J===I.releaseOn),!P){t.push({code:"missing-release-condition",message:`Gate cue "${v}" needs policy.releaseOn of ${vk.join(", ")}.`,cueIdentifier:v});continue}if(r9(P)){if(L=t9.find(V=>V===I.onUnknownCorrectness),!L){t.push({code:"missing-unknown-correctness",message:`Gate cue "${v}" releases on correctness, so policy.onUnknownCorrectness must state "release" or "hold" for an item no controller can score.`,cueIdentifier:v});continue}const J=$.filter(V=>e.resolveItemTryBudget(V)!=="unlimited");if(J.length>0){t.push({code:"gate-requires-unlimited-tries",message:`Gate cue "${v}" releases on correctness, so every item it names needs formative delivery with maxTries: "unlimited" — otherwise a learner who runs out of Tries can never release playback. Offending item refs: ${J.join(", ")}.`,cueIdentifier:v});continue}}}f.push({identifier:v,range:b,itemRefs:$,activation:C,releaseOn:P,onUnknownCorrectness:L,holdsPlayback:C==="gate"&&o.pauseOnRequiredCue})}return t.length>0?{data:null,errors:t}:{data:{stimulusRef:n,stimulusRenderableId:i??"",cues:f,playbackPolicy:o,scoringPolicy:a},errors:[]}}var s9=.5,a9=.001,l9=10;function lp(){return{version:1,mediaCurrentTime:0,maxPositionSeconds:0,mediaCompleted:!1,visitedCueIdentifiers:[],completedCueIdentifiers:[],aggregateComplete:!1}}function Sv(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?t:r}function c9(e,t){return t+a9>=e.range.startSeconds}function u9(e,t,r){if(e.releaseOn==="responded")return r.respondedByItemId[t]===!0;const n=r.correctnessByItemId[t];return n===void 0?!1:n==="unknown"?e.onUnknownCorrectness==="release":e.releaseOn==="correct"?n==="correct":n==="correct"||n==="partial"}function h_(e,t){return e.itemRefs.length===0?!0:e.itemRefs.every(r=>u9(e,r,t))}function bk(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function d9(e){const{state:t,data:r,delivery:n,input:i}=e,o={pause:!1};let s=t.mediaCurrentTime,a=t.mediaCompleted;switch(i.kind){case"time":s=Sv(i.currentTimeSeconds,t.mediaCurrentTime);break;case"seek":{const I=Sv(i.currentTimeSeconds,t.mediaCurrentTime);!r.playbackPolicy.allowSeekAhead&&I>t.maxPositionSeconds+s9?(o.seekToSeconds=t.maxPositionSeconds,s=t.maxPositionSeconds):s=I;break}case"ended":s=Sv(i.currentTimeSeconds,t.mediaCurrentTime),a=!0}const l=Math.max(t.maxPositionSeconds,s),c=[...t.visitedCueIdentifiers],u=new Set(c);for(const I of r.cues)u.has(I.identifier)||c9(I,s)&&(u.add(I.identifier),c.push(I.identifier),o.activatedCueIdentifier=I.identifier);const d=new Set(t.completedCueIdentifiers);let f=null;for(const I of r.cues)if(u.has(I.identifier)&&!d.has(I.identifier)){if(!I.holdsPlayback){d.add(I.identifier);continue}if(h_(I,n)){d.add(I.identifier),o.releasedCueIdentifier=I.identifier;continue}f||(f=I)}const h=r.cues.map(I=>I.identifier).filter(I=>d.has(I));o.pause=f!==null;const g=f?.identifier??c[c.length-1],m=h.length===r.cues.length&&n.itemsComplete&&(r.playbackPolicy.requireMediaCompletion?a:!0),v={version:1,mediaCurrentTime:s,maxPositionSeconds:l,mediaCompleted:a,visitedCueIdentifiers:c,completedCueIdentifiers:h,activeCueIdentifier:g,aggregateComplete:m},b=v.mediaCurrentTime!==t.mediaCurrentTime||v.maxPositionSeconds!==t.maxPositionSeconds||v.mediaCompleted!==t.mediaCompleted||v.activeCueIdentifier!==t.activeCueIdentifier||v.aggregateComplete!==t.aggregateComplete||!bk(v.visitedCueIdentifiers,t.visitedCueIdentifiers)||!bk(v.completedCueIdentifiers,t.completedCueIdentifiers);return{state:b?v:t,effects:o,changed:b}}function p_(e){const t=[],r=e.playbackPolicy.pauseOnRequiredCue&&e.hasGate,n=!e.playbackPolicy.allowSeekAhead,i=e.capabilities?e.capabilities.canPause:!0,o=e.capabilities?e.capabilities.canRestrictSeeking:!0;return r&&!i&&t.push({policy:"pause-on-required-cue",capability:"canPause",message:"The media time source cannot pause, so gate cues are advisory: they fire and record state, and playback continues."}),n&&!o&&t.push({policy:"restrict-seek-ahead",capability:"canRestrictSeeking",message:"The media time source cannot restrict seeking, so allowSeekAhead: false is advisory: a learner can seek past cues."}),{pause:r&&!i?"advisory":"enforced",seek:n&&!o?"advisory":"enforced",degradations:t}}function f9(e){const t=new Set(e.state.visitedCueIdentifiers),r=new Set(e.state.completedCueIdentifiers);for(const n of e.data.cues)if(!(!n.holdsPlayback||!n.releaseOn)&&t.has(n.identifier)&&!r.has(n.identifier))return{cueIdentifier:n.identifier,itemRefs:[...n.itemRefs],releaseOn:n.releaseOn,holding:!h_(n,e.delivery),enforcement:e.pauseEnforcement};return null}function m_(e){return e.activation!=="metadata"}function h9(e){const t=[];for(const r of e.cues)if(m_(r))for(const n of r.itemRefs)t.includes(n)||t.push(n);return t}function p9(e,t){const r=new Set(t.visitedCueIdentifiers),n=[];for(const i of e.cues)if(m_(i)&&r.has(i.identifier))for(const o of i.itemRefs)n.includes(o)||n.push(o);return n}function m9(e){const t=e.data.cues.some(n=>n.activation==="gate"),r=p_({playbackPolicy:e.data.playbackPolicy,capabilities:e.capabilities,hasGate:t});return{version:1,stimulusRenderableId:e.data.stimulusRenderableId,cues:e.data.cues,playbackPolicy:e.data.playbackPolicy,mediaAttached:e.capabilities!==null,enforcement:{pause:r.pause,seek:r.seek},degradations:r.degradations,revealedItemIds:p9(e.data,e.state),sequencedItemIds:h9(e.data),activeCueIdentifier:e.state.activeCueIdentifier,gate:f9({data:e.data,state:e.state,delivery:e.delivery,pauseEnforcement:r.pause}),visitedCueIdentifiers:[...e.state.visitedCueIdentifiers],completedCueIdentifiers:[...e.state.completedCueIdentifiers],mediaCurrentTime:e.state.mediaCurrentTime,maxPositionSeconds:e.state.maxPositionSeconds,mediaCompleted:e.state.mediaCompleted,aggregateComplete:e.state.aggregateComplete===!0}}function g_(e){return e?[(e.visitedCueIdentifiers??[]).join(","),(e.completedCueIdentifiers??[]).join(","),(e.revealedItemIds??[]).join(","),e.activeCueIdentifier??"",e.gate?.cueIdentifier??"",e.gate?.holding===!0?"1":"0",e.enforcement?.pause??"",e.enforcement?.seek??"",e.mediaAttached===!0?"1":"0",e.mediaCompleted===!0?"1":"0",e.aggregateComplete===!0?"1":"0",String(Math.floor((e.maxPositionSeconds??0)/l9))].join(":"):""}function wk(e){const t=typeof e=="number"?e:NaN;if(!(!Number.isFinite(t)||t<0))return t}function Sk(e,t){if(!Array.isArray(e))return[];const r=[];for(const n of e){if(typeof n!="string")continue;const i=n.trim();!i||!t.has(i)||r.includes(i)||r.push(i)}return r}function g9(e){return{...e,version:1,visitedCueIdentifiers:[...e.visitedCueIdentifiers],completedCueIdentifiers:[...e.completedCueIdentifiers]}}function v9(e){const{slice:t,data:r}=e;if(!r||!t||typeof t!="object")return null;const n=t;if(n.version!==1)return null;const i=new Set(r.cues.map(u=>u.identifier)),o=lp(),s=wk(n.mediaCurrentTime)??o.mediaCurrentTime,a=Sk(n.visitedCueIdentifiers,i),l=Sk(n.completedCueIdentifiers,i),c=typeof n.activeCueIdentifier=="string"&&i.has(n.activeCueIdentifier)?n.activeCueIdentifier:void 0;return{version:1,mediaCurrentTime:s,maxPositionSeconds:Math.max(wk(n.maxPositionSeconds)??0,s),mediaCompleted:n.mediaCompleted===!0,visitedCueIdentifiers:a,completedCueIdentifiers:l.filter(u=>a.includes(u)),activeCueIdentifier:c,aggregateComplete:n.aggregateComplete===!0}}var y9={canPause:!0,canRestrictSeeking:!0},b9=[{name:"timeupdate",type:"time"},{name:"seeking",type:"seek"},{name:"seeked",type:"seek"},{name:"play",type:"play"},{name:"pause",type:"pause"},{name:"ended",type:"ended"}];function w9(e,t={}){const r={...y9,...t.capabilities??{}},n=new Set;function i(){const a=e.currentTime;return Number.isFinite(a)&&a>=0?a:0}function o(a){const l={type:a,currentTime:i()};for(const c of Array.from(n))try{c(l)}catch{}}const s=b9.map(a=>({name:a.name,handler:()=>o(a.type)}));return{get currentTime(){return i()},get duration(){return e.duration},get paused(){return e.paused},get seekable(){return e.seekable??null},capabilities:r,play(){return e.play()},pause(){e.pause()},seekTo(a){!Number.isFinite(a)||a<0||(e.currentTime=a)},subscribe(a){if(n.add(a),n.size===1)for(const l of s)e.addEventListener(l.name,l.handler);return()=>{if(n.delete(a)&&!(n.size>0))for(const l of s)e.removeEventListener(l.name,l.handler)}}}}function S9(e){return e?e.querySelector("video, audio")??null:null}var I9=Wt('<div class="pie-section-player-content-card-body pie-section-player-passage-content pie-section-player__passage-content svelte-1qmzs9f" data-region="content"><!></div>'),k9=Wt('<div class="pie-section-player-passage-card-anchor svelte-1qmzs9f" aria-hidden="true"></div> <pie-passage-shell><div class="pie-section-player-content-card svelte-1qmzs9f" data-pie-tool-overlay-boundary=""><div class="pie-section-player-content-card-header pie-section-player-passage-header pie-section-player__passage-header svelte-1qmzs9f" data-region="header"><!> <pie-item-toolbar></pie-item-toolbar></div> <!> <!></div></pie-passage-shell>',3),T9={hash:"svelte-1qmzs9f",code:`.pie-section-player-passage-card-anchor.svelte-1qmzs9f {display:none;}pie-section-player-passage-card {display:block;border-radius:var(--pie-section-player-card-radius, 8px);
1339
+ /* Bridge for the hosted passage-player custom element, which reads its
1340
+ own --pie-passage-header-background token and lives outside this
1341
+ package's control. Resolving it here keeps the passage header in
1342
+ sync with the section-player card header without either side
1343
+ hardcoding the other's token name. */--pie-passage-header-background: var(--pie-section-player-card-header-background);}
1344
+
1345
+ /* Same bridge under a dark theme, so the hosted element follows the dark hook. */[data-theme="dark"] pie-section-player-passage-card,
1346
+ pie-theme[theme="dark"] pie-section-player-passage-card {--pie-passage-header-background: var(
1347
+ --pie-section-player-card-header-background-dark,
1348
+ var(--pie-section-player-card-header-background)
1349
+ );}.pie-section-player-content-card.svelte-1qmzs9f {
1350
+ /*
1351
+ * Containing block for frameless tool overlays. The toolkit appends them to
1352
+ * this element (see \`resolveOverlayMountParent\` in the assessment toolkit),
1353
+ * so the card's box is the frame a line reader or a ruler positions and
1354
+ * clamps against. Without it those overlays resolve against whichever
1355
+ * ancestor happens to be positioned, and a tool placed on this card can open
1356
+ * outside it.
1357
+ */position:relative;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);}pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-passage-content :focus-visible) {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:2px;}
1358
+
1359
+ /* Multi-passage sets render their own tab strip (role="tablist") as the
1360
+ first thing inside the body, which already reads as a header. Drop the
1361
+ gap and duplicate rule above it so the two headers blend into one band;
1362
+ a single passage has no tablist and keeps the default spacing. */pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-content-card-body [role="tablist"]) .pie-section-player-content-card-header {border-bottom:none;}pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-content-card-body [role="tablist"]) .pie-section-player-content-card-body {padding:0 0 1rem;}.pie-section-player-content-card-header.svelte-1qmzs9f {position:relative;display:flex;flex-wrap:wrap;align-items:center;gap:0.75rem;padding:0.75rem 1rem;overflow:visible;border-bottom:1px solid var(--pie-border-light, #e5e7eb);
1363
+ /* Header fill is intentionally transparent by default. Hosts/themes
1364
+ opt-in to a solid color via --pie-section-player-card-header-background
1365
+ (e.g. a brand Bluegreen tint) without this framework encoding a palette. */background:var(--pie-section-player-card-header-background, transparent);
1366
+ /* Default just inside the card radius to avoid a double-radius effect with the border. */border-top-left-radius:var(
1367
+ --pie-section-player-card-header-radius,
1368
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1369
+ );border-top-right-radius:var(
1370
+ --pie-section-player-card-header-radius,
1371
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1372
+ );}
1373
+
1374
+ /*
1375
+ * Dark themes get their own opt-in fill: a host's light-theme brand tint
1376
+ * surviving into a dark theme is the failure this avoids. Unset, it falls
1377
+ * back to the single light hook, so a host that sets only that one is
1378
+ * unaffected. Keyed off the selectors the theme package writes its dark
1379
+ * tokens under — see renderTokensCss in packages/theme/src/theme-css.ts.
1380
+ */[data-theme="dark"] .pie-section-player-content-card-header.svelte-1qmzs9f,
1381
+ pie-theme[theme="dark"] .pie-section-player-content-card-header.svelte-1qmzs9f {background:var(
1382
+ --pie-section-player-card-header-background-dark,
1383
+ var(--pie-section-player-card-header-background, transparent)
1384
+ );}
1385
+
1386
+ /* Any heading level, not \`h2\`: the card renders at \`base-heading-level\`, so
1387
+ the tag is composition context rather than a fixed choice, and a host that
1388
+ nests the player deeper got an unstyled title. */.pie-section-player-content-card-header.svelte-1qmzs9f :is(h1:where(.svelte-1qmzs9f), h2:where(.svelte-1qmzs9f), h3:where(.svelte-1qmzs9f), h4:where(.svelte-1qmzs9f), h5:where(.svelte-1qmzs9f), h6:where(.svelte-1qmzs9f)) {position:relative;
1389
+ /* Was supplied by the content stylesheet's heading reset, which now
1390
+ applies inside a player's content root only. */line-height:1.2;min-width:0;overflow-wrap:anywhere;z-index:0;margin:0;
1391
+ /* Reads the scale rather than inheriting it: the card wraps the passage
1392
+ shell that \`font-sizes.css\` scales, so nothing above this rule carries
1393
+ the scaled size. Root-relative, so it does not compound with the shell. */font-size:calc(0.95rem * var(--pie-font-scale, 1));font-weight:600;
1394
+ /* Default to the themed body text color so titles stay legible across
1395
+ DaisyUI themes; --pie-header-text remains a host opt-in override. */color:var(--pie-header-text, var(--pie-text, #111827));}.pie-section-player-content-card-header.svelte-1qmzs9f pie-item-toolbar:where(.svelte-1qmzs9f) {position:relative;min-width:0;max-width:100%;z-index:1;margin-left:auto;}
1396
+
1397
+ /* Match item-card overlay layering above the pane's scroll hint (10). */.pie-section-player-content-card-header.svelte-1qmzs9f pie-item-toolbar[data-pie-header-overlay-active="true"] {z-index:11;}.pie-section-player-content-card-body.svelte-1qmzs9f {padding:1rem;color:var(--pie-text, #111827);}`};function E9(e,t){pn(t,!0),Ln(e,T9);let r=D(t,"passage",7),n=D(t,"baseHeadingLevel",7,2),i=D(t,"resolvedPlayerTag",7,"div"),o=D(t,"playerAction",7,(W,se)=>{}),s=D(t,"playerParams",7),a=D(t,"passageToolbarTools",7),l=D(t,"toolRegistry",7,null),c=D(t,"hostButtons",23,()=>[]),u=D(t,"timedMediaStimulus",7,!1);const d=q(()=>ow(n()));let f=Be(null);const h=q(()=>Ba(p(f)));let g=Be(null),m=Be(null),v=Be(null),b=Be(null),I=Be(!1);const C=Dr(()=>`pie-section-player-passage-card-heading-${r()?.id??Math.random().toString(36).slice(2,10)}`),x=q(()=>(p(I)?p(m):null)||i()),$=q(()=>(p(I)?p(v):null)||o()),P=q(()=>(p(I)?p(b):null)||null),L=q(()=>{const W=p(h).t("player.passage");if(!p(P))return W;try{const se=p(P)({kind:"passage",passage:r(),defaultTitle:W});return typeof se!="string"?W:se.trim()||W}catch{return W}}),J=q(()=>`${C}-media`),V=q(()=>`${C}-lead`),Y=q(()=>CT({kind:"passage",itemId:r()?.id??"",assessmentId:p(f)?.assessmentId,sectionId:p(f)?.sectionId}));vt(()=>{if(p(g))return sf(p(g),W=>{be(f,W,!0)})});function Pe(){be(I,!1),be(m,null),be(v,null),be(b,null)}function M(W){!W||typeof W!="object"||(typeof W.resolvedPlayerTag=="string"&&W.resolvedPlayerTag.trim()&&be(m,W.resolvedPlayerTag,!0),typeof W.playerAction=="function"&&be(v,W.playerAction,!0),typeof W.cardTitleFormatter=="function"&&be(b,W.cardTitleFormatter,!0))}let H=Be(null),ne=null;function ae(W){const se=oa(p(g));se&&Vl(se,fD,W)}vt(()=>{if(!u())return;const W=p(H),se=r()?.id;if(!W||!se)return;const _e=()=>{const le=S9(W);if(le!==ne){if(ne&&!le){ne=null,ae({renderableId:se,action:"detach",origin:"native-adapter"});return}le&&(ne=le,ae({renderableId:se,action:"attach",source:w9(le),origin:"native-adapter"}))}};let Ue=!1;queueMicrotask(()=>{Ue||Dr(()=>_e())});const it=new MutationObserver(()=>Dr(()=>_e()));return it.observe(W,{childList:!0,subtree:!0}),()=>{Ue=!0,it.disconnect(),ne&&(ne=null,ae({renderableId:se,action:"detach",origin:"native-adapter"}))}}),Pm(()=>{const W=oa(p(g));if(!W)return;be(I,!0);const se=l_(W,M);return()=>{se(),Pe()}});var ye={get passage(){return r()},set passage(W){r(W),N()},get baseHeadingLevel(){return n()},set baseHeadingLevel(W=2){n(W),N()},get resolvedPlayerTag(){return i()},set resolvedPlayerTag(W="div"){i(W),N()},get playerAction(){return o()},set playerAction(W=(se,_e)=>{}){o(W),N()},get playerParams(){return s()},set playerParams(W){s(W),N()},get passageToolbarTools(){return a()},set passageToolbarTools(W){a(W),N()},get toolRegistry(){return l()},set toolRegistry(W=null){l(W),N()},get hostButtons(){return c()},set hostButtons(W=[]){c(W),N()},get timedMediaStimulus(){return u()},set timedMediaStimulus(W=!1){u(W),N()}},te=k9(),z=bn(te);$r(z,W=>be(g,W),()=>p(g));var A=mr(z,2);ve(()=>Ce(A,"item-id",r().id)),Ce(A,"content-kind","rubric-block-stimulus"),ve(()=>Ce(A,"item",r()));var K=Er(A),Q=Er(K),_=Er(Q);Cp(_,()=>`h${p(d)}`,!1,(W,se)=>{FE(W,()=>({id:C,"data-pie-tool-overlay-protect":!0,class:""}),void 0,void 0,void 0,"svelte-1qmzs9f");var _e=xE();ve(()=>ks(_e,p(L))),ht(se,_e)});var B=mr(_,2);ve(()=>Ce(B,"item-id",r().id)),ve(()=>Ce(B,"catalog-id",r().id)),ve(()=>Ce(B,"tools",a())),Ce(B,"content-kind","rubric-block-stimulus"),Ce(B,"size","md"),ve(()=>Ce(B,"toolRegistry",l())),ve(()=>Ce(B,"hostButtons",c())),yn(B,1,"svelte-1qmzs9f"),Tr(Q);var U=mr(Q,2);uw(U,{get regionId(){return p(V)},get surface(){return c_},get ownerContext(){return p(Y)},get runtimeContext(){return p(f)},get toolRegistry(){return l()}});var fe=mr(U,2);{const W=_e=>{var Ue=I9(),it=Er(Ue);Cp(it,()=>p(x),!1,(le,de)=>{OE(le,(Ne,Ae)=>p($)?.(Ne,Ae),s),yn(le,0,"svelte-1qmzs9f")}),Tr(Ue),$r(Ue,le=>be(H,le),()=>p(H)),ht(_e,Ue)};let se=q(()=>p(h).t("player.resizePassageAndMediaA11y"));cw(fe,{get regionId(){return p(J)},get ownerContext(){return p(Y)},get runtimeContext(){return p(f)},get toolRegistry(){return l()},get dividerAriaLabel(){return p(se)},content:W,$$slots:{content:!0}})}return Tr(K),Tr(A),ht(e,te),mn(ye)}C9("pie-section-player-passage-card",Tn(E9,{passage:{type:"Object"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},resolvedPlayerTag:{attribute:"resolved-player-tag",type:"String"},playerAction:{type:"Object"},playerParams:{attribute:"player-params",type:"Object"},passageToolbarTools:{attribute:"passage-toolbar-tools",type:"String"},timedMediaStimulus:{attribute:"timed-media-stimulus",type:"Boolean"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"}},[],[],void 0,ja));function C9(e,t){customElements.get(e)||customElements.define(e,t)}function x9(e){let t=Be(ui({status:"idle"})),r=0;return vt(()=>{const n=e();if(!n){be(t,{status:"idle"},!0);return}const i=++r;be(t,{status:"pending"},!0),n.then(o=>{i===r&&be(t,{status:"resolved",data:o},!0)},o=>{i===r&&be(t,{status:"rejected",error:o},!0)})}),{get current(){return p(t)}}}var v_=Cu(Symbol.for("@pie-players/pie-section-player/layout-context"));function dw(e,t){return af(e,v_,t)}function R9(e,t){const r=new Ql(e,{context:v_,initialValue:t});return r.connect(),{setValue:n=>r.setValue(n),disconnect:()=>r.disconnect()}}function P9(e){const t=e.warn??(l=>console.warn(l)),r={items:[],passages:[]},n=new Set,i=new Set;let o=!1;const s=()=>({items:r.items[0]??null,passages:r.passages[0]??null}),a=l=>{const c=r[l].length;if(o||c<2||n.has(l))return;n.add(l);const u=`pie-section-player-${l}-pane`;t(`[pie-section-player] ${c} <${u}> elements are inside one section player. The first one connected renders and the rest render nothing until it disconnects. Reported once per section player.`)};return{register(l,c){const u=r[l];if(u.includes(c)||u.push(c),e.onChange(s()),u.length>1&&!n.has(l)){const d=setTimeout(()=>{i.delete(d),a(l)},0);i.add(d)}return()=>{const d=u.indexOf(c);d<0||(u.splice(d,1),o||e.onChange(s()))}},active:s,dispose(){o=!0;for(const l of i)clearTimeout(l);i.clear()}}}var _9=Wt('<p class="pie-section-player-timed-media-status svelte-potd9r" data-pie-timed-media-status="" aria-live="polite"> </p>'),A9=Wt('<div class="pie-section-player-content-card svelte-potd9r"><div class="pie-section-player-content-card-body pie-section-player-item-content pie-section-player__item-content svelte-potd9r"> </div></div>'),$9=Wt("<pie-section-player-item-card></pie-section-player-item-card>",2),M9=Wt("<nds-icon-button></nds-icon-button>",2),O9=Wt('<button type="button" class="pie-section-player-scroll-hint__button svelte-potd9r"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false"><path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg></button>'),L9=Wt('<!> <!> <div class="pie-section-player-scroll-hint svelte-potd9r"><!></div>',1),N9=Wt('<div style="display:none" aria-hidden="true"></div> <!>',1),D9={hash:"svelte-potd9r",code:`:host {display:flex;flex-direction:column;gap:1rem;min-height:0;min-width:0;}.pie-section-player-scroll-hint.svelte-potd9r {position:sticky;bottom:0;height:56px;margin-top:calc(-56px - 1rem);background:linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, var(--pie-white, #fff) 100%);display:flex;align-items:flex-start;justify-content:center;padding-top:4px;z-index:10;
1398
+ /* so the buttons behind are still clickable, but the hint itself is not */pointer-events:none;}
1399
+
1400
+ /* so the "scroll down" button still works */.pie-section-player-scroll-hint.svelte-potd9r nds-icon-button:where(.svelte-potd9r),
1401
+ .pie-section-player-scroll-hint__button.svelte-potd9r {pointer-events:auto;}.pie-section-player-scroll-hint.svelte-potd9r nds-icon-button:where(.svelte-potd9r) {
1402
+ /* NDS palette bridge — keep in sync with the copies in tool-tts-inline
1403
+ and assessment-toolkit ItemToolBar (asserted by
1404
+ scripts/check-theme-tokens.mjs). The vendored button paints its glyph,
1405
+ fill, hover ring and focus ring from the NDS design-system palette,
1406
+ which no PIE theme sets, so this scroll-down control kept a #146eb3
1407
+ glyph on a #f3f5f7 pill under every theme while the fallback button
1408
+ beside it followed the tokens. */--color-interactive-blue: var(--pie-button-color, var(--pie-text, #222));--color-new-gray: var(--pie-background-dark, #f3f5f7);--color-primary-white: var(--pie-white, #ffffff);--color-primary-black: var(--pie-text, #000000);--color-focus-blue: var(--pie-button-focus-outline, #2b87ff);}
1409
+
1410
+ /* Non-NDS fallback button: a compact circular control mirroring the NDS
1411
+ tertiary icon button's footprint. */.pie-section-player-scroll-hint__button.svelte-potd9r {display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;padding:0;border:1px solid var(--pie-border, #c6c6c6);border-radius:50%;background:var(--pie-white, #fff);color:var(--pie-text, #222);cursor:pointer;}.pie-section-player-scroll-hint__button.svelte-potd9r:focus-visible {outline:2px solid var(--pie-button-focus-outline, var(--pie-primary, #0066cc));outline-offset:2px;}
1412
+
1413
+ /* Keep content readable when space is scarce, including browser zoom.
1414
+ The chevron retains its full target size; window width ratios are not zoom. */
1415
+ @media (max-width: 839px), (max-height: 480px) {.pie-section-player-scroll-hint.svelte-potd9r {background:none;}
1416
+ }.pie-section-player-content-card.svelte-potd9r {border:1px solid var(--pie-border-light, #e5e7eb);border-radius:8px;background:var(--pie-background, #fff);}
1417
+
1418
+ /* Painted only from \`--pie-*\` chains, so it follows every base theme and colour
1419
+ scheme without a hook of its own — same rule as the formative status line, and
1420
+ colour is never the only signal here either. */.pie-section-player-timed-media-status.svelte-potd9r {margin:0;padding:0.5rem 0.75rem;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);font-size:calc(0.9rem * var(--pie-font-scale, 1));}
1421
+
1422
+ /* Collapsed, not removed: \`display: none\` takes the element out of the
1423
+ accessibility tree, and a live region that did not exist when its first message
1424
+ arrived does not announce it (WCAG 4.1.3). The region is rendered before it has
1425
+ content for exactly that reason. */.pie-section-player-timed-media-status.svelte-potd9r:empty {padding:0;border:0;block-size:0;overflow:hidden;}
1426
+
1427
+ /* The gated card takes focus, so it needs a visible focus indicator of its own;
1428
+ the card is not otherwise focusable. */pie-section-player-item-card [data-pie-timed-media-gate="holding"]:focus-visible {outline:3px solid
1429
+ var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:2px;}.pie-section-player-content-card-body.svelte-potd9r {padding:1rem;}`};function j9(e,t){pn(t,!0),Ln(e,D9);const r=[],n={},i=[],o=t.$$host;let s=Be(null);vt(()=>dw(o,Re=>{be(s,Re)}));const a=q(()=>p(s)?.registerPane??null);vt(()=>p(a)?.("items",o));const l=q(()=>p(s)?.activePanes.items===o),c=q(()=>p(s)?.items??r),u=q(()=>p(s)?.compositionModel??$0),d=q(()=>p(s)?.resolvedPlayerEnv??n),f=q(()=>p(s)?.resolvedPlayerAttributes??n),h=q(()=>p(s)?.resolvedPlayerProps??n),g=q(()=>p(s)?.playerStrategy??"preloaded"),m=q(()=>p(s)?.baseHeadingLevel??2),v=q(()=>p(s)?.itemToolbarTools??""),b=q(()=>p(s)?.toolRegistry??null),I=q(()=>p(s)?.itemHostButtons??i),C=q(()=>p(s)?.iifeBundleHost??""),x=q(()=>p(s)?.preloadedRenderables??r),$=q(()=>p(s)?.preloadedRenderablesSignature??""),P=q(()=>p(s)?.componentTag??"pie-section-player-items-pane"),L=q(()=>p(s)?.preloadEnabled??!0),J=q(()=>p(s)?.reportWarmup??null),V=q(()=>r_(p(P))),Y=q(()=>JSON.stringify(p(x).map((Re,Ze)=>{const Ye=Re??{},yt=typeof Ye.id=="string"&&Ye.id?Ye.id:`renderable-${Ze}`,re=Ye.config?.elements??{};return`${yt}:${Object.entries(re??{}).filter(([Qe,lt])=>typeof Qe=="string"&&Qe.length>0&&typeof lt=="string"&&lt.length>0).sort(([Qe],[lt])=>Qe.localeCompare(lt)).map(([Qe,lt])=>`${Qe}=${lt}`).join(",")}`}))),Pe=q(()=>JSON.stringify({active:p(l),preloadEnabled:p(L),strategy:p(g),renderables:p(Y),iifeBundleHost:p(C),mode:p(h)?.mode??null,hosted:p(h)?.hosted??null,envMode:p(d)?.mode??null,loaderOptions:p(h)?.loaderOptions??null})),M=x9(()=>(p(Pe),Dr(()=>p(l))?p(L)?Dr(()=>B6({strategy:p(g),renderables:p(x),resolvedPlayerProps:p(h),resolvedPlayerEnv:p(d),iifeBundleHost:p(C),logger:p(V),onBundleRetryStatus:Re=>{let Ze=null;try{Ze=nb({strategy:p(g),resolvedPlayerProps:p(h),resolvedPlayerEnv:p(d),iifeBundleHost:p(C)})}catch{Ze=null}const Ye=Math.max(Re.retryDelayMs??0,1),yt=Math.max(1,Math.ceil(Re.timeoutMs/Ye));p(s)?.reportPreloadRetry(o,{componentTag:p(P),stage:"iife-load",attempt:Re.attempt,maxRetries:yt,error:Re.reason??Re.state,strategy:p(g),bundleType:ak(Ze),bundleHost:lk(Ze),renderablesCount:p(x).length})}})):Dr(()=>Promise.resolve()):null)),H=q(()=>M.current.status==="resolved"),ne=q(()=>p(H)?"loaded":M.current.status==="rejected"?"failed":"pending");let ae=Be(null);vt(()=>{M.current.status==="resolved"&&be(ae,p(Y),!0)});const ye=q(()=>p(H)||p(ae)===p(Y));vt(()=>{p(l),p(J)?.(o,{warmup:p(ne),renderablesSignature:p($)})});function te(Re){return Re instanceof sp?{stage:Re.stage,cause:Re.cause}:{stage:p(g)==="esm"?"esm-load":"iife-load",cause:Re}}function z(Re){const{stage:Ze,cause:Ye}=te(Re),yt=P0({kind:"element-preload",source:p(P),message:rb(Ze,Ye),details:[`stage=${Ze}`,`strategy=${p(g)}`,`renderablesCount=${p(x).length}`],recoverable:!1,scope:"cohort",cause:Ye});try{p(Ae)?.reportSectionError?.(yt)}catch(lt){p(V).warn("element-preload section error report failed:",lt)}const re=p(Ae)?.toolkitCoordinator;if(typeof re?.reportFrameworkError=="function")try{re.reportFrameworkError(yt);return}catch(lt){p(V).warn("element-preload framework error report failed:",lt)}const Qe=p(Ue)?.parentElement;if(Qe){Qe.dispatchEvent(new CustomEvent("framework-error",{detail:yt,bubbles:!0,composed:!0}));return}p(V).warn(yt.message,Ye)}function A(Re){const{stage:Ze,cause:Ye}=te(Re);p(V).error(rb(Ze,Ye));let yt=null;try{yt=nb({strategy:p(g),resolvedPlayerProps:p(h),resolvedPlayerEnv:p(d),iifeBundleHost:p(C)})}catch{yt=null}p(s)?.reportPreloadError(o,{componentTag:p(P),stage:Ze,error:eg(Ye),strategy:p(g),bundleType:ak(yt),bundleHost:lk(yt),renderablesCount:p(x).length})}vt(()=>{const Re=M.current;Re.status==="rejected"&&Dr(()=>{z(Re.error),A(Re.error)})});const K=q(()=>Number.isFinite(p(u)?.currentItemIndex)?Math.max(0,Number(p(u).currentItemIndex)):-1),Q=q(()=>p(u)?.timedMedia??null),_=q(()=>p(Q)?.gate??null),B=q(()=>p(_)?.holding===!0);function U(Re){const Ze=p(c).findIndex(Ye=>hk({compositionModel:p(u),item:Ye})===Re);return Ze>=0?Ze+1:1}let fe=Be(""),W=null,se=0,_e=null;vt(()=>{const Re=p(Q),Ze=p(B)?p(_)?.cueIdentifier??null:null,Ye=Re?.revealedItemIds.length??0,yt=p(_)?.enforcement==="enforced",re=p(_)?.itemRefs[0]??"",Qe=Re?.revealedItemIds[Ye-1]??"";Dr(()=>{if(!Re){be(fe,""),W=null,se=0;return}if(Ze&&Ze!==W){W=Ze,se=Ye,_e=Ze,be(fe,p(ce).t(yt?"player.timedMedia.playbackPaused":"player.timedMedia.playbackAdvisory",{position:U(re)}),!0);return}if(!Ze&&W){W=null,se=Ye,be(fe,p(ce).t("player.timedMedia.playbackReleased"),!0);return}if(p(fe)===""){se=Ye,be(fe,Ye===0?p(ce).t("player.timedMedia.waitingForMedia"):p(ce).t("player.timedMedia.questionAvailable",{position:U(Qe)}),!0);return}Ye!==se&&(se=Ye,be(fe,Ye===0?p(ce).t("player.timedMedia.waitingForMedia"):p(ce).t("player.timedMedia.questionAvailable",{position:U(Qe)}),!0))})}),vt(()=>{const Re=p(B)?p(_)?.cueIdentifier??null:null;Re&&Dr(()=>{_e===Re&&(_e=null,queueMicrotask(()=>{(p(Ue)?.parentElement??null)?.querySelector('[data-pie-timed-media-gate="holding"]')?.focus()}))})});let Ue=Be(null),it=Be(!1),le=Be(null),de=Be(void 0);const Ne=q(()=>p(de)===!0);let Ae=Be(void 0);const ce=q(()=>Ba(p(Ae)));vt(()=>{if(p(Ue))return sf(p(Ue),Re=>{be(de,Re?.ndsIcons,!0),be(Ae,Re,!0)})});const ie=()=>p(le)?.scrollBy({top:150,behavior:"smooth"}),De=Re=>{for(let Ze=Re;Ze&&Ze!==document.body;Ze=Ze.parentElement){const{overflowY:Ye}=getComputedStyle(Ze);if(Ye==="auto"||Ye==="scroll"||Ye==="overlay")return Ze}return null};Pm(()=>{const Re=p(Ue)?.parentElement??null;if(!Re)return;let Ze=null,Ye=null,yt=null,re=null;const Qe=()=>{const st=Ze;if(!st)return;const Rt=st.scrollHeight,bt=st.clientHeight,ft=Rt-st.scrollTop<=bt+1,me=Rt>bt&&!ft;me!==p(it)&&be(it,me,!0)},lt=()=>{const st=De(Re.parentElement);st&&(Ze=st,be(le,st,!0),yt=new ResizeObserver(Vt),yt.observe(st),st.addEventListener("scroll",Vt,{passive:!0}),re=()=>st.removeEventListener("scroll",Vt))},zt=()=>{Ye=null,Ze||lt(),Qe()},Vt=()=>{Ye===null&&(Ye=setTimeout(zt,0))},ur=new MutationObserver(Vt);return ur.observe(Re,{childList:!0,subtree:!0,characterData:!0}),Vt(),()=>{Ye!==null&&(clearTimeout(Ye),Ye=null),ur.disconnect(),yt?.disconnect(),re?.()}});var Je=N9(),At=bn(Je);$r(At,Re=>be(Ue,Re),()=>p(Ue));var pt=mr(At,2),Et=Re=>{var Ze=L9(),Ye=bn(Ze),yt=bt=>{var ft=_9(),me=La(ft,!0);ve(()=>ks(me,p(fe))),ht(bt,ft)};cn(Ye,bt=>{p(Q)&&bt(yt)});var re=mr(Ye,2),Qe=bt=>{var ft=A9(),me=Er(ft),Nt=La(me,!0);Tr(ft),ve(tr=>ks(Nt,tr),[()=>p(ce).t(M.current.status==="rejected"?"player.sectionLoadError":"player.loadingSection")]),ht(bt,ft)},lt=bt=>{var ft=Ys(),me=bn(ft);ME(me,19,()=>p(c),(Nt,tr)=>Nt.id||tr,(Nt,tr,mt)=>{const vr=q(()=>hk({compositionModel:p(u),item:p(tr)})),dr=q(()=>bH({compositionModel:p(u),canonicalItemId:p(vr)})),Ir=q(()=>wH({compositionModel:p(u),canonicalItemId:p(vr)}));var Qt=$9();ve(()=>Ce(Qt,"hidden",p(Ir)?.pending===!0)),ve(()=>Ce(Qt,"item",p(tr))),ve(()=>Ce(Qt,"itemIndex",p(mt))),ve(()=>Ce(Qt,"itemCount",p(c).length)),ve(()=>Ce(Qt,"isCurrent",p(mt)===p(K))),ve(()=>Ce(Qt,"canonicalItemId",p(vr))),ve(Nr=>Ce(Qt,"itemSettings",Nr),[()=>TH({compositionModel:p(u),item:p(tr)})]),ve(()=>Ce(Qt,"baseHeadingLevel",p(m))),ve(Nr=>Ce(Qt,"playerParams",Nr),[()=>kH({item:p(tr),compositionModel:p(u),resolvedPlayerEnv:p(d),resolvedPlayerAttributes:p(f),resolvedPlayerProps:p(h),playerStrategy:p(g),itemIndex:p(mt),baseHeadingLevel:p(m),formativeView:p(dr)})]),ve(()=>Ce(Qt,"formativeView",p(dr))),ve(()=>Ce(Qt,"timedMediaView",p(Ir))),ve(()=>Ce(Qt,"itemToolbarTools",p(v))),ve(()=>Ce(Qt,"toolRegistry",p(b))),ve(()=>Ce(Qt,"hostButtons",p(I))),ht(Nt,Qt)}),ht(bt,ft)};cn(re,bt=>{p(ye)?bt(lt,-1):bt(Qe)});var zt=mr(re,2);let Vt;var ur=Er(zt),st=bt=>{var ft=M9();Ce(ft,"variant","tertiary"),Ce(ft,"size","small"),Ce(ft,"icon-name","chevron-down"),ve(me=>Ce(ft,"button-aria-label",me),[()=>p(ce).t("player.scrollDownA11y")]),yn(ft,1,"svelte-potd9r"),fo("click",ft,ie),ht(bt,ft)},Rt=bt=>{var ft=O9();ve(me=>at(ft,"aria-label",me),[()=>p(ce).t("player.scrollDownA11y")]),fo("click",ft,ie),ht(bt,ft)};cn(ur,bt=>{p(Ne)?bt(st):bt(Rt,-1)}),Tr(zt),ve(()=>Vt=Xl(zt,"",Vt,{visibility:p(it)?"visible":"hidden"})),ht(Re,Ze)};cn(pt,Re=>{p(l)&&Re(Et)}),ht(e,Je),mn()}Pu(["click"]);z9("pie-section-player-items-pane",Tn(j9,{},[],[]));function z9(e,t){customElements.get(e)||customElements.define(e,t)}function Hf(e){let t=Be(null);vt(()=>{const n=e();if(n)return sf(n,i=>{be(t,i,!0)})});const r=q(()=>Ba(p(t)));return{get provider(){return p(r)},get locale(){return p(r).getLocale()},get direction(){return p(r).getDirection?.()??"ltr"},t(n,i){return p(r).t(n,i)},plural(n,i){return p(r).plural?.(n,i)??p(r).t(n,i)}}}var B9=Wt('<div class="pie-section-player-content-card svelte-1mpods8"><div class="pie-section-player-content-card-body pie-section-player-passage-content pie-section-player__passage-content svelte-1mpods8"> </div></div>'),F9=Wt("<pie-section-player-passage-card></pie-section-player-passage-card>",2),H9={hash:"svelte-1mpods8",code:":host {display:flex;flex-direction:column;gap:1rem;min-height:0;min-width:0;}.pie-section-player-content-card.svelte-1mpods8 {border:1px solid var(--pie-border-light, #e5e7eb);border-radius:8px;background:var(--pie-background, #fff);}.pie-section-player-content-card-body.svelte-1mpods8 {padding:1rem;}"};function U9(e,t){pn(t,!0),Ln(e,H9);const r=[],n={},i=[],o=t.$$host;let s=Be(null);vt(()=>dw(o,Pe=>{be(s,Pe)}));const a=q(()=>p(s)?.registerPane??null);vt(()=>p(a)?.("passages",o));const l=q(()=>p(s)?.activePanes.passages===o),c=q(()=>p(s)?.passages??r),u=q(()=>p(s)?.elementsLoaded===!0),d=q(()=>p(s)?.resolvedPlayerEnv??n),f=q(()=>p(s)?.resolvedPlayerAttributes??n),h=q(()=>p(s)?.resolvedPlayerProps??n),g=q(()=>p(s)?.playerStrategy??"preloaded"),m=q(()=>p(s)?.baseHeadingLevel??2),v=q(()=>p(s)?.passageToolbarTools??""),b=q(()=>p(s)?.toolRegistry??null),I=q(()=>p(s)?.passageHostButtons??i),C=q(()=>p(s)?.compositionModel??null);let x=Be(null);const $=Hf(()=>p(x)),P=q(()=>p(C)?.timedMedia?.stimulusRenderableId??""),L=q(()=>{if(!p(P))return p(c);const Pe=p(c).filter(M=>M.id===p(P));return Pe.length===0?p(c):[...Pe,...p(c).filter(M=>M.id!==p(P))]});var J=Ys(),V=bn(J),Y=Pe=>{var M=Ys(),H=bn(M),ne=ye=>{var te=B9(),z=Er(te),A=La(z,!0);Tr(te),$r(te,K=>be(x,K),()=>p(x)),ve(K=>ks(A,K),[()=>$.t("player.loadingPassage")]),ht(ye,te)},ae=ye=>{var te=Ys(),z=bn(te);ME(z,19,()=>p(L),(A,K)=>A.id||K,(A,K)=>{var Q=F9();ve(()=>Ce(Q,"passage",p(K))),ve(()=>Ce(Q,"baseHeadingLevel",p(m))),ve(()=>Ce(Q,"timedMediaStimulus",!!p(P)&&p(K).id===p(P))),ve(_=>Ce(Q,"playerParams",_),[()=>yH({passage:p(K),resolvedPlayerEnv:p(d),resolvedPlayerAttributes:p(f),resolvedPlayerProps:p(h),playerStrategy:p(g),baseHeadingLevel:p(m)})]),ve(()=>Ce(Q,"passageToolbarTools",p(v))),ve(()=>Ce(Q,"toolRegistry",p(b))),ve(()=>Ce(Q,"hostButtons",p(I))),ht(A,Q)}),ht(ye,te)};cn(H,ye=>{p(u)?ye(ae,-1):ye(ne)}),ht(Pe,M)};cn(V,Pe=>{p(l)&&p(c).length>0&&Pe(Y)}),ht(e,J),mn()}q9("pie-section-player-passages-pane",Tn(U9,{},[],[]));function q9(e,t){customElements.get(e)||customElements.define(e,t)}function tg(e,t){const r=e.target;return r===t?!0:r instanceof Element&&r.localName==="pie-section-player-base"&&(t.shadowRoot??t).querySelector("pie-section-player-base")===r}function W9(e){const t=e;return typeof t?.canRequestTool!="function"||typeof t.requestTool!="function"?null:t}var V9=[{toolId:"dictionary",label:"Look up selected text in dictionary",tooltip:"Look up",icon:"book-open"},{toolId:"pictureDictionary",label:"Show pictures for selected text",tooltip:"Show pictures",icon:"photo"}];function G9(e){const t=W9(e.toolkitCoordinator);return t?V9.map(r=>{const n=_H(r.icon)??void 0;return{id:r.toolId,label:r.label,tooltip:r.tooltip,iconSvg:n,isAvailable:()=>t.canRequestTool(r.toolId),run:i=>{const o=i.text.trim();o&&t.requestTool({toolId:r.toolId,params:{term:o}})}}}):[]}var Y9="__pieToolElementUnmount",Ik=new WeakMap;function Uf(e,t,r){const n=e.toolCoordinator;if(!n)return r();let i=Ik.get(n);const o=i?.get(t);if(o?.isConnected)return o;const s=r();return i||(i=new Map,Ik.set(n,i)),i.set(t,s),s[Y9]=()=>{queueMicrotask(()=>{!s.isConnected&&i.get(t)===s&&i.delete(t)})},s}function yc(e,t,r,n={}){const{toolId:i}=e,o=aw(i,r),s={toolId:i,label:e.name,icon:typeof e.icon=="function"?e.icon(t):e.icon,disabled:!1,ariaLabel:r.i18n.t(`tools.${i}.buttonA11y`),tooltip:r.i18n.t(`tools.${i}.tooltip`),onClick:()=>r.toggleTool(i),active:o.isActive()},a=r.componentOverrides??{},l=Uf(r,o.fullToolId,()=>$f(i,t,r,a));return l.setAttribute("tool-id",o.fullToolId),n.surface==="frameless"&&jH(l,"frameless"),{toolId:i,button:s,elements:[{element:l,mount:"after-buttons",...n.surface==="frameless"?{container:"content-boundary"}:{},...n.shell?{shell:{title:ED(e,r.i18n),draggable:!0,closeable:!0,...n.shell}}:{}}],sync:()=>{lw({button:s,overlay:l,isActive:o.isActive})},subscribeActive:o.subscribeActive}}var K9={toolId:"lineReader",name:"Line Reader",description:"Reading guide overlay",nameKey:"tools.lineReader.name",descriptionKey:"tools.lineReader.description",icon:"bars-3",supportedLevels:["section","passage","rubric","item"],isVisibleInContext(e){return Mf(e)},renderToolbar(e,t){return yc(this,e,t,{surface:"frameless"})}},X9={toolId:"theme",name:"Theme",description:"Accessible themes and contrast",nameKey:"tools.theme.name",descriptionKey:"tools.theme.description",icon:"swatch",supportedLevels:["assessment","section"],isVisibleInContext(e){return!0},renderToolbar(e,t){return yc(this,e,t,{shell:{resizable:!1,initialWidth:520,initialHeight:380,minWidth:420,minHeight:300}})}},J9={toolId:"annotationToolbar",name:"Highlighter",description:"Highlight and annotate text",nameKey:"tools.annotationToolbar.name",descriptionKey:"tools.annotationToolbar.description",icon:"highlighter",activation:"selection-gateway",singletonScope:"section",surfaces:["section-overlay"],supportedLevels:["passage","rubric","item","element"],isVisibleInContext(e){return Mf(e)},renderSurface(e){const t=e.componentOverrides??{},r=x0(e.toolId,t);if(typeof customElements<"u"&&!customElements.get(r))return null;const n=document.createElement(r),i=o=>{n.enabled=!0,n.selectionActions=G9(o.services)};return i(e),{element:n,sync:i}},renderToolbar(e,t){return yc(this,e,t)}},Q9="transcript";var ob="pie-tool-audio-transcript",Z9="always",eU=e=>!!e&&e.catalog==="transcript",tU=e=>typeof e.visibility=="string"&&e.visibility.trim().toLowerCase()===Z9,rU=e=>typeof e.content=="string"?e.content.trim():"";function nU(e){if(!e.catalogs)return null;let t=null;for(const{catalogId:r,card:n}of e.catalogs.cards){if(!eU(n))continue;const i=rU(n);if(!i)continue;const o={catalogId:r,text:i,language:typeof n.language=="string"?n.language:void 0,always:tU(n)};if(o.always)return o;t??(t=o)}return t&&e.granted?t:null}var iU="content-lead";function oU(){const e=document.createElement("section");e.className=ob,e.setAttribute("role","region");const t=document.createElement("p");return t.className=`${ob}__text`,e.appendChild(t),e}var kk=(e,t)=>{const r=e.querySelector(`.${ob}__text`);r&&(r.textContent=t?.text??"",t?.language?e.setAttribute("lang",t.language):e.removeAttribute("lang"),e.dataset.transcriptVisibility=t?.always?"always":"onGrant")},sU={toolId:Q9,name:"Audio Transcript",description:"Text of an audio prompt, read before the content it transcribes",nameKey:"tools.audioTranscript.name",descriptionKey:"tools.audioTranscript.description",supportedLevels:["item","passage"],activation:"region",surfaces:[iU],requiresAuthoredContent:{resolve(e){return nU(e)},description:"An accessibility catalog card of type `transcript` on the item or passage"},resolvesWithoutGrant:!0,renderSurface(e){const t=e.content;if(!t)return null;const r=oU();return kk(r,t),{element:r,ariaLabel:e.services.i18n?.t("tools.audioTranscript.regionA11y")??"Transcript",sync:n=>kk(r,n.content)}}},fw=class{constructor(){T(this,"category","calculator"),T(this,"calculatorProvider",null),T(this,"initializationPromise",null),T(this,"lifecycleGeneration",0)}async emitTelemetry(e,t,r){try{await e.onTelemetry?.(t,r)}catch(n){console.warn(`[${this.providerName}] telemetry callback failed:`,n)}}async initialize(e={}){if(this.calculatorProvider)return;if(this.initializationPromise)return this.initializationPromise;const t=++this.lifecycleGeneration,r=this.initializeProvider(e,t);this.initializationPromise=r;try{await r}finally{this.initializationPromise===r&&(this.initializationPromise=null)}}async initializeProvider(e,t){const r=this.getDefinition(),n=Date.now();await this.emitTelemetry(e,"pie-tool-library-load-start",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend});let i;try{i=await r.loadProvider(),await this.emitTelemetry(e,"pie-tool-library-load-success",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend,duration:Date.now()-n})}catch(s){throw await this.emitTelemetry(e,"pie-tool-library-load-error",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend,duration:Date.now()-n,errorType:"ToolLibraryLoadError",message:s instanceof Error?s.message:String(s)}),new Error(r.initializationErrorMessage,{cause:s})}if(t!==this.lifecycleGeneration)throw new Error(`${this.providerName} initialization was cancelled`);const o=new i;try{if(await o.initialize(e),t!==this.lifecycleGeneration)throw new Error(`${this.providerName} initialization was cancelled`);this.calculatorProvider=o}catch(s){throw o.destroy(),new Error(r.initializationErrorMessage,{cause:s})}}async createInstance(){if(!this.calculatorProvider)throw new Error(`[${this.providerName}] Provider not initialized. Call initialize() first.`);return this.calculatorProvider}isReady(){return this.calculatorProvider!==null}destroy(){this.lifecycleGeneration+=1,this.initializationPromise=null,this.calculatorProvider?.destroy(),this.calculatorProvider=null}},aU=class extends fw{constructor(...e){super(...e),T(this,"providerName","PIE Open-Source Calculator"),T(this,"version","1"),T(this,"requiresAuth",!1)}getDefinition(){return{backend:"cortex",moduleImportOperation:"cortex-provider-module-import",loadProvider:async()=>(await Mr(()=>import("./chunks/dist-41b39e7f.js").then(e=>e.t),[],import.meta.url)).CortexCalculatorProvider,initializationErrorMessage:"Failed to initialize the PIE open-source calculator provider. Confirm that this browser supports module workers and that the bundled worker assets are available."}}getCapabilities(){return{supportsOffline:!0,requiresAuth:!1,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!0}}}},lU=class extends fw{constructor(...e){super(...e),T(this,"providerName","Desmos Calculator"),T(this,"version","1.12"),T(this,"requiresAuth",!0)}getDefinition(){return{backend:"desmos",moduleImportOperation:"desmos-provider-module-import",loadProvider:async()=>(await Mr(()=>import("./chunks/dist-59132a53.js"),[],import.meta.url)).DesmosCalculatorProvider,initializationErrorMessage:"Failed to initialize Desmos calculator provider. Check the application key, preloaded API, runtime endpoint, or network access."}}getCapabilities(){return{supportsOffline:!1,requiresAuth:!0,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!0}}}},cU=class extends fw{constructor(...e){super(...e),T(this,"providerName","GeoGebra Calculator"),T(this,"version","6"),T(this,"requiresAuth",!1)}getDefinition(){return{backend:"geogebra",moduleImportOperation:"geogebra-provider-module-import",loadProvider:async()=>(await Mr(()=>import("./chunks/dist-60d7afef.js"),[],import.meta.url)).GeoGebraCalculatorProvider,initializationErrorMessage:"Failed to initialize GeoGebra calculator provider. Confirm that the deployment may load GeoGebra and that its script URL is reachable."}}getCapabilities(){return{supportsOffline:!1,requiresAuth:!1,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!1}}}},uU="calculator-desmos";function dU(e){const t=e?.provider?.id;if(t===void 0||t==="")return uU;if(t==="calculator-desmos"||t==="calculator-geogebra"||t==="calculator-cortex")return t;throw new Error(`Unsupported calculator provider "${String(t)}". Expected "calculator-desmos", "calculator-geogebra", or "calculator-cortex".`)}function fU(e){switch(dU(e)){case"calculator-cortex":return new aU;case"calculator-geogebra":return new cU;default:return new lU}}function hU(e){const t=e?.theme;return{settings:e?.settings&&typeof e.settings=="object"?{...e.settings}:{},restrictedMode:e?.restrictedMode===!0,locale:typeof e?.locale=="string"?e.locale:void 0,theme:t==="light"||t==="dark"||t==="auto"?t:void 0}}function Tk(e){return e==="basic"||e==="scientific"||e==="graphing"?e:null}function pU(e){const t=e.getToolRenderParams?.("calculator")??{},r=Tk(t.calculatorType),n=t.availableTypes;return{calculatorType:r,availableTypes:Array.isArray(n)?n.map(i=>Tk(i)).filter(i=>i!==null):r?[r]:null,displayName:e.i18n.t(mU[r??"untyped"])}}var mU={basic:"tools.calculator.nameBasic",scientific:"tools.calculator.nameScientific",graphing:"tools.calculator.nameGraphing",untyped:"tools.calculator.name"};function Ek(e,t,r,n){const i=e;i.calculatorConfig=n,t?(i.calculatorType=t,e.setAttribute("calculator-type",t)):(delete i.calculatorType,e.removeAttribute("calculator-type")),r&&r.length>0?i.availableTypes=r:delete i.availableTypes}var gU={toolId:"calculator",name:"Calculator",description:"Multi-type calculator (basic, scientific, graphing)",nameKey:"tools.calculator.name",descriptionKey:"tools.calculator.description",icon:"calculator",provider:{createProvider:fU,getInitConfig:e=>e?.provider?.init??{},getAuthFetcher:e=>{const t=e?.provider?.runtime?.authFetcher;return typeof t=="function"?t:void 0},lazy:!0},supportedLevels:["item"],isVisibleInContext(e){return Gm(e)},renderToolbar(e,t){const{calculatorType:r,availableTypes:n,displayName:i}=pU(t),o=hU(t.toolkitCoordinator?.getToolConfig(this.toolId)||void 0),s=xb(this.toolId,t.scope.level,t.scope.scopeId),a=t.componentOverrides,l=Uf(t,s,()=>$f(this.toolId,e,t,a));l.setAttribute("tool-id",s),Ek(l,r,n,o);const c={toolId:this.toolId,label:i,icon:typeof this.icon=="function"?this.icon(e):this.icon,faIconName:"calculator",disabled:!1,ariaLabel:i,tooltip:i,onClick:()=>t.toggleTool(this.toolId),active:t.isToolVisible(this.toolId)};let u=c.active;return l.visible!==c.active&&(l.visible=c.active),{toolId:this.toolId,elements:[{element:l,mount:"after-buttons",shell:{title:i,draggable:!0,resizable:!0,closeable:!0,initialWidth:r==="graphing"?720:380,initialHeight:r==="graphing"?660:r==="basic"?500:560,minWidth:380,minHeight:480,initialAlign:"bottom-left",initialMargin:16,ndsHeaderControls:!0,pageTabOrder:!0,content:{overflowY:"auto",preserveMinHeight:!0}}}],button:c,sync:()=>{const d=t.isToolVisible(this.toolId);c.active=d,c.label=i,c.ariaLabel=i,c.tooltip=i,u!==d&&(l.visible=d,u=d),Ek(l,r,n,o)},subscribeActive:d=>t.subscribeVisibility?t.subscribeVisibility(()=>{d(t.isToolVisible(this.toolId))}):()=>{}}}},Ck=new WeakMap;function xk(e,t,r,n){const i=r.getToolRenderParams?.(t)??{},o={};typeof i.endpoint=="string"&&(o.endpoint=i.endpoint),typeof i.lookup=="function"&&(o.lookup=i.lookup),typeof i.headers=="function"&&(o.headers=i.headers),typeof i.credentials=="string"&&(o.credentials=i.credentials);for(const a of Ck.get(e)??[])a in o||(e[a]=void 0);Object.assign(e,o),Ck.set(e,new Set(Object.keys(o))),typeof i.term=="string"&&i.term&&(e.term=i.term),(typeof i.toolRequestId=="string"||typeof i.toolRequestId=="number")&&(e.termRequestId=i.toolRequestId);const s=typeof i.language=="string"?i.language:n??r.language;typeof s=="string"&&s&&(e.language=s)}function y_(e){const{registration:t,context:r,toolbarContext:n}=e,i=aw(t.toolId,n),o={toolId:t.toolId,label:t.name,icon:typeof t.icon=="function"?t.icon(r):t.icon,disabled:!1,ariaLabel:n.i18n.t(e.buttonA11yKey),tooltip:n.i18n.t(e.tooltipKey),onClick:()=>n.toggleTool(t.toolId),active:i.isActive()},s=n.componentOverrides??{},a=Uf(n,i.fullToolId,()=>$f(t.toolId,r,n,s));return a.setAttribute("tool-id",i.fullToolId),xk(a,t.toolId,n,e.lookupLanguage),{toolId:t.toolId,button:o,elements:[{element:a,mount:"after-buttons",shell:{title:n.i18n.t(e.shellTitleKey),draggable:!0,resizable:!0,closeable:!0,initialWidth:e.initialWidth,initialHeight:e.initialHeight,minWidth:e.minWidth,minHeight:e.minHeight}}],sync:()=>{lw({button:o,overlay:a,isActive:i.isActive}),xk(a,t.toolId,n,e.lookupLanguage)},subscribeActive:i.subscribeActive}}function b_(e={}){const t=e.toolId??"dictionary",r=e.messageKeyPrefix??`tools.${t}`;return{toolId:t,name:e.name??"Dictionary",description:e.description??"Look up word definitions",nameKey:`${r}.name`,descriptionKey:`${r}.description`,icon:"book-open",supportedLevels:["section","item","passage","rubric"],isVisibleInContext(n){return Mf(n)},renderToolbar(n,i){return y_({registration:this,context:n,toolbarContext:i,buttonA11yKey:`${r}.buttonA11y`,tooltipKey:`${r}.tooltip`,shellTitleKey:`${r}.name`,lookupLanguage:e.lookupLanguage,initialWidth:420,initialHeight:380,minWidth:300,minHeight:240})}}}var vU=b_();function w_(e={}){const t=e.toolId??"pictureDictionary",r=e.messageKeyPrefix??`tools.${t}`;return{toolId:t,name:e.name??"Picture Dictionary",description:e.description??"Look up pictures for words",nameKey:`${r}.name`,descriptionKey:`${r}.description`,icon:"photo",supportedLevels:["section","item","passage","rubric"],isVisibleInContext(n){return Mf(n)},renderToolbar(n,i){return y_({registration:this,context:n,toolbarContext:i,buttonA11yKey:`${r}.buttonA11y`,tooltipKey:`${r}.tooltip`,shellTitleKey:`${r}.name`,lookupLanguage:e.lookupLanguage,initialWidth:520,initialHeight:460,minWidth:320,minHeight:280})}}}var yU=w_(),bU=b_({toolId:"dictionarySpanish",name:"Spanish Dictionary",description:"Look up word definitions in Spanish",lookupLanguage:"es"}),wU=w_({toolId:"pictureDictionarySpanish",name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",lookupLanguage:"es"}),SU=e=>e==="mask"?"mask":"strikethrough";function IU(e,t){const r={};if(!("item"in e)||!t.getGlobalElementId)return r;for(const n of e.item?.config?.models??[]){const i=n?.id;if(typeof i!="string"||!i)continue;const o=t.getGlobalElementId(i);o&&(r[i]=o)}return r}var kU={toolId:"answerEliminator",name:"Answer Eliminator",description:"Strike through answer choices",nameKey:"tools.answerEliminator.name",descriptionKey:"tools.answerEliminator.description",icon:"strikethrough",supportedLevels:["item"],isVisibleInContext(e){return cS(e)},isApplicableToContent(e){return cS(e)},renderToolbar(e,t){const r=aw(this.toolId,t),n=t.componentOverrides??{},i=Uf(t,r.fullToolId,()=>$f(this.toolId,e,t,n));i.setAttribute("tool-id",r.fullToolId),i.setAttribute("button-alignment","inline"),i.setAttribute("strategy",SU(t.toolkitCoordinator?.getToolConfig(this.toolId)?.strategy));const o={toolId:this.toolId,label:this.name,icon:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true"><path d="M19,3H16.3H7.7H5A2,2 0 0,0 3,5V7.7V16.4V19A2,2 0 0,0 5,21H7.7H16.4H19A2,2 0 0,0 21,19V16.3V7.7V5A2,2 0 0,0 19,3M15.6,17L12,13.4L8.4,17L7,15.6L10.6,12L7,8.4L8.4,7L12,10.6L15.6,7L17,8.4L13.4,12L17,15.6L15.6,17Z"/></svg>',disabled:!1,ariaLabel:t.i18n.t("tools.answerEliminator.buttonA11y"),tooltip:t.i18n.t("tools.answerEliminator.tooltip"),onClick:()=>t.toggleTool(this.toolId),active:r.isActive()};return{toolId:this.toolId,button:o,elements:[{element:i,mount:"after-buttons"}],sync:()=>{lw({button:o,overlay:i,isActive:r.isActive}),i.scopeElement=t.getScopeElement?.()||null,i.elementStateKeys=IU(e,t)},subscribeActive:r.subscribeActive}}},TU={toolId:"ruler",name:"Ruler",description:"On-screen ruler for measurements",nameKey:"tools.ruler.name",descriptionKey:"tools.ruler.description",icon:"ruler",supportedLevels:["section","item","element"],isVisibleInContext(e){return Gm(e)},renderToolbar(e,t){return yc(this,e,t,{surface:"frameless"})}},EU={toolId:"protractor",name:"Protractor",description:"On-screen protractor for angle measurements",nameKey:"tools.protractor.name",descriptionKey:"tools.protractor.description",icon:"protractor",supportedLevels:["section","item","element"],isVisibleInContext(e){return Gm(e)},renderToolbar(e,t){return yc(this,e,t,{surface:"frameless"})}},CU={toolId:"graph",name:"Graph",description:"Coordinate plane",nameKey:"tools.graph.name",descriptionKey:"tools.graph.description",icon:"chart-bar",supportedLevels:["section","item"],isVisibleInContext(e){return Gm(e)},renderToolbar(e,t){return yc(this,e,t,{shell:{resizable:!0,initialWidth:920,initialHeight:680,minWidth:640,minHeight:500}})}},xU={toolId:"periodicTable",name:"Periodic Table",description:"Chemistry periodic table reference",nameKey:"tools.periodicTable.name",descriptionKey:"tools.periodicTable.description",icon:"beaker",supportedLevels:["section","item"],isVisibleInContext(e){return zD(e)},renderToolbar(e,t){return yc(this,e,t,{shell:{resizable:!0,initialWidth:1160,initialHeight:760,minWidth:920,minHeight:620}})}},RU=async()=>(await Mr(async()=>{const{ServerTTSProvider:e}=await import("./chunks/dist-ca9b9622.js");return{ServerTTSProvider:e}},[],import.meta.url)).ServerTTSProvider,Rk="pie-tool-active-change",PU={toolId:"textToSpeech",name:"Text to Speech",description:"Read content aloud",nameKey:"tools.textToSpeech.name",descriptionKey:"tools.textToSpeech.description",icon:"volume-up",provider:{createProvider:e=>new mj(hg(e).backend,{loadServerProvider:RU}),getInitConfig:e=>e$(hg(e)),getAuthFetcher:e=>{const t=e?.provider?.runtime?.authFetcher;return typeof t=="function"?t:void 0},lazy:!0},sanitizeConfig:e=>{const t={...e};return"layoutMode"in t&&(t.layoutMode=ZA(t.layoutMode)),"speedOptions"in t&&(t.speedOptions=_w(t.speedOptions)),t},supportedLevels:["item","passage"],isVisibleInContext(e){return Mf(e)},renderToolbar(e,t){const r=()=>hg(t.toolkitCoordinator?.getToolConfig(this.toolId)||void 0),n=()=>{const f=r();return _w(f.speedOptions)},i=()=>JA(r()),o=()=>QA(r()),s=xb(this.toolId,t.scope.level,t.scope.scopeId),a=f=>{t.language?f.setAttribute("language",t.language):f.removeAttribute("language")},l=()=>{const f=t.ui?.size;return f==="sm"||f==="lg"?f:"md"},c=Uf(t,s,()=>$f(this.toolId,e,t,t.componentOverrides)),u=()=>{c.setAttribute("catalog-id",t.catalogId||t.itemId),a(c),c.setAttribute("size",l()),c.setAttribute("layout-mode",i()),c.speedOptions=n(),c.showSingleSpeedOption=r().showSingleSpeedOption===!0};u();const d=o();return{toolId:this.toolId,button:null,elements:[{element:c,mount:d.mount,layoutHints:{controlsRow:{reserveSpace:d.controlsRow.reserveSpace,showWhenToolActive:d.controlsRow.expandWhenToolActive},headerOverlay:{showWhenToolActive:d.headerOverlay.expandWhenToolActive}}}],subscribeActive:f=>{const h=g=>{const m=g.detail;f(m?.active===!0)};return c.addEventListener(Rk,h),()=>{c.removeEventListener(Rk,h)}},sync:u}}},Io=e=>e().then(()=>{}),_U=()=>globalThis.customElements?.get("pie-tool-calculator")?Promise.resolve():Io(()=>Mr(()=>import("./chunks/calculator-element-271c142f.js"),[],import.meta.url)),AU=()=>Io(()=>Mr(()=>import("./chunks/tool-tts-inline-98c2ce7a.js"),[],import.meta.url)),$U=()=>Io(()=>Mr(()=>import("./chunks/tool-ruler-1d9a03a6.js"),[],import.meta.url)),MU=()=>Io(()=>Mr(()=>import("./chunks/tool-protractor-23f77028.js"),[],import.meta.url)),OU=()=>Io(()=>Mr(()=>import("./chunks/tool-answer-eliminator-35483abd.js"),[],import.meta.url)),LU=()=>Io(()=>Mr(()=>import("./chunks/tool-annotation-toolbar-997438b4.js"),[],import.meta.url)),NU=()=>Io(()=>Mr(()=>import("./chunks/tool-line-reader-f8ef3c6a.js"),[],import.meta.url)),DU=()=>Io(()=>Mr(()=>import("./chunks/tool-color-scheme-b7de5cdf.js"),[],import.meta.url)),jU=()=>Io(()=>Mr(()=>import("./chunks/tool-graph-cb0338e8.js"),[],import.meta.url)),zU=()=>Io(()=>Mr(()=>import("./chunks/tool-periodic-table-43b133b8.js"),[],import.meta.url)),Pk=()=>Io(()=>Mr(()=>import("./chunks/tool-dictionary-cecff3b4.js"),[],import.meta.url)),_k=()=>Io(()=>Mr(()=>import("./chunks/tool-picture-dictionary-33721e91.js"),[],import.meta.url)),BU=[{registration:gU,tagName:"pie-tool-calculator",loadModule:_U,preferredPlacementOrder:{item:10},universal:!0},{registration:PU,tagName:"pie-tool-tts-inline",loadModule:AU,preferredPlacementOrder:{item:20,passage:10},universal:!0},{registration:TU,tagName:"pie-tool-ruler",loadModule:$U,preferredPlacementOrder:{section:50},universal:!0},{registration:EU,tagName:"pie-tool-protractor",loadModule:MU,preferredPlacementOrder:{section:60},universal:!0},{registration:kU,tagName:"pie-tool-answer-eliminator",loadModule:OU,preferredPlacementOrder:{item:30},universal:!0},{registration:K9,tagName:"pie-tool-line-reader",loadModule:NU,preferredPlacementOrder:{section:40},universal:!0},{registration:X9,tagName:"pie-tool-theme",loadModule:DU,preferredPlacementOrder:{section:10},universal:!0},{registration:J9,tagName:"pie-tool-annotation-toolbar",loadModule:LU,preferredPlacementOrder:{item:40,passage:20},universal:!0},{registration:CU,tagName:"pie-tool-graph",loadModule:jU,preferredPlacementOrder:{section:20},universal:!0},{registration:xU,tagName:"pie-tool-periodic-table",loadModule:zU,preferredPlacementOrder:{section:30},universal:!0},{registration:vU,tagName:"pie-tool-dictionary",loadModule:Pk,preferredPlacementOrder:{section:70},universal:!1},{registration:yU,tagName:"pie-tool-picture-dictionary",loadModule:_k,preferredPlacementOrder:{section:80},universal:!1},{registration:bU,tagName:"pie-tool-dictionary",loadModule:Pk,preferredPlacementOrder:{section:90},universal:!1},{registration:wU,tagName:"pie-tool-picture-dictionary",loadModule:_k,preferredPlacementOrder:{section:100},universal:!1},{registration:sU,universal:!1}];function FU(e,t,r){return e.flatMap(n=>{const i=r(n)?.[t];return i===void 0?[]:[{definition:n,order:i}]}).sort((n,i)=>n.order-i.order).map(({definition:n})=>n.registration.toolId)}var HU=class{constructor(e){T(this,"definitions",void 0),T(this,"registrations",void 0),T(this,"toolTagMap",void 0),T(this,"moduleLoaders",void 0),T(this,"preferredPlacement",void 0),T(this,"universalSupportIds",void 0),this.definitions=e,this.registrations=Object.freeze(e.map(({registration:r})=>r)),this.toolTagMap=Object.freeze(Object.fromEntries(e.flatMap(r=>r.tagName?[[r.registration.toolId,r.tagName]]:[]))),this.moduleLoaders=Object.freeze(Object.fromEntries(e.flatMap(r=>r.loadModule?[[r.registration.toolId,r.loadModule]]:[])));const t=r=>Object.freeze(FU(e,r,({preferredPlacementOrder:n})=>n));this.preferredPlacement=Object.freeze({section:t("section"),item:t("item"),passage:t("passage")}),this.universalSupportIds=Object.freeze(e.filter(r=>r.universal).map(({registration:r})=>r.toolId).sort())}selectRegistrations(e){if(!e?.length)return this.registrations;const t=new Set(e);return this.registrations.filter(({toolId:r})=>t.has(r))}createRegistry(e={}){const t=new _D;for(const r of this.selectRegistrations(e.toolIds))t.register(e.overrides?.[r.toolId]??r);return e.toolModuleLoaders&&Object.keys(e.toolModuleLoaders).length>0&&t.setToolModuleLoaders({...e.toolModuleLoaders}),t.setComponentOverrides({toolTagMap:{...this.toolTagMap,...e.toolTagMap??{}},toolComponentFactories:e.toolComponentFactories}),t}createUniversalPersonalNeedsProfile(){return{supports:[...this.universalSupportIds],prohibitedSupports:[]}}},ql=new HU(BU),yK=[...ql.registrations],bK={...ql.toolTagMap},S_={...ql.moduleLoaders},wK={section:[...ql.preferredPlacement.section],item:[...ql.preferredPlacement.item],passage:[...ql.preferredPlacement.passage]};function I_(e={}){return ql.createRegistry(e)}var sb={readiness:{mode:"progressive"},preload:{enabled:!0},telemetry:{enabled:!0}};function qf(e){const t=e?.readiness?.mode;return{readiness:{mode:t==="strict"||t==="progressive"?t:sb.readiness.mode},preload:{enabled:e?.preload?.enabled!==!1},telemetry:{enabled:e?.telemetry?.enabled!==!1}}}var of=new WeakMap;function UU(e){if(!e)return"";try{return JSON.stringify(e)}catch{return String(e?.id||"")}}function Ak(e){if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function qU(e){return(t,r)=>($k(t,r,e),{update(n){$k(t,n,e)},destroy(){GU(t,e.stateKey)}})}function $k(e,t,r){const n=e,i=WU(e,r.stateKey),o=Object.keys(t.attributes||{}),s=Object.keys(t.props||{}),a=i.attributeKeys||[],l=i.propKeys||[];for(const f of a)o.includes(f)||e.removeAttribute(f);for(const f of l)s.includes(f)||delete n[f];const c=Ak(t.config);i.configSignature!==c&&(n.config=t.config);const u=Ak(t.env);i.envSignature!==u&&(n.env=t.env);const d=UU(t.session);t.session!==void 0&&i.sessionSignature!==d&&(n.session=t.session);for(const[f,h]of Object.entries(t.attributes||{}))e.setAttribute(f,String(h));for(const[f,h]of Object.entries(t.props||{}))n[f]=h;VU(e,r.stateKey,{config:t.config,configSignature:c,env:t.env,envSignature:u,session:r.includeSessionRefInState?t.session:void 0,sessionSignature:d,attributeKeys:o,propKeys:s})}function WU(e,t){return of.get(e)?.get(t)||{}}function VU(e,t,r){const n=of.get(e)||new Map;n.set(t,r),of.set(e,n)}function GU(e,t){const r=of.get(e);r&&(r.delete(t),r.size===0&&of.delete(e))}function YU(e){const{host:t,getOnStageChange:r,getOnLoadingComplete:n,onError:i}=e,o=a=>{if(a.target!==t)return;const l=a.detail,c=r();if(c)try{c(l)}catch(u){i?.("onStageChange",u)}},s=a=>{if(a.target!==t)return;const l=a.detail,c=n();if(c)try{c(l)}catch(u){i?.("onLoadingComplete",u)}};return t.addEventListener("pie-stage-change",o),t.addEventListener("pie-loading-complete",s),()=>{t.removeEventListener("pie-stage-change",o),t.removeEventListener("pie-loading-complete",s)}}var KU={"nl-NL":()=>Mr(()=>import("./chunks/nl-NL-364d61b9.js"),[],import.meta.url)},XU=["en-US","nl-NL"];async function JU(e){const t=KU[e];if(!t)throw new Error(`No bundled i18n catalog for locale: ${e}`);return(await t()).default}function QU(e={}){return new KA({loadCatalog:JU,availableLocales:XU,...e})}function ab(e){return{kind:e.kind,severity:e.severity??"error",source:e.source,message:e.message,details:[...e.details||[]],recoverable:e.recoverable===!0,scope:e.scope??"runtime",cause:e.cause}}function k_(e){let t=e.error instanceof Error&&e.error.message.trim().length>0?e.error.message:String(e.error||"Unknown framework error");return ab({kind:e.kind,source:e.source,message:t,recoverable:e.recoverable,scope:e.scope,cause:e.error})}var ZU={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose","tool-module-load":"tool-module-load"};function eq(e){let t=ZU[e.context.phase];return k_({kind:t,source:e.context.toolId?`pie-toolkit-coordinator/${e.context.toolId}`:`pie-toolkit-coordinator:${e.context.phase}`,error:e.error,recoverable:e.recoverable,scope:e.scope})}function tq(e){let t=`[pie-framework:${e.kind}:${e.source}]`;return e.details.length===0?`${t} ${e.message}`:`${t} ${e.message}
1430
+ - ${e.details.join(`
1431
+ - `)}`}var rq="error";function T_(e){return e==="off"||e==="warn"||e==="error"?e:rq}function nq(e){return e?new Map(e.getAllTools().slice().sort((t,r)=>t.toolId.localeCompare(r.toolId)).map(t=>[t.toolId,t])):new Map}function iq(e,t,r,n){if(!t||!r?.sanitizeConfig)return t;try{let i=r.sanitizeConfig(t);return!i||typeof i!="object"||Array.isArray(i)?(n.push({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${e}`,message:`Config sanitizer of tool "${e}" must return an object.`,toolId:e}),t):i}catch(i){return n.push({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${e}`,message:`Config sanitizer of tool "${e}" failed: ${i instanceof Error?i.message:String(i)}`,toolId:e}),t}}function oq(e,t,r,n){if(!(!t||!r?.validateConfig))try{let i=r.validateConfig(t);if(!Array.isArray(i)){n.push({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${e}`,message:`Config validator of tool "${e}" must return an array.`,toolId:e});return}for(let o of i)n.push({...o,path:o.path||`providers.${e}`,toolId:o.toolId||e})}catch(i){n.push({code:"tools.providerValidateFailed",severity:"error",path:`providers.${e}`,message:`Config validator of tool "${e}" failed: ${i instanceof Error?i.message:String(i)}`,toolId:e})}}function sq(e,t,r){if(t.size!==0)for(let n of["section","item","passage"])for(let i of e.placement[n]){let o=t.get(i);if(!o){r.push({code:"tools.unknownToolId",severity:"error",path:`placement.${n}`,message:`Unknown tool id "${i}" in placement.${n}.`,toolId:i});continue}if(o.activation==="region"){r.push({code:"tools.unplaceableActivation",severity:"error",path:`placement.${n}`,message:`Tool "${i}" renders into a host surface (activation "region") and cannot be placed on the ${n} toolbar. Remove it from placement.${n}; its availability comes from policy plus its content dependency.`,toolId:i});continue}let s=o.supportedLevels.includes(n),a=n==="item"&&o.supportedLevels.includes("section");!s&&!a&&r.push({code:"tools.unsupportedLevel",severity:"error",path:`placement.${n}`,message:`Tool "${i}" does not support level "${n}".`,toolId:i})}}function aq(e,t,r){if(t.size!==0){for(let n of e.policy.allowed||[])t.has(n)||r.push({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${n}" in policy.allowed.`,toolId:n});for(let n of e.policy.blocked||[])t.has(n)||r.push({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${n}" in policy.blocked.`,toolId:n})}}function lq(e,t,r){for(let n of Object.keys(e.providers).sort())t.size===0||t.has(n)||r.push({code:"tools.unknownProviderKey",severity:"error",path:`providers.${n}`,message:`Unknown provider key "${n}".`,toolId:n})}function Mk(e,t){if(e.length!==0)for(let r of e){let n=`[tool-config-validation:${t}]`;console.warn(`${n} ${r.path} - ${r.message}`)}}function cq(e,t){let r=e.map(n=>`- ${n.path}: ${n.message}`).join(`
1432
+ `);throw Error(`[tool-config-validation:${t}] Invalid tools config:
1433
+ ${r}`)}function uq(e,t={}){let r=E_(e,t.toolRegistry);return C_(r.diagnostics,t),r}function E_(e,t){let r=nq(t),n=C0(e),i=[],o=Object.values(n.placement).some(l=>l.length>0)||Object.keys(n.providers).length>0||(n.policy.allowed?.length??0)>0||(n.policy.blocked?.length??0)>0;r.size===0&&o&&i.push({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated, and a coordinator without one registers no tool providers. Pass `toolRegistry` to the coordinator or the toolkit it is bound to — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'});let s={...n.providers||{}};for(let l of Object.keys(s).sort()){let c=r.get(l);s[l]=iq(l,s[l],c,i),oq(l,s[l],c,i)}let a={...n,providers:s};return sq(a,r,i),aq(a,r,i),lq(a,r,i),{config:a,diagnostics:i}}function C_(e,t={}){let r=T_(t.strictness),n=t.source??"tools";r==="warn"&&Mk(e,n);let i=e.filter(o=>o.severity==="error");r==="error"&&i.length>0&&cq(i,n),r==="error"&&i.length===0&&Mk(e,n)}var hw=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),x_=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),R_=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),P_=new Set(["break","mark","lexicon"]);function dq(e){let t=e;for(let r of P_){let n=new RegExp(`<${r}\\b([^>/]*?)\\s*/>`,"gi");t=t.replace(n,(i,o)=>{let s=o?o.replace(/\s+$/,""):"";return`<${r}${s}></${r}>`})}return t}var fq=[/^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 hq(e){if(typeof e!="string"||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;let r=t.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!fq.some(n=>n.test(r))}function lb(e){let t=Array.from(e.children);for(let n of t){let i=n.tagName.toLowerCase();if(x_.has(i)){n.remove();continue}if(lb(n),!hw.has(i)){let o=e.ownerDocument.createTextNode(n.textContent??"");n.replaceWith(o)}}let r=Array.from(e.attributes).map(n=>n.name);for(let n of r)R_.has(n.toLowerCase())||e.removeAttribute(n);if(e.tagName.toLowerCase()==="audio"){let n=e.getAttribute("src");n!==null&&!hq(n)&&e.removeAttribute("src")}}function cb(e){let t=e.tagName.toLowerCase(),r=Array.from(e.attributes).filter(i=>R_.has(i.name.toLowerCase())).map(i=>` ${i.name}="${pq(i.value)}"`).join("");if(P_.has(t))return`<${t}${r}/>`;let n=[];for(let i of Array.from(e.childNodes))if(i.nodeType===3)n.push(mm(i.nodeValue??""));else if(i.nodeType===1){let o=i,s=o.tagName.toLowerCase();if(x_.has(s))continue;hw.has(s)?n.push(cb(o)):n.push(mm(o.textContent??""))}return`<${t}${r}>${n.join("")}</${t}>`}function Ok(e){let t=String(e||"").trim();if(!t||!t.includes("<")||typeof DOMParser>"u")return e;let r=new DOMParser().parseFromString(dq(t),"text/html"),n=r.querySelector("speak");if(n)return lb(n),cb(n);let i=r.createElement("speak");for(let o of Array.from(r.body.childNodes))i.appendChild(o);return lb(i),Array.from(i.childNodes).map(o=>{if(o.nodeType===3)return mm(o.nodeValue??"");if(o.nodeType===1){let s=o;return hw.has(s.tagName.toLowerCase())?cb(s):mm(s.textContent??"")}return""}).join("")}function mm(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function pq(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var __=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),ub="ext:";function Lk(e){return __.has(e)?!0:e.startsWith(ub)&&e.length>ub.length}var Nk=new Set;function db(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e>"u")return e;if(typeof e!="object")throw TypeError("catalog cards must contain JSON-compatible values");if(t.has(e))throw TypeError("catalog cards must not contain cycles");t.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(i=>db(i,t)));let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let n={};for(let[i,o]of Object.entries(e))n[i]=db(o,t);return Object.freeze(n)}finally{t.delete(e)}}function Dk(e,t,r){let n=`${t}|${e}`;if(Nk.has(n))return;Nk.add(n);let i=`${Array.from(__).join(", ")}, or an "${ub}" prefixed vendor extension`;if(t==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${r}" has a card of unknown type "${e}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${i}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${e}" on "${r}" cannot match any card. Expected one of: ${i}.`)}var jk=e=>e.payload!==void 0?"payload":"content",mq=class{constructor(e,t="en-US"){T(this,"assessmentCatalogs",new Map),T(this,"itemCatalogs",new Map),T(this,"scopedCatalogs",new Map),T(this,"defaultLanguage","en-US"),T(this,"sanitizedSpokenCache",new Map),T(this,"catalogChangeListeners",new Set),T(this,"reportedSnapshotProblems",new Set),this.defaultLanguage=t,this.indexCatalogs(e??[],"assessment")}setDefaultLanguage(e){this.defaultLanguage=e}onCatalogsChange(e){return this.catalogChangeListeners.add(e),()=>{this.catalogChangeListeners.delete(e)}}emitCatalogsChange(e){for(let t of Array.from(this.catalogChangeListeners))try{t(e)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(e,t){let r=t==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let n of this.sanitizeCatalogs(e)){if(r.has(n.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${t} catalog "${n.identifier}" ignored`);continue}r.set(n.identifier,n)}}insertScopedCatalogs(e,t){if(!t||t.length===0)return null;let r=this.getOwnerKey(e),n=this.scopedCatalogs.get(r),i=n?.catalogs??new Map,o=[];for(let s of this.sanitizeCatalogs(t)){if(i.has(s.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${s.identifier}" ignored for ${r}`);continue}i.set(s.identifier,s),o.push(s.identifier)}return!n&&o.length>0&&this.scopedCatalogs.set(r,{context:{...e},catalogs:i}),{key:r,context:{...e},catalogs:i,insertedIds:o}}removeScopedInsertion(e){let t=this.scopedCatalogs.get(e.key);if(t?.catalogs!==e.catalogs)return!1;let r=!1;for(let n of e.insertedIds)r=t.catalogs.delete(n)||r;return t.catalogs.size===0&&this.scopedCatalogs.delete(e.key),r}registerCatalogs(e,t){let r=this.insertScopedCatalogs(e,t);r&&r.insertedIds.length>0&&this.emitCatalogsChange({reason:"scoped-registered",context:e});let n=!0;return()=>{n&&(n=!1,r&&this.removeScopedInsertion(r)&&this.emitCatalogsChange({reason:"scoped-removed",context:e}))}}registerOwner(e){let{owner:t,entity:r}=e,n=tC(t),i=[],o=[];try{o=rC(r,t)}catch(a){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",a)}for(let a of o)try{let l=this.insertScopedCatalogs(a.context,a.catalogs);l&&i.push(l)}catch(l){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",l)}i.some(a=>a.insertedIds.length>0)&&this.emitCatalogsChange({reason:"scoped-registered",context:n});let s=!0;return()=>{if(!s)return;s=!1;let a=!1;for(let l of i)a=this.removeScopedInsertion(l)||a;a&&this.emitCatalogsChange({reason:"scoped-removed",context:n})}}forOwner(e){let t={...e};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(t),onChange:r=>this.onCatalogsChange(n=>{this.catalogChangeAffectsOwner(n,t)&&r()})})}addItemCatalogs(e){!e||e.length===0||(this.indexCatalogs(e,"item"),this.emitCatalogsChange({reason:"item-added"}))}clearItemCatalogs(){this.itemCatalogs.size!==0&&(this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"}))}hasCatalog(e){return this.itemCatalogs.has(e)||this.assessmentCatalogs.has(e)||Array.from(this.scopedCatalogs.values()).some(t=>t.catalogs.has(e))}getAlternative(e,t){Lk(t.type)||Dk(t.type,"lookup",e);let r=t.context?this.scopedCatalogs.get(this.getOwnerKey(t.context))?.catalogs.get(e):null;if(r){let o=this.findMatchingCard(r,t);if(o)return this.resolveCard(e,o,"item")}if(t.context){let o=this.findScopedCandidates(e,t.context);if(o.length===1){let s=this.findMatchingCard(o[0],t);if(s)return this.resolveCard(e,s,"item")}else if(o.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${e}" for owner context`,t.context),null}let n=this.itemCatalogs.get(e);if(n){let o=this.findMatchingCard(n,t);if(o)return this.resolveCard(e,o,"item")}let i=this.assessmentCatalogs.get(e);if(i){let o=this.findMatchingCard(i,t);if(o)return this.resolveCard(e,o,"assessment")}return null}resolveCard(e,t,r){return{catalogId:e,type:t.catalog,language:t.language,content:t.catalog==="spoken"&&t.content!==void 0?this.ensureSpokenSanitized(t.content):t.content,payload:t.payload,source:r}}ensureSpokenSanitized(e){let t=this.sanitizedSpokenCache.get(e);if(t!==void 0)return t;let r=Ok(e);return this.sanitizedSpokenCache.set(e,r),r}getOwnerKey(e){return[e.ownerKind,e.assessmentId||"",e.sectionId||"",e.canonicalItemId||"",e.itemId||"",e.passageId||"",e.modelId||""].join("|")}scopedCatalogEntries(){let e=[];for(let t of this.scopedCatalogs.values())for(let r of t.catalogs.entries())e.push(r);return e}findScopedCandidates(e,t){return Array.from(this.scopedCatalogs.values()).filter(r=>this.isCompatibleOwnerContext(r.context,t)).map(r=>r.catalogs.get(e)).filter(r=>!!r)}isCompatibleOwnerContext(e,t){return!(e.ownerKind!==t.ownerKind||t.assessmentId&&e.assessmentId!==t.assessmentId||t.sectionId&&e.sectionId!==t.sectionId||t.canonicalItemId&&e.canonicalItemId!==t.canonicalItemId||t.itemId&&e.itemId!==t.itemId||t.passageId&&e.passageId!==t.passageId||t.modelId&&e.modelId!==t.modelId)}ownerScopedCatalogEntries(e){let t=[],r=this.scopedCatalogs.get(this.getOwnerKey(e));r&&t.push(...r.catalogs.entries());for(let n of this.scopedCatalogs.values())n!==r&&this.isCompatibleOwnerContext(n.context,e)&&t.push(...n.catalogs.entries());return t}createOwnerSnapshot(e){let t=[],r=this.ownerScopedCatalogEntries(e);e.ownerKind==="global"&&r.push(...this.assessmentCatalogs.entries());for(let[n,i]of r)for(let o of i.cards)try{t.push(Object.freeze({catalogId:n,card:db(o)}))}catch(s){let a=`${this.getOwnerKey(e)}\0${n}`;this.reportedSnapshotProblems.has(a)||(this.reportedSnapshotProblems.add(a),console.warn(`[AccessibilityCatalogResolver] Catalog "${n}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,s))}return Object.freeze({cards:Object.freeze(t)})}catalogChangeAffectsOwner(e,t){return e.context?this.isCompatibleOwnerContext(e.context,t)?!0:t.ownerKind==="itemModel"&&t.modelId&&e.context.ownerKind==="itemModel"&&!e.context.modelId?this.isCompatibleOwnerContext({...e.context,modelId:t.modelId},t):!1:!1}sanitizeCatalogs(e){return e.map(t=>({...t,cards:t.cards.map(r=>(Lk(r.catalog)||Dk(r.catalog,"card",t.identifier),{...r,content:r.catalog==="spoken"&&r.content!==void 0?Ok(r.content):r.content}))}))}findMatchingCard(e,t){let{type:r,language:n,useFallback:i=!0,form:o}=t,s=[],a=l=>{for(let c of YA(l))s.push(u=>Pw(u.language)===c)};n&&a(n),i&&(a(this.defaultLanguage),s.push(()=>!0));for(let l of s){let c=e.cards.filter(u=>u.catalog===r&&l(u));if(c.length!==0){if(o){let u=c.find(d=>jk(d)===o);if(u)return u}return c[0]}}return null}getAllAlternatives(e){let t=[],r=new Set,n=(s,a)=>{let l=`${s.catalog}|${Pw(s.language)}|${jk(s)}`;r.has(l)||(r.add(l),t.push(this.resolveCard(e,s,a)))},i=this.itemCatalogs.get(e);if(i)for(let s of i.cards)n(s,"item");let o=this.assessmentCatalogs.get(e);if(o)for(let s of o.cards)n(s,"assessment");for(let[s,a]of this.scopedCatalogEntries())if(s===e)for(let l of a.cards)n(l,"item");return t}getAllCatalogIds(){let e=this.scopedCatalogEntries().map(([t])=>t);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...e]))}getStatistics(){let e=new Set,t=new Set;for(let r of this.assessmentCatalogs.values())for(let n of r.cards)e.add(n.catalog),n.language&&t.add(n.language);for(let r of this.itemCatalogs.values())for(let n of r.cards)e.add(n.catalog),n.language&&t.add(n.language);for(let r of this.scopedCatalogs.values())for(let n of r.catalogs.values())for(let i of n.cards)e.add(i.catalog),i.language&&t.add(i.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((r,n)=>r+n.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((r,n)=>r+n.catalogs.size,0),availableTypes:e,availableLanguages:t}}hasAlternativeType(e,t){return this.getAllAlternatives(e).some(r=>r.type===t)}getCatalogsByType(e){let t=new Set;for(let[r,n]of this.assessmentCatalogs.entries())n.cards.some(i=>i.catalog===e)&&t.add(r);for(let[r,n]of this.itemCatalogs.entries())n.cards.some(i=>i.catalog===e)&&t.add(r);for(let[r,n]of this.scopedCatalogEntries())n.cards.some(i=>i.catalog===e)&&t.add(r);return Array.from(t)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}};function Iv(e){return e.replace(/%/g,"%25").replace(/:/g,"%3A")}function gq(e){return e.replace(/%(25|3A)/g,(t,r)=>r==="25"?"%":":")}var vq=class{constructor(){T(this,"elementStates",new Map),T(this,"listeners",new Set),T(this,"onStateChange",null)}getGlobalElementId(e,t,r,n){return[e,t,r,n].map(Iv).join(":")}parseGlobalElementId(e){let t=e.split(":");if(t.length!==4)return null;let[r,n,i,o]=t.map(gq);return{assessmentId:r,sectionId:n,itemId:i,elementId:o}}setState(e,t,r){let n=this.elementStates.get(e);n||(n=new Map,this.elementStates.set(e,n)),n.set(t,r),this._notifyListeners(),this._notifyStateChange()}getState(e,t){return this.elementStates.get(e)?.get(t)}getElementState(e){let t=this.elementStates.get(e);return t?Object.fromEntries(t.entries()):{}}getAllState(){let e={};for(let[t,r]of this.elementStates.entries())e[t]=Object.fromEntries(r.entries());return e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}_notifyListeners(){if(this.listeners.size===0)return;let e=new Map([...this.elementStates].map(([t,r])=>[t,new Map(r)]));for(let t of this.listeners)try{t(e)}catch(r){console.warn("[ElementToolStateStore] listener failed:",r)}}setOnStateChange(e){this.onStateChange=e}_notifyStateChange(){if(this.onStateChange)try{this.onStateChange(this.getAllState())}catch(e){console.warn("[ElementToolStateStore] state-change callback failed:",e)}}loadState(e){this.elementStates.clear();for(let[t,r]of Object.entries(e)){let n=new Map(Object.entries(r));this.elementStates.set(t,n)}this._notifyListeners()}clearElement(e){this.elementStates.delete(e),this._notifyListeners(),this._notifyStateChange()}clearTool(e){for(let t of this.elementStates.values())t.delete(e);this._notifyListeners(),this._notifyStateChange()}clearSection(e,t){let r=`${Iv(e)}:${Iv(t)}:`,n=[];for(let i of this.elementStates.keys())i.startsWith(r)&&n.push(i);for(let i of n)this.elementStates.delete(i);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}},A_=class{constructor(){T(this,"listeners",new Set)}subscribeFrameworkErrors(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}reportFrameworkError(e){let t=Array.from(this.listeners);for(let r of t)try{r(e)}catch(n){console.warn("[FrameworkErrorBus] listener failed:",n)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}},yq=new Set(["pie-item-toolbar","pie-section-toolbar","pie-item-player-session-debugger"]),bq=["pie-tool-","pie-section-player-tools-"],wq=new Set(["style","script","noscript","template"]),Si=e=>!!e&&e.nodeType===11&&e.host?.nodeType===1,Sq=e=>{let t=e.localName?.toLowerCase()||"";return yq.has(t)?!0:bq.some(r=>t.startsWith(r))},Iq=e=>{let t=e.localName?.toLowerCase()||"";return wq.has(t)||Sq(e)?!0:Si(e.parentNode)&&e.getAttribute("aria-hidden")==="true"},kq=e=>{if(!Si(e.getRootNode?.()))return null;let t=e.assignedNodes;if(typeof t!="function")return null;try{return t.call(e,{flatten:!0})}catch{return null}},wu=e=>{let t=e.childNodes;if(e.nodeType===1){let n=e,i=n.shadowRoot;i?t=i.childNodes:n.localName?.toLowerCase()==="slot"&&(t=kq(n)??n.childNodes)}let r=[];for(let n of Array.from(t||[]))n.nodeType===1&&Iq(n)||r.push(n);return r},rg=(e,t)=>{let r=n=>{for(let i of wu(n)){let o=t(i);if(o==="stop")return!1;if(o!=="skip"&&!r(i))return!1}return!0};r(e)},Wf=e=>{let t=[];return rg(e,r=>{r.nodeType===3&&t.push(r)}),t},Tq=e=>Wf(e).map(t=>t.data).join(""),Eq=(e,t)=>{let r=[];return rg(e,n=>{n.nodeType===1&&n.matches(t)&&r.push(n)}),r},ng=(e,t)=>{let r=null;return rg(e,n=>{if(n.nodeType===1&&n.matches(t))return r=n,"stop"}),r},zk=e=>{let t=e.assignedSlot;if(t)return t;let r=e.parentNode;return Si(r)?r.host:r},ho=e=>{let t=zk(e);for(;t&&t.nodeType!==1;)t=zk(t);return t},Bk=(e,t)=>{let r=e.nodeType===1?e:ho(e);for(;r;){if(r.matches(t))return r;r=ho(r)}return null},Ps=e=>{if(e.parentElement)return e.parentElement;let t=e.parentNode;return Si(t)?t.host:null},$_=(e,t,r)=>{let n=e.nodeType===1?e:Ps(e);for(;n;){if(n.matches(t))return n;if(r&&n===r)return null;n=Ps(n)}return null},Su=(e,t)=>{if(!e||!t)return!1;let r=t;for(;r;){if(r===e||e.contains(r))return!0;let n=r.getRootNode?.();r=Si(n)?n.host:null}return!1},M_=(e,t)=>{let r=e;for(;r;){let n=r.getRootNode?.();if(n===t)return r;r=Si(n)?n.host:null}return null},fb=(e,t,r)=>{try{let n=e.startContainer.getRootNode?.();return!n||t.getRootNode?.()===n?e.comparePoint(t,r)===0&&e.comparePoint(t,Math.min(r+1,t.length))===0:O_(e,M_(t,n))}catch{return!1}},Vf=(e,t)=>{try{let r=e.startContainer.getRootNode?.();return!r||t.getRootNode?.()===r?e.intersectsNode(t):O_(e,M_(t,r))}catch{return!1}},O_=(e,t)=>{let r=t?.parentNode;if(!t||!r)return!1;let n=Array.prototype.indexOf.call(r.childNodes,t);return n<0?!1:e.comparePoint(r,n)===0&&e.comparePoint(r,n+1)===0},kv=" >>> ",Cq=class{serialize(e,t){return{startContainer:this.getNodePath(e.startContainer,t),startOffset:e.startOffset,endContainer:this.getNodePath(e.endContainer,t),endOffset:e.endOffset,text:e.toString()}}deserialize(e,t){let r=this.findNodeByPath(e.startContainer,t),n=this.findNodeByPath(e.endContainer,t);if(!r||!n)return null;try{let i=new Range;return i.setStart(r,e.startOffset),i.setEnd(n,e.endOffset),i.toString()===e.text?i:null}catch(i){return console.warn("Failed to deserialize range:",i),null}}getNodePath(e,t){if(e===t)return"";if(e.nodeType===Node.TEXT_NODE){let r=e.parentNode;if(!r)throw Error("Text node has no parent");let n=Array.from(r.childNodes).filter(i=>i.nodeType===Node.TEXT_NODE).indexOf(e);return`${Si(r)?this.getShadowRootPath(r,t):this.getElementPath(r,t)}::text[${n}]`}if(e.nodeType===Node.ELEMENT_NODE)return this.getElementPath(e,t);if(Si(e))return this.getShadowRootPath(e,t);throw Error(`Unsupported node type: ${e.nodeType}`)}getElementPath(e,t){if(e===t)return"";let r=t.getRootNode?.(),n=[],i=[],o=e,s=a=>{n.unshift(i.join(" > ")),i=[],o=a.host};for(;o&&o!==t;){if(o.id){i.unshift(`#${o.id}`);let g=o.getRootNode?.();if(Si(g)&&g!==r){s(g);continue}break}let{parentElement:a,parentNode:l}=o,c=a??(Si(l)?l:null);if(!c)break;let u=o.tagName,d=Array.from(c.children).filter(g=>g.tagName===u),f=d.indexOf(o),h=d.length>1?`${u.toLowerCase()}:nth-of-type(${f+1})`:u.toLowerCase();i.unshift(h),a?o=a:s(c)}return n.unshift(i.join(" > ")),n.join(kv)}getShadowRootPath(e,t){return`${this.getElementPath(e.host,t)}${kv}`}resolveElementPath(e,t){let r=t,n=e.split(kv);for(let i=0;i<n.length;i++){if(i>0){let a=Si(r)?null:r.shadowRoot;if(!a)return null;r=a}let o=n[i].trim();if(!o)continue;let s=r.querySelector(o);if(!s)return null;r=s}return r}findNodeByPath(e,t){if(e==="")return t;if(e.includes("::text[")){let r=e.lastIndexOf("::text["),n=e.slice(0,r),i=e.slice(r+7),o=Number.parseInt(i.replace("]",""),10),s;try{s=this.resolveElementPath(n,t)}catch(a){return console.warn("Invalid selector path:",e,a),null}return s&&Array.from(s.childNodes).filter(a=>a.nodeType===Node.TEXT_NODE)[o]||null}try{return this.resolveElementPath(e,t)}catch(r){return console.warn("Invalid selector path:",e,r),null}}serializeMany(e,t){return e.map(r=>this.serialize(r,t))}deserializeMany(e,t){return e.map(r=>this.deserialize(r,t))}},so;(function(e){e.TTS_WORD="tts-word",e.TTS_SENTENCE="tts-sentence",e.ANNOTATION="annotation"})(so||(so={}));var Ad;(function(e){e.YELLOW="yellow",e.GREEN="green",e.BLUE="blue",e.PINK="pink",e.ORANGE="orange",e.UNDERLINE="underline"})(Ad||(Ad={}));var L_=`
1434
+ /* TTS highlights - temporary */
1435
+ ::highlight(tts-word) {
1436
+ background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
1437
+ text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1438
+ text-underline-offset: 2px;
1439
+ text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));
1440
+ color: inherit;
1441
+ }
1442
+
1443
+ /* tts-sentence registry id: coarse read-along band (visual line boxes in layout) */
1444
+ ::highlight(tts-sentence) {
1445
+ background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));
1446
+ color: inherit;
1447
+ }
1448
+
1449
+ [data-pie-tts-sentence-element="true"] {
1450
+ background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));
1451
+ border-radius: 0.12em;
1452
+ box-decoration-break: clone;
1453
+ -webkit-box-decoration-break: clone;
1454
+ }
1455
+
1456
+ [data-pie-tts-word-element="true"] {
1457
+ background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
1458
+ text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1459
+ text-underline-offset: 2px;
1460
+ text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));
1461
+ border-bottom: 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1462
+ padding-bottom: 1px;
1463
+ border-radius: 0.12em;
1464
+ box-decoration-break: clone;
1465
+ -webkit-box-decoration-break: clone;
1466
+ }
1467
+
1468
+ /* Annotation highlights - persistent */
1469
+ ::highlight(annotation-yellow) {
1470
+ background-color: var(--pie-annotation-yellow-highlight, rgba(253, 233, 149, 0.5));
1471
+ color: inherit;
1472
+ }
1473
+
1474
+ ::highlight(annotation-green) {
1475
+ background-color: var(--pie-annotation-green-highlight, rgba(166, 225, 197, 0.5));
1476
+ color: inherit;
1477
+ }
1478
+
1479
+ ::highlight(annotation-blue) {
1480
+ background-color: var(--pie-annotation-blue-highlight, rgba(167, 224, 246, 0.5));
1481
+ color: inherit;
1482
+ }
1483
+
1484
+ ::highlight(annotation-pink) {
1485
+ background-color: var(--pie-annotation-pink-highlight, rgba(255, 159, 174, 0.5));
1486
+ color: inherit;
1487
+ }
1488
+
1489
+ ::highlight(annotation-orange) {
1490
+ background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.5));
1491
+ color: inherit;
1492
+ }
1493
+
1494
+ /* The base light/dark pair is fixed: #4221d5 on light, #9c89ec on dark.
1495
+ One value cannot serve both -- #4221d5 is 2.41:1 on black and #9c89ec is
1496
+ 2.85:1 on white -- so neither of those two consults the theme accent,
1497
+ which is chosen against one background and illegible on the other.
1498
+
1499
+ Each state has its own token so overriding one never silently moves the
1500
+ other, and so either can beat a host-set pie-primary: a var() fallback
1501
+ can never override a value the host actually set. */
1502
+ ::highlight(annotation-underline) {
1503
+ background-color: transparent;
1504
+ text-decoration: underline 2px solid var(--pie-annotation-underline, #4221d5);
1505
+ text-underline-offset: 2px;
1506
+ color: inherit;
1507
+ }
1508
+
1509
+ /* The blocks below cover annotation swatches, print, and reduced motion.
1510
+ They deliberately do NOT retune the TTS layers: applyAdaptiveTTSStyle()
1511
+ writes the pie-tts custom properties inline on documentElement on every
1512
+ paint and on theme change, so a media query that only varies a var()
1513
+ fallback for those can never take effect. Annotation colours have no such
1514
+ adaptive path -- they are fixed swatches a student chose -- so a media
1515
+ query is the only way to adjust them, and each keeps its var() so a host
1516
+ override still wins.
1517
+
1518
+ The names above are spelled without their leading dashes on purpose.
1519
+ check-theme-tokens scans comments, and its token pattern stops at the
1520
+ first non-alphanumeric character, so writing the wildcard form reads as
1521
+ consumption of a shorter token that is not in the registry and fails the
1522
+ check. Spell property names in full, or omit the dashes. */
1523
+
1524
+ @media (prefers-color-scheme: dark) {
1525
+ ::highlight(annotation-yellow) {
1526
+ background-color: var(--pie-annotation-yellow-highlight, rgba(139, 117, 0, 0.6));
1527
+ }
1528
+ ::highlight(annotation-green) {
1529
+ background-color: var(--pie-annotation-green-highlight, rgba(45, 92, 63, 0.6));
1530
+ }
1531
+ ::highlight(annotation-blue) {
1532
+ background-color: var(--pie-annotation-blue-highlight, rgba(0, 102, 170, 0.6));
1533
+ }
1534
+ ::highlight(annotation-pink) {
1535
+ background-color: var(--pie-annotation-pink-highlight, rgba(139, 51, 74, 0.6));
1536
+ }
1537
+ ::highlight(annotation-orange) {
1538
+ background-color: var(--pie-annotation-orange-highlight, rgba(154, 99, 0, 0.6));
1539
+ }
1540
+ ::highlight(annotation-underline) {
1541
+ text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
1542
+ }
1543
+ }
1544
+
1545
+ /* The media query above reports the OS preference, which is only a guess
1546
+ at what the page is actually showing. An app that declares a theme has
1547
+ the final say, so the rules below override it. pie-theme always stamps
1548
+ data-theme on documentElement (scope="document") or on its own host, and
1549
+ resolves to a dark palette only for the literal value "dark" -- every
1550
+ other value, including DaisyUI theme ids, maps to a light base.
1551
+
1552
+ The three cases are mutually exclusive, so they never fight each other.
1553
+ All carry attribute selectors, which outrank the bare ::highlight() rules
1554
+ above -- including the one inside the media query, since a media query
1555
+ adds no specificity -- whatever the source order. */
1556
+ [data-theme="light"] ::highlight(annotation-underline) {
1557
+ text-decoration-color: var(--pie-annotation-underline, #4221d5);
1558
+ }
1559
+
1560
+ [data-theme="dark"] ::highlight(annotation-underline) {
1561
+ text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
1562
+ }
1563
+
1564
+ /* A host or DaisyUI palette: follow its accent so the mark belongs to that
1565
+ theme, falling back to the light default when it declares none. */
1566
+ [data-theme]:not([data-theme="light"]):not([data-theme="dark"]) ::highlight(annotation-underline) {
1567
+ text-decoration-color: var(--pie-annotation-underline, var(--pie-primary, #4221d5));
1568
+ }
1569
+
1570
+ /* WCAG 2.2 SC 1.4.11 non-text contrast: a highlight is the only indication
1571
+ that text is annotated, so the swatches saturate and the underline
1572
+ thickens when the user asks for more contrast.
1573
+
1574
+ The value is "more", not "high". The stylesheet this was recovered from
1575
+ used prefers-contrast: high, which is not a valid value for the feature
1576
+ -- the keywords are no-preference, more, less, custom. An invalid query
1577
+ evaluates to "not all", so that block could never have matched in any
1578
+ browser even had the file been loaded. Verified with matchMedia under
1579
+ emulation: "high" stays false where "more" flips true. */
1580
+ @media (prefers-contrast: more) {
1581
+ ::highlight(annotation-yellow) {
1582
+ background-color: var(--pie-annotation-yellow-highlight, rgba(255, 255, 0, 0.7));
1583
+ }
1584
+ ::highlight(annotation-green) {
1585
+ background-color: var(--pie-annotation-green-highlight, rgba(0, 255, 127, 0.7));
1586
+ }
1587
+ ::highlight(annotation-blue) {
1588
+ background-color: var(--pie-annotation-blue-highlight, rgba(0, 191, 255, 0.7));
1589
+ }
1590
+ ::highlight(annotation-pink) {
1591
+ background-color: var(--pie-annotation-pink-highlight, rgba(255, 105, 180, 0.7));
1592
+ }
1593
+ ::highlight(annotation-orange) {
1594
+ background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.85));
1595
+ }
1596
+ ::highlight(annotation-underline) {
1597
+ text-decoration-thickness: 3px;
1598
+ }
1599
+ }
1600
+
1601
+ @media print {
1602
+ /* TTS highlighting is a transient read-along cue, not content. */
1603
+ ::highlight(tts-word),
1604
+ ::highlight(tts-sentence),
1605
+ [data-pie-tts-word-element="true"],
1606
+ [data-pie-tts-sentence-element="true"] {
1607
+ background-color: transparent;
1608
+ text-decoration: none;
1609
+ text-shadow: none;
1610
+ border-bottom: none;
1611
+ }
1612
+
1613
+ /* Annotations are student work and must survive printing, but a fill
1614
+ that reads fine on screen can print as an illegible wash, so each
1615
+ becomes an underline that keeps its colour coding. */
1616
+ ::highlight(annotation-yellow),
1617
+ ::highlight(annotation-green),
1618
+ ::highlight(annotation-blue),
1619
+ ::highlight(annotation-pink),
1620
+ ::highlight(annotation-orange) {
1621
+ background-color: transparent;
1622
+ border-bottom: 2px solid currentColor;
1623
+ }
1624
+ ::highlight(annotation-yellow) { border-bottom-color: #ffeb3b; }
1625
+ ::highlight(annotation-green) { border-bottom-color: #a6e1c5; }
1626
+ ::highlight(annotation-blue) { border-bottom-color: #a7e0f6; }
1627
+ ::highlight(annotation-pink) { border-bottom-color: #ff9fae; }
1628
+ ::highlight(annotation-orange) { border-bottom-color: #ffa500; }
1629
+ ::highlight(annotation-underline) {
1630
+ text-decoration-color: #000;
1631
+ border-bottom: none;
1632
+ }
1633
+ }
1634
+
1635
+ /* text-shadow is a direct property rather than a var(), so unlike the
1636
+ other TTS rules this one is not overridden by the adaptive path. */
1637
+ @media (prefers-reduced-motion: reduce) {
1638
+ ::highlight(tts-word),
1639
+ [data-pie-tts-word-element="true"] {
1640
+ text-shadow: none;
1641
+ }
1642
+ }
1643
+ `,Fk=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet"),Hk=Symbol.for("@pie-players/pie-assessment-toolkit/highlight-stylesheet-adopted"),Uk=e=>!!e&&typeof e.replaceSync=="function",xq=()=>{let e=globalThis,t=e[Fk];if(Uk(t))return t;let r=globalThis.CSSStyleSheet;if(typeof r!="function")return null;try{let n=new r;return Uk(n)?(n.replaceSync(L_),e[Fk]=n,n):null}catch{return null}},td=e=>{let t=e?.getRootNode?.();if(!Si(t))return;let r=t,n=r.adoptedStyleSheets;if(!n||typeof n!="object")return;let i=Array.from(n),o=r[Hk];if(o&&i.includes(o))return;let s=xq();if(s)try{r.adoptedStyleSheets=[...i,s],r[Hk]=s}catch{}},Tv="tts-word",Ev="tts-sentence",xc=e=>`annotation-${e}`,ol=e=>{let t=CSS.highlights.get(e);if(t)return t;let r=new Highlight;return CSS.highlights.set(e,r),r},rd=(e,t)=>{let r=CSS.highlights.get(e);if(r)for(let n of t)r.delete(n)},qk=e=>{let t=e[0]?.startContainer;return t?t.nodeType===Node.ELEMENT_NODE?t:Ps(t):null},Us={source:null,override:null},pw=class hb{constructor(){if(T(this,"ttsWordRanges",new Set),T(this,"ttsSentenceRanges",new Set),T(this,"ttsWordElementHighlights",new Set),T(this,"ttsSentenceElementHighlights",new Set),T(this,"annotations",new Map),T(this,"ttsStyleSource",null),T(this,"nextAnnotationId",1),T(this,"supported",!1),T(this,"rangeSerializer",void 0),T(this,"themeObserver",null),this.rangeSerializer=new Cq,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"||typeof MutationObserver>"u")return;let t=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(t),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let r of document.querySelectorAll("pie-theme"))this.themeObserver.observe(r,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(t){if(!t)return null;let r=t.trim();if(!r)return null;let n=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(r);if(n){let o=n[1];return o.length===3?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]}let i=/^rgba?\((.+)\)$/i.exec(r);if(i){let o=i[1].replace(/\//g,",").split(/[,\s]+/).map(c=>c.trim()).filter(Boolean),s=Number(o[0]),a=Number(o[1]),l=Number(o[2]);if(Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l))return[s,a,l]}if(typeof document<"u"){let o=document.createElement("span");if(o.style.color=r,typeof o.style.color=="string"&&o.style.color){document.body?.appendChild(o);let s=typeof getComputedStyle=="function"?getComputedStyle(o).color:"";o.remove();let a=s.trim();if(a&&a!==r)return this.parseColor(s)}}return null}relativeLuminance([t,r,n]){let i=l=>{let c=l/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4},o=i(t),s=i(r),a=i(n);return .2126*o+.7152*s+.0722*a}contrastRatio(t,r){let n=this.relativeLuminance(t),i=this.relativeLuminance(r),o=Math.max(n,i),s=Math.min(n,i);return(o+.05)/(s+.05)}blend(t,r,n){return[Math.round(t[0]*n+r[0]*(1-n)),Math.round(t[1]*n+r[1]*(1-n)),Math.round(t[2]*n+r[2]*(1-n))]}resolveAdaptiveTTSStyle(t){let r=[255,235,59],n=[17,24,39],i=[255,255,255],o=t||(typeof document<"u"?document.documentElement:null),s=o&&typeof getComputedStyle=="function"?getComputedStyle(o):null,a=this.parseColor(s?.getPropertyValue("--pie-background")||s?.backgroundColor)||i,l=this.parseColor(s?.getPropertyValue("--pie-text"))||n,c=Us.override,u=c?this.parseColor(c.color)||r:this.parseColor(s?.getPropertyValue("--pie-missing"))||r,d=c?[Math.max(.3,Math.min(.95,c.opacity))]:[.8,.72,.68,.62,.56,.5],f=d[d.length-1],h=-1/0;for(let P of d){let L=this.blend(u,a,P),J=this.contrastRatio(L,a),V=this.contrastRatio(L,l),Y=J*1.2+V*.8;if(J>=1.25&&V>=2.4){f=P;break}Y>h&&(h=Y,f=P)}let g=Math.max(.24,Math.min(.85,f*.55)),m=Math.max(.55,Math.min(.95,f+.2)),v=Math.max(.22,Math.min(.6,f*.45)),b=l,I=this.blend(b,a,m),C=this.contrastRatio(I,a),x=this.relativeLuminance(a)>.45?[0,0,0]:[255,255,255],$=C>=1.35?b:x;return{wordHighlight:`rgba(${u[0]}, ${u[1]}, ${u[2]}, ${f})`,sentenceHighlight:`rgba(${u[0]}, ${u[1]}, ${u[2]}, ${g})`,wordUnderline:`rgba(${$[0]}, ${$[1]}, ${$[2]}, ${m})`,wordShadow:`rgba(${$[0]}, ${$[1]}, ${$[2]}, ${v})`}}applyAdaptiveTTSStyle(t){if(typeof document>"u")return;t&&(this.ttsStyleSource=t,Us.source=t);let r=t??(Us.source?.isConnected?Us.source:null),n=this.resolveAdaptiveTTSStyle(r),i=document.documentElement.style,o=[["--pie-tts-word-highlight",n.wordHighlight],["--pie-tts-sentence-highlight",n.sentenceHighlight],["--pie-tts-line-highlight",n.sentenceHighlight],["--pie-tts-word-underline",n.wordUnderline],["--pie-tts-word-shadow",n.wordShadow]];for(let[s,a]of o)i.getPropertyValue?.(s)!==a&&i.setProperty(s,a)}initializeHighlights(){if(this.supported){ol(Tv),ol(Ev);for(let t of Object.values(Ad))ol(xc(t))}}registerStyles(){if(!this.supported||typeof document>"u"||document.getElementById("pie-highlight-styles"))return;let t=document.createElement("style");t.id="pie-highlight-styles",t.textContent=L_,document.head.appendChild(t)}highlightTTSWord(t){if(!this.supported)return;this.applyAdaptiveTTSStyle(qk(t)),this.clearTTSWord();let r=ol(Tv);for(let n of t)td(n.startContainer),r.add(n),this.ttsWordRanges.add(n);this.highlightTTSWordElementFallbacks(t.filter(n=>n.startContainer!==n.endContainer||n.startContainer.nodeType!==Node.TEXT_NODE))}highlightTTSWordElement(t){this.supported&&(this.applyAdaptiveTTSStyle(t),td(t),this.clearTTSWord(),t.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(t))}highlightTTSSentence(t){if(!this.supported)return;this.applyAdaptiveTTSStyle(qk(t)),this.clearTTSSentence();let r=ol(Ev);for(let n of t)td(n.startContainer),r.add(n),this.ttsSentenceRanges.add(n);this.highlightTTSElementFallbacks(t)}highlightTTSSentenceElements(t){if(this.supported){this.applyAdaptiveTTSStyle(t[0]||null),this.clearTTSSentence();for(let r of t)td(r),r.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(r)}}highlightTTSElementFallbacks(t){typeof Element>"u"||this.highlightElementFallbacks(t,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,hb.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(t){typeof Element>"u"||this.highlightElementFallbacks(t,"data-pie-tts-word-element",this.ttsWordElementHighlights,hb.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(t,r,n,i){let o=s=>s.nodeType===Node.ELEMENT_NODE?s:Ps(s);for(let s of t){let a=s.commonAncestorContainer,l=Si(a)?a:o(a);if(!l)continue;let c=[],u=o(s.startContainer),d=o(s.endContainer);for(let f of[u,d]){let h=f;for(;h;)h.matches?.(i)&&c.push(h),h=Ps(h)}!Si(l)&&l.matches?.(i)&&c.push(l),c.push(...Array.from(l.querySelectorAll(i)));for(let f of new Set(c)){try{if(!s.intersectsNode(f)&&!Su(f,u)&&!Su(f,d))continue}catch{continue}f.setAttribute(r,"true"),n.add(f)}}}clearTTSWord(){if(this.supported){rd(Tv,this.ttsWordRanges),this.ttsWordRanges.clear();for(let t of this.ttsWordElementHighlights)t.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}}clearTTSSentence(){if(this.supported){rd(Ev,this.ttsSentenceRanges),this.ttsSentenceRanges.clear();for(let t of this.ttsSentenceElementHighlights)t.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}}clearTTS(){this.clearTTSWord(),this.clearTTSSentence(),Us.source===this.ttsStyleSource&&(Us.source=null),this.ttsStyleSource=null}addAnnotation(t,r=Ad.YELLOW){let n=`annotation-${this.nextAnnotationId++}`,i=t.cloneRange();td(i.startContainer);let o={id:n,range:i,type:so.ANNOTATION,color:r,timestamp:Date.now()};return this.annotations.set(n,o),this.supported&&ol(xc(r)).add(i),n}removeAnnotation(t){let r=this.annotations.get(t);if(!r){console.warn(`[HighlightCoordinator] Annotation ${t} not found`);return}this.supported&&rd(xc(r.color),[r.range]),this.annotations.delete(t)}clearAnnotations(){if(this.supported)for(let t of this.annotations.values())rd(xc(t.color),[t.range]);this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(t){return this.annotations.get(t)??null}changeAnnotationColor(t,r){let n=this.annotations.get(t);if(!n)return;let i=n.color;i!==r&&(n.color=r,this.supported&&(rd(xc(i),[n.range]),ol(xc(r)).add(n.range)))}exportAnnotations(t=document.body){return this.getAnnotations().map(r=>({...this.rangeSerializer.serialize(r.range,t),id:r.id,color:r.color,timestamp:r.timestamp}))}importAnnotations(t,r=document.body){let n=0;for(let i of t){let o=this.rangeSerializer.deserialize(i,r);o&&(this.addAnnotation(o,i.color),n++)}return n}highlightRange(t,r,n=Ad.YELLOW){if(this.supported)switch(r){case so.TTS_WORD:this.highlightTTSWord([t]);break;case so.TTS_SENTENCE:this.highlightTTSSentence([t]);break;case so.ANNOTATION:this.addAnnotation(t,n)}}clearHighlights(t){if(this.supported)switch(t){case so.TTS_WORD:this.clearTTSWord();break;case so.TTS_SENTENCE:this.clearTTSSentence();break;case so.ANNOTATION:this.clearAnnotations()}}clearAll(){this.supported&&(this.clearTTS(),this.clearAnnotations())}isSupported(){return this.supported}updateTTSHighlightStyle(t,r){if(!this.supported||typeof document>"u"||!document.getElementById("pie-highlight-styles"))return;let n=(i=>{let o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(i);return o?{r:parseInt(o[1],16),g:parseInt(o[2],16),b:parseInt(o[3],16)}:null})(t);n&&(Us.override={color:`rgb(${n.r}, ${n.g}, ${n.b})`,opacity:Math.max(.2,Math.min(.95,r)),owner:this},this.applyAdaptiveTTSStyle())}destroy(){this.supported&&(this.clearTTS(),this.clearAnnotations(),Us.override?.owner===this&&(Us.override=null),this.themeObserver?.disconnect(),this.themeObserver=null)}};T(pw,"SENTENCE_FALLBACK_SELECTOR","math, mjx-container, svg, img, canvas, [role='img']");T(pw,"WORD_FALLBACK_SELECTOR","svg, img, canvas, [role='img']");function Rq(e){if(!e)return null;let t=e.payload;if(!t||typeof t!="object")return null;let r=t.media;if(!r||typeof r!="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(HD(r.version))return console.warn(`[spoken-audio] card's media declares version ${String(r.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`),null;if(r.kind!==void 0&&r.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${r.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let n=qD(r.sources);return n.length===0?(console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null):{sources:n,fragment:Lx(t.fragment),label:WD(r.label)}}var Pq="[data-pie-shell-root]",_q=e=>e?$_(e,Pq):null,pb="en-US",N_=(e,t)=>{let r=e?e.nodeType===1?e:Ps(e):null;for(;r;){let n=r.getAttribute("lang")?.trim();if(n)return n;if(t&&r===t)return;r=Ps(r)}},D_=(e,t={})=>{let r=t.boundary!==void 0?t.boundary:_q(e);return(r?N_(e,r):void 0)||t.contentLanguage?.trim()||void 0},Aq=(e,t={})=>D_(e,t)??pb,ln=e=>e.trim().replace(/\s+/g," "),$q=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,j_=e=>{if(e.hidden||e.tagName?.toLowerCase()==="mjx-assistive-mml"||e.getAttribute("aria-hidden")==="true"||e.hasAttribute("inert"))return!0;let t=e.classList;if(t?.contains("sr-only")||t?.contains("pie-sr-only")||t?.contains("visually-hidden"))return!0;if(typeof window<"u"){let r=window.getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!0;let n=Number.parseFloat(r.width||"0"),i=Number.parseFloat(r.height||"0"),o=Number.isFinite(n)&&Number.isFinite(i)&&n<=1&&i<=1,s=r.clipPath.includes("inset(50%")||r.clipPath.includes("inset(100%")||r.clip.includes("rect(0px, 0px, 0px, 0px)")||r.clip.includes("rect(0 0 0 0)");if((r.position==="absolute"||r.position==="fixed")&&o&&(r.overflow==="hidden"||s)||r.opacity==="0"&&o)return!0}return!1},ig=(e,t)=>{let r=e.nodeType===1?e:ho(e);for(;r;){if(j_(r))return!0;if(t&&r===t)break;r=ho(r)}return!1},Wk="data-tts-suppress",z_=new Set(["computer-read-aloud","all"]),Vk=new Set([...z_,"screen-reader"]),Gk=new Set,Mq=e=>{let t=e.getAttribute?.(Wk);if(t==null)return!1;let r=t.trim().toLowerCase();return z_.has(r)?!0:Vk.has(r)?!1:(Gk.has(r)||(Gk.add(r),console.warn(`[tts] ${Wk}="${t}" is not one of ${Array.from(Vk).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.`)),!0)},mb=(e,t)=>{let r=e.nodeType===1?e:ho(e);for(;r;){if(Mq(r))return!0;if(t&&r===t)break;r=ho(r)}return!1},zu=(e,t)=>ig(e,t)||mb(e),Yk=(e,t)=>{if(typeof e.intersectsNode!="function")return{text:e.toString(),filtered:!1};let r=[],n=!1;for(let i of Wf(t))Vf(e,i)&&(zu(i,t)?n=!0:r.push(B_(i,e)));return{text:r.join(""),filtered:n}},B_=(e,t)=>{let r=e.textContent||"",n=e===t.startContainer?t.startOffset:0,i=e===t.endContainer?t.endOffset:r.length;return r.slice(n,i)},gb=(e,t,r)=>{let n=null,i=null;for(let o of Wf(t)){if(zu(o,r))continue;let s=o.textContent||"",a=s.search(/\S/);a!==-1&&(n??(n={node:o,offset:a}),i={node:o,offset:s.trimEnd().length-1})}return!n||!i?Vf(e,t):fb(e,n.node,n.offset)&&fb(e,i.node,i.offset)},F_=(e,t,r)=>{if(!e||!t||/\s/.test(e)||/\s/.test(t))return!1;let n=r?.boundarySpacingMode??"segmenterPreferred";if(n==="none")return!1;if(n==="segmenterPreferred")try{let s=globalThis.Intl?.Segmenter;if(typeof s=="function"){let a=new s(r?.locale,{granularity:"word"});if(Array.from(a.segment(`${e}${t}`)).filter(l=>l.isWordLike!==!1&&l.segment.trim().length>0).length>=2)return!0}}catch{}let i=/[A-Za-z0-9]/.test(e),o=/[A-Za-z0-9]/.test(t);return i&&o},$d=(e,t)=>{let r=new Map;if(typeof document>"u")return{text:"",map:r};let n=[],i=0,o=!0,s=!1,a=null,l=null;for(let u of Wf(e))if(ho(u)&&!zu(u,e)){let d=u.textContent||"",f=d.match(/\S/),h=f?f[0]:null;!o&&!s&&F_(l,h,t)&&(n.push(" "),a&&r.set(i,a),i++,s=!0);for(let g=0;g<d.length;g++){let m=d[g],v=/\s/.test(m);o?v||(o=!1,n.push(m),r.set(i,{node:u,offset:g}),a={node:u,offset:g},i++,s=!1,l=m):v?(s||(n.push(" "),r.set(i,{node:u,offset:g}),a={node:u,offset:g},i++),s=!0):(n.push(m),r.set(i,{node:u,offset:g}),a={node:u,offset:g},i++,s=!1,l=m)}}let c=n.join("").trimEnd();for(;r.has(c.length);)r.delete(c.length);return{text:c,map:r}},Oq=/^\s*<speak[\s/>]/i,H_=e=>Oq.test(e),Lq=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),Kk=new Set(["audio","phoneme"]),U_=e=>e.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),cp=(e,t,r)=>{for(let n=0;n<t.length;n++)e.push({char:t[n],rawOffset:r===null?null:r+n})},Nq=(e,t,r)=>{let n=t.slice(r).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);return n?(cp(e,U_(n[0]),r),n[0].length):0},Xk=e=>{e.push({char:" ",rawOffset:null})},Dq=e=>{let t=new Map,r=[],n=!0;for(let i of e){if(/\s/.test(i.char)){!n&&r.length>0&&(r.push(" "),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1)),n=!0;continue}r.push(i.char),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1),n=!1}for(;r.length>0&&r[r.length-1]===" ";)r.pop();for(let[i,o]of t)o>=r.length&&t.delete(i);return{text:r.join(""),rawToSpokenOffsetMap:t}},jq=e=>e.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||"",zq=(e,t)=>{let r=new RegExp(`${t}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),n=e.match(r);return U_(n?.[2]??n?.[3]??"")||null},q_=e=>{let t=[],r=!1,n=!1,i=0;for(;i<e.length;){let s=e[i];if(s!=="<"){if(s==="&"){let f=Nq(t,e,i);if(f>0){i+=f;continue}}cp(t,s,i),i++;continue}let a=e.indexOf(">",i+1);if(a<0){cp(t,s,i),i++;continue}n=!0;let l=e.slice(i,a+1),c=jq(l),u=/^<\s*\//.test(l),d=/\/\s*>$/.test(l);if(!u&&c==="sub"){let f=zq(l,"alias");if(!f){r=!0,i=a+1;continue}cp(t,f,null);let h=e.toLowerCase().indexOf("</sub>",a+1);i=h>=0?h+6:a+1;continue}if(!u&&c==="break"){Xk(t),i=a+1;continue}if(!u&&Kk.has(c)&&(r=!0,d)){i=a+1;continue}c&&!Lq.has(c)&&!Kk.has(c)&&c!=="break"&&c!=="sub"&&(r=!0),!u&&(c==="p"||c==="s")&&Xk(t),i=a+1}let o=Dq(t);return{spokenText:ln(o.text),rawToSpokenOffsetMap:o.rawToSpokenOffsetMap,unsupportedSemantic:r,hasMarkup:n}},Bq=$q(),Fq=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),Hq=e=>{let t=e.toLowerCase();return Fq.get(t)||t},W_=e=>{let t=[];for(let r of e.matchAll(Bq)){let n=r[0],i=r.index??0;t.push({text:n,normalized:Hq(n),start:i,end:i+n.length})}return t},Uq=e=>W_(e).map((t,r)=>({...t,id:`speech-token-${r}`,sourceStart:t.start,sourceEnd:t.end,coordinateSystem:"normalized-speech"})),og=e=>{let t=q_(e.speechText);return{speechText:e.speechText,spokenText:t.spokenText,tokens:Uq(t.spokenText),rawToSpokenOffsetMap:t.rawToSpokenOffsetMap,boundaryOffsetSpace:t.unsupportedSemantic?"unsupported":t.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:t.unsupportedSemantic,hasMarkup:t.hasMarkup}},mw=e=>!!(e&&/^<[^>]+>$/.test(e.trim())),sg=e=>!e||mw(e)?null:og({speechText:e}).tokens[0]?.normalized??null,qq=(e,t)=>e.find(r=>r.start<=t&&t<r.end)||null,Wq=(e,t)=>{let r=e.rawToSpokenOffsetMap.get(t);if(r!==void 0)return r;for(let n=t;n<e.speechText.length;n++){let i=e.rawToSpokenOffsetMap.get(n);if(i!==void 0)return i;if(e.speechText[n]===">")break}return null},vb=(e,t,r)=>{if(t===null)return null;let n=qq(e.tokens,t);return n?{token:n,start:t,length:Math.max(1,Math.min(r,n.end-t)),confidence:.75}:null},yb=(e,t)=>!!(e&&t&&e.token.normalized===t),Vq=e=>{if(e.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(e.position)||mw(e.boundaryWord))return null;let t=Math.max(1,Number.isFinite(e.length)?e.length:1),r=sg(e.boundaryWord),n=vb(e.tokenization,Wq(e.tokenization,e.position),t),i=vb(e.tokenization,e.position>=0&&e.position<e.tokenization.spokenText.length?e.position:null,t);return yb(n,r)?{...n,confidence:1}:yb(i,r)?{...i,confidence:1}:r?null:e.tokenization.boundaryOffsetSpace==="raw-ssml"?n||i:i||n},Gq=e=>{if(e.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(e.position)||mw(e.boundaryWord))return null;let t=Math.max(1,Number.isFinite(e.length)?e.length:1),r=sg(e.boundaryWord),n=vb(e.tokenization,e.position>=0&&e.position<e.tokenization.spokenText.length?e.position:null,t);return yb(n,r)?{...n,confidence:1}:r?null:n},Yq=[{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}],Kq=(e,t)=>{let r=[];for(let n=0;n<e.length;n++){for(let i=0;i<t.length;i++)e[n].normalized===t[i].normalized&&r.push({spokenStartToken:n,spokenEndToken:n+1,visibleToken:i,score:10});for(let i of Yq){let o=e.slice(n,n+i.phrase.length);if(o.length===i.phrase.length&&o.every((s,a)=>s.normalized===i.phrase[a]))for(let s=0;s<t.length;s++)t[s].text===i.visible&&r.push({spokenStartToken:n,spokenEndToken:n+i.phrase.length,visibleToken:s,score:i.score})}}return r},Xq=(e,t)=>{let r=Kq(e,t).sort((l,c)=>e[l.spokenStartToken].start-e[c.spokenStartToken].start||t[l.visibleToken].start-t[c.visibleToken].start),n=Array(r.length).fill(0),i=Array(r.length).fill(-1);for(let l=0;l<r.length;l++){let c=r[l];n[l]=c.score;for(let u=0;u<l;u++){let d=r[u];if(d.spokenEndToken<=c.spokenStartToken&&d.visibleToken<c.visibleToken){let f=c.spokenStartToken-d.spokenEndToken,h=c.visibleToken-d.visibleToken-1,g=Math.max(0,Math.abs(f-h)-2),m=n[u]+c.score-g;m>n[l]&&(n[l]=m,i[l]=u)}}}let o=-1;for(let l=0;l<n.length;l++)(o<0||n[l]>n[o])&&(o=l);if(o<0)return[];let s=[],a=o;for(;a>=0;)s.unshift(r[a]),a=i[a];return s.map(l=>{let c=e[l.spokenStartToken],u=e[l.spokenEndToken-1],d=t[l.visibleToken];return{spokenStart:c.start,spokenEnd:u.end,visibleStart:d.start,visibleEnd:d.end,score:l.score}})},Jq=(e,t,r)=>{if(e.length===0)return 0;let n=e.length/Math.max(1,Math.min(t.length,r.length)),i=e.reduce((o,s)=>o+s.score,0)/e.length/10;return Math.min(1,n*i)},V_=e=>{let t=og({speechText:e.speechText}),r=ln(e.visibleText),n=t.tokens,i=W_(r),o=t.unsupportedSemantic?[]:Xq(n,i),s=Jq(o,n,i),a=t.spokenText===r&&t.spokenText.length>0,l=o.length===1&&o[0].score===10&&n.length<=2&&i.length<=2;return{speech:t,visibleText:r,playbackMode:t.unsupportedSemantic?"region-fallback":a?"exact-word":(o.length>=2||l)&&s>=.12?"anchor-span":"region-fallback",anchors:o,confidence:s}},Qq=(e,t)=>{if(e.playbackMode==="region-fallback")return null;let r=e.anchors.find(o=>o.spokenStart<=t&&t<o.spokenEnd);if(r)return{start:r.visibleStart,end:r.visibleEnd};let n=null,i=null;for(let o of e.anchors){if(o.spokenEnd<=t){n=o;continue}if(o.spokenStart>t){i=o;break}}return n&&i?{start:Math.min(n.visibleStart,i.visibleStart),end:Math.max(n.visibleEnd,i.visibleEnd)}:null},Zq=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"]]]),eW=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),G_=new Map([["2",["squared"]],["3",["cubed"]]]),tW=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),rW=e=>e.replace(/\s+/g," ").trim(),Wl=e=>(e.localName||e.tagName||"").toLowerCase(),nW=e=>e.nodeType===Node.ELEMENT_NODE,Iu=e=>Array.from(e.childNodes).filter(nW),gw=e=>rW(e.textContent||""),sa=(e,t)=>({type:"element-range",quality:t,element:e}),iW=e=>{switch(e){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"}},oW=(e,t)=>t==="operator"?e==="−"?"-":e:e.toLowerCase(),sW=(e,t,r)=>r==="fraction"?["over","divided by"]:r==="superscript"?G_.get(e)??[]:e==="|"?["absolute value"]:t==="operator"?Zq.get(e)||[]:[],ac=e=>{let t=e.normalized??oW(e.text,e.kind||"unknown");return{id:`math-token-${e.state.nextId++}`,kind:e.kind,role:e.role,text:e.text,normalized:t,spokenAliases:sW(e.text,e.kind,e.role),sourceElement:e.sourceElement,path:e.path,target:e.target||sa(e.sourceElement,"element-range"),optional:e.optional}},lc=(e,t,r="tokens")=>{e[r].push(t)},Y_=(e,t,r)=>{Iu(e).forEach((n,i)=>aa(n,t,`${r}/${Wl(n)}[${i}]`))},aW=(e,t,r)=>{let n=Iu(e);n[0]&&aa(n[0],t,`${r}/numerator`),lc(t,ac({state:t,kind:"structure",role:"fraction",text:"/",sourceElement:e,path:r,target:sa(e,"element-range")})),n[1]&&aa(n[1],t,`${r}/denominator`)},lW=(e,t,r)=>{let n=e.getAttribute("open")||"(",i=e.getAttribute("close")||")";lc(t,ac({state:t,kind:"operator",role:n==="|"?"absolute-value-fence":"open-fence",text:n,sourceElement:e,path:`${r}/open`,target:sa(e,"element-range")})),Y_(e,t,r),lc(t,ac({state:t,kind:"operator",role:i==="|"?"absolute-value-fence":"close-fence",text:i,sourceElement:e,path:`${r}/close`,target:sa(e,"element-range")}))},cW=(e,t,r)=>{let n=Iu(e);n[0]&&aa(n[0],t,`${r}/base`);let i=n[1];if(!i)return;let o=gw(i);if(G_.has(o)){lc(t,ac({state:t,kind:"structure",role:"superscript",text:o,normalized:o,sourceElement:i,path:`${r}/exponent`,target:sa(e,"element-range")}));return}aa(i,t,`${r}/exponent`)},uW=(e,t,r,n)=>{lc(t,ac({state:t,kind:"structure",role:n,text:gw(e)||n,normalized:`\0${n}`,sourceElement:e,path:r,target:sa(e,"element-range")}))},dW=(e,t,r)=>{let n=0;for(let i of Iu(e))(Wl(i)==="mtr"||Wl(i)==="mlabeledtr")&&(n++,lc(t,ac({state:t,kind:"layout",role:"table-row",text:`row-${n}`,normalized:`row-${n}`,sourceElement:i,path:`${r}/row[${n}]`,target:sa(i,"region-fallback")}),"layoutTargets")),aa(i,t,`${r}/${Wl(i)}[${n}]`)},fW=(e,t,r)=>{let n=gw(e);if(!n)return;let i=iW(Wl(e)),o=i==="operator"?eW.get(n):void 0,s=o??(i==="operator"&&(n==="("||n===")")?"grouping-fence":i);lc(t,ac({state:t,kind:i,role:s,text:n,sourceElement:e,path:r,target:o&&e.parentElement?sa(e.parentElement,"region-fallback"):void 0,optional:!!o||s==="grouping-fence"}))},aa=(e,t,r)=>{let n=Wl(e);switch(n){case"annotation":case"annotation-xml":return;case"semantics":{let i=Iu(e).find(o=>{let s=Wl(o);return s!=="annotation"&&s!=="annotation-xml"});i&&aa(i,t,`${r}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":fW(e,t,r);return;case"mfrac":aW(e,t,r);return;case"msup":cW(e,t,r);return;case"mfenced":lW(e,t,r);return;case"mtable":dW(e,t,r);return;case"mphantom":return;case"maction":{let i=Iu(e)[0];i&&aa(i,t,`${r}/action`);return}default:{let i=tW.get(n);if(i){uW(e,t,r,i);return}Y_(e,t,r)}}},hW=e=>{let t={tokens:[],layoutTargets:[],nextId:0};return aa(e,t,"/math"),{tokens:t.tokens,layoutTargets:t.layoutTargets,expressionTarget:sa(e,"region-fallback")}},pW=e=>e.boundary&&e.alignment.segments.find(t=>t.speechTokenIds.includes(e.boundary.token.id))?.target||null,mW=e=>{let t=[],r=new Set,n=i=>{let o=i.toLowerCase().trim().split(/\s+/).filter(Boolean);if(o.length===0)return;let s=o.join(" ");r.has(s)||(r.add(s),t.push(o))};n(e.normalized);for(let i of e.spokenAliases)n(i);return t},Jk=(e,t,r)=>{let n=0;for(let i of r){if(i.length<=n)continue;let o=!0;for(let s=0;s<i.length;s++){let a=e[t+s];if(!a||a.normalized.toLowerCase()!==i[s]){o=!1;break}}o&&(n=i.length)}return n},gW=(e,t)=>{let r=[],n=0;for(let i of t){let o=mW(i);if(i.optional){let s=Jk(e,n,o);s>0&&(r.push({speechTokens:e.slice(n,n+s),math:i}),n+=s);continue}for(;n<e.length;){let s=Jk(e,n,o);if(s>0){r.push({speechTokens:e.slice(n,n+s),math:i}),n+=s;break}n++}}return r},vW=(e,t,r)=>{let n=r.filter(s=>!s.optional).length,i=e.filter(s=>!s.math.optional).length,o=e.reduce((s,a)=>s+a.speechTokens.length,0);return n>0&&i===n&&o===t.length},yW=e=>e.map(({speechTokens:t,math:r})=>({speechTokenIds:t.map(n=>n.id),mathTokenIds:[r.id],score:1,confidence:1,target:r.target})),bW=e=>{let t=e.minExactWordConfidence??.95,r=gW(e.speech.tokens,e.math.tokens),n=vW(r,e.speech.tokens,e.math.tokens)?1:0;return{segments:n>=t?yW(r):[],confidence:n,fallbackTarget:e.math.expressionTarget}},gm=e=>{let t=og({speechText:e.speechText}),r=hW(e.mathElement);return{speech:t,math:r,result:bW({speech:t,math:r})}},wW=(e,t)=>{let r=Gq({tokenization:e.speech,position:t.position,length:t.length,boundaryWord:t.boundaryWord});return pW({alignment:e.result,boundary:r})},SW=(e,t)=>{let r=sg(t.boundaryWord);if(!r)return null;let n=e.math.tokens.filter(i=>i.normalized.toLowerCase()===r||i.spokenAliases.some(o=>o.toLowerCase()===r));return n.length===1?n[0].target:null},IW=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"]),kW=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"]),K_=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),TW=e=>K_(e).replace(/"/g,"&quot;"),EW=(e,t)=>{let r=e.toLowerCase(),n=t.trim().toLowerCase();return!!(r.startsWith("on")||!kW.has(r)||n.includes("javascript:")||n.includes("data:text/html"))},CW=e=>{let t=e.localName.toLowerCase();if(!IW.has(t))return!1;let r=e.namespaceURI;return!r||r==="http://www.w3.org/1998/Math/MathML"||r==="http://www.w3.org/1999/xhtml"},X_=e=>{if(e.nodeType===Node.TEXT_NODE)return K_(e.textContent||"");if(e.nodeType===Node.COMMENT_NODE)return"";if(e.nodeType!==Node.ELEMENT_NODE)return null;let t=e;if(!CW(t))return null;let r=t.localName.toLowerCase(),n=[];for(let o of Array.from(t.attributes)){let s=o.name.toLowerCase();if(!EW(s,o.value)){if(s==="xmlns"&&o.value!=="http://www.w3.org/1998/Math/MathML")return null;n.push(`${s}="${TW(o.value)}"`)}}r==="math"&&!n.some(o=>o.startsWith("xmlns="))&&n.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let i=[];for(let o of Array.from(t.childNodes)){let s=X_(o);if(s===null)return null;i.push(s)}return`<${r}${n.length>0?` ${n.join(" ")}`:""}>${i.join("")}</${r}>`},xW=e=>typeof DOMParser<"u"?new DOMParser().parseFromString(e,"application/xml"):null,up=e=>{let t=String(e||"").trim();if(!t)return null;let r=xW(t);if(!r||r.getElementsByTagName("parsererror").length>0)return null;let n=r.documentElement;return!n||n.localName.toLowerCase()!=="math"?null:X_(n)},J_=e=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:e}),vw=e=>e.classList?.contains("MathJax")||e.tagName?.toLowerCase()==="mjx-container",Q_=e=>e.tagName?.toLowerCase()==="mjx-assistive-mml",yw=e=>{let t=e.tagName?.toLowerCase();return t==="annotation"||t==="annotation-xml"},RW=e=>{let t=e.getAttribute("data-mathml");return t&&t.trim()?t:null},PW=e=>ng(e,"mjx-assistive-mml math")?.outerHTML||null,_W=e=>{if(e.tagName.toLowerCase()==="math")return up(e.outerHTML);let t=RW(e);if(t){let r=up(t);if(r)return r}if(vw(e)){let r=PW(e);if(r){let n=up(r);if(n)return n}}return null},AW=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),$W=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),MW=(e,t)=>{let r=ho(e),n=null;for(;r&&r!==t;){let i=(r.getAttribute("role")||"").toLowerCase(),o=r.tagName.toUpperCase();if(AW.has(o)||$W.has(i)){n=r;break}r=ho(r)}return n||t},OW=e=>!!(typeof e.querySelector=="function"&&ng(e,"math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||e.tagName?.toLowerCase()==="math"||e.hasAttribute?.("data-mathml")||vw(e),El=(e,t,r)=>{/[.,;:!?]/.test(t)&&e.chars.length>0&&e.chars[e.chars.length-1]===" "&&(e.chars.pop(),e.position--,e.map.delete(e.position)),e.chars.push(t),r?(e.map.set(e.position,r),e.lastMapped=r):e.lastMapped&&e.map.set(e.position,e.lastMapped),e.position++},Z_=(e,t)=>{if(e.inLeadingWhitespace||e.lastCharWasWhitespace||e.chars.length===0)return!1;let r=e.chars[e.chars.length-1];return F_(r,t,e.options)},eA=(e,t,r=0,n=(t.textContent||"").length)=>{let i=t.textContent||"",o=!1;for(let s=r;s<n;s++){let a=i[s],l=/\s/.test(a);if(e.inLeadingWhitespace){l||(e.inLeadingWhitespace=!1,El(e,a,{node:t,offset:s}),o=!0,e.lastCharWasWhitespace=!1);continue}if(l){e.lastCharWasWhitespace||El(e," ",{node:t,offset:s}),e.lastCharWasWhitespace=!0;continue}!o&&Z_(e,a)&&El(e," ",{node:t,offset:s}),El(e,a,{node:t,offset:s}),o=!0,e.lastCharWasWhitespace=!1}},LW=(e,t)=>{for(let r=0;r<t.text.length;r++){let n=t.text[r],i=/\s/.test(n),o=t.map.get(r)||null,s=o?.node||e.lastMapped?.node||null,a=o?.offset??e.lastMapped?.offset??0,l=o?{node:o.node,offset:o.offset}:s?{node:s,offset:a}:null;if(e.inLeadingWhitespace){if(i)continue;e.inLeadingWhitespace=!1}if(i){e.lastCharWasWhitespace||El(e," ",l),e.lastCharWasWhitespace=!0;continue}r===0&&Z_(e,n)&&El(e," ",l),El(e,n,l),e.lastCharWasWhitespace=!1,o?(e.map.set(e.position-1,{node:o.node,offset:o.offset}),e.lastMapped={node:o.node,offset:o.offset}):s&&e.map.set(e.position-1,{node:s,offset:a})}},NW=e=>{if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror").length>0)return"";let r=[],n=i=>{if(i.nodeType===3){let s=i.textContent||"";s.trim()&&r.push(s);return}if(i.nodeType!==1)return;let o=i;if(!yw(o))for(let s of Array.from(o.childNodes))n(s)};return n(t.documentElement),ln(r.join(" "))},DW=(e,t)=>{let r=new Map,n=vw(e)?ng(e,"mjx-assistive-mml math"):null;if(!n)return r;let i=[],o=a=>{if(a.nodeType===3){let l=a.textContent||"";for(let c=0;c<l.length;c++)/\s/.test(l[c])||i.push({node:a,offset:c});return}if(!(a.nodeType!==1||yw(a)))for(let l of wu(a))o(l)};o(n);let s=0;for(let a=0;a<t.length;a++){if(/\s/.test(t[a]))continue;let l=i[s];if(l?.node.textContent?.[l.offset]!==t[a])return new Map;r.set(a,l),s++}return s===i.length?r:new Map},jW=(e,t,r)=>{let n=J_(r),i=a=>{if(zu(a,e))return;if(a.nodeType===3){eA(n,a);return}if(a.nodeType!==1)return;let l=a;if(!(Q_(l)||yw(l)))for(let c of wu(l))i(c)};i(e),tA(n);let o=ln(n.chars.join(""));if(o)return{text:o,map:n.map};let s=NW(t);return s?{text:s,map:DW(e,s)}:$d(e,r)},tA=e=>{for(;e.chars.length>0&&/\s/.test(e.chars[e.chars.length-1]);)e.chars.pop(),e.position--,e.map.delete(e.position)},Qk=(e,t,r)=>{let n=J_(t),i=[],o=0,s,a=!1,l=()=>{let d=ln(n.chars.slice(o,n.chars.length).join(""));d&&i.push({type:"text",text:d,sourceElement:s}),o=n.chars.length,s=void 0},c=d=>{if(zu(d,e)||r&&!Vf(r,d))return;if(d.nodeType===3){let g=MW(d,e);s&&g!==s&&l(),s=g;let m=d;eA(n,m,r?.startContainer===m?r.startOffset:void 0,r?.endContainer===m?r.endOffset:void 0);return}if(d.nodeType!==1)return;let f=d;if(Q_(f))return;let h=_W(f);if(h&&(!r||gb(r,f,e))){l();let g=jW(f,h,t);LW(n,g);let m=ln(g.text);i.push({type:"math",mathml:h,fallbackText:m,sourceElement:f}),o=n.chars.length,a=!0;return}for(let g of wu(f))c(g)};for(let d of wu(e))c(d);tA(n),l();let u=n.chars.join("");for(;n.map.has(u.length);)n.map.delete(u.length);return{visibleText:u,map:n.map,chunks:i,containsMathMarkup:a}},qc=(e,t,r)=>{if(r)return Qk(e,t,r);if(!OW(e)){let{text:n,map:i}=$d(e,t);return{visibleText:n,map:i,chunks:n?[{type:"text",text:n}]:[],containsMathMarkup:!1}}return Qk(e,t)},vm=ei("tts-math-speech",xu),Zk=Promise.resolve(),zW=e=>(e||"en").split("-")[0].toLowerCase()||"en",BW=e=>{let t=null,r=!1;return n=>{if(!t){HA(n);let i=e();t=i,i.catch(o=>{if(t===i&&(t=null),r){vm.debug("speech-rule-engine failed to load again",o);return}r=!0,vm.warn("speech-rule-engine failed to load; math reads as its visible text until a later read loads it.",o)})}return t}},FW=BW(()=>Mr(async()=>{const{default:e}=await import("./chunks/sre-engine-jd8cc08x-42d270e5.js");return{default:e}},[],import.meta.url).then(({default:e})=>{if(!e||typeof e.toSpeech!="function")throw Error("speech-rule-engine did not expose toSpeech");return e})),rA=e=>{let t=null;return()=>(t??(t=FW(ku(e)?.engineOptions)),t)},HW=e=>e==="en"?"clearspeak":"mathspeak",eT=e=>!!e&&typeof e=="object"&&!Array.isArray(e),tT=e=>typeof e=="string"&&e.trim()?e.trim():void 0,ku=e=>{if(!eT(e))return;let t=tT(e.domain),r=tT(e.style),n=eT(e.engineOptions)?e.engineOptions:void 0;if(!(!t&&!r&&!n))return{...t?{domain:t}:{},...r?{style:r}:{},...n?{engineOptions:n}:{}}},UW=async(e,t,r,n)=>{let i=zW(t),o=ku(n),s=o?.engineOptions||{};await e.setupEngine?.({...FA(s),...s,locale:i,domain:o?.domain||HW(i),style:o?.style||"default",modality:"speech",markup:r}),await e.engineReady?.()},qW=async e=>{let t=Zk.then(e,e);return Zk=t.then(()=>{},()=>{}),t},nA=async(e,t,r,n,i)=>qW(async()=>(await UW(e,r,n,i),e.toSpeech(t))),WW=e=>e.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),VW=async(e,t,r,n)=>{try{let i=WW(await nA(e,t,r,"ssml",n));return i.includes("<speak")?i:null}catch(i){return vm.debug("math SSML generation failed; using plain",{message:i instanceof Error?i.message:String(i)}),null}},bw=async(e,t={})=>{if(!e.some(c=>c.type==="math"))return{speechText:ln(e.map(c=>c.type==="text"?c.text:c.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let r=null,n=!1,i=!1,o=t.loadSre||rA(t.mathSpeech),s=[];for(let c of e){if(c.type==="text"){s.push(c.text);continue}try{r||(r=await o());let u=ln(await nA(r,c.mathml,t.language,"none",t.mathSpeech));if(u){s.push(u),n=!0;continue}i=!0,s.push(c.fallbackText)}catch(u){i=!0,vm.debug("math speech generation failed; using visible fallback",{message:u instanceof Error?u.message:String(u)}),s.push(c.fallbackText)}}let a=ln(s.join(" ")),l;return t.produceSsml&&r&&n&&e.length===1&&e[0].type==="math"&&(l=await VW(r,e[0].mathml,t.language,t.mathSpeech)??void 0),{speechText:a,usedMathSpeech:n,usedFallback:i,ssml:l}},GW=e=>(e||"en").split("-")[0].toLowerCase()||"en",YW="sre-v1",KW=256,bb=e=>Array.isArray(e)?`array:[${e.map(bb).join(",")}]`:e&&typeof e=="object"?`object:{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${bb(r)}`).join(",")}}`:e===null?"null:null":typeof e>"u"?"undefined:":typeof e=="function"?`function:${e.name||"anonymous"}`:typeof e=="symbol"?`symbol:${String(e)}`:typeof e=="bigint"?`bigint:${e.toString()}`:typeof e=="number"?Number.isFinite(e)?`number:${e}`:`number:${String(e)}`:`${typeof e}:${JSON.stringify(e)}`,rT=(e,t,r,n)=>`${YW}\0${GW(e)}\0${t?"ssml":"plain"}\0${bb(r??null)}\0${n}`,XW=(e={})=>{let t=Math.max(1,e.maxEntries??KW),r=e.resolve??((o,s)=>bw([o],s)),n=new Map,i=(o,s)=>{for(n.delete(o),n.set(o,s);n.size>t;){let a=n.keys().next().value;a!==void 0&&n.delete(a)}};return async(o,s)=>{let a=ku(s.mathSpeech),l=s.produceSsml===!0,c=rT(s.language,l,a,o.mathml),u=n.get(c);if(u)return n.delete(c),n.set(c,u),u;let d=await r(o,{...s,mathSpeech:a});return d.usedFallback?d:(l&&d.ssml&&t>1&&i(rT(s.language,!1,a,o.mathml),{speechText:d.speechText,usedMathSpeech:d.usedMathSpeech,usedFallback:d.usedFallback}),i(c,d),d)}},JW=(e,t)=>{let r=sg(t.word);if(e.id!==t.chunkId)return{chunkId:t.chunkId,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(t.providerOffsetSpace==="unknown"||e.offsetSpace==="unsupported")return{chunkId:e.id,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let n=Vq({tokenization:e.catalogAlignment?.speech??og({speechText:e.speechText}),position:t.position,length:t.length,boundaryWord:t.word});return n?{chunkId:e.id,normalizedWord:r,chunkSpokenStart:n.start,chunkSpokenEnd:n.start+n.length,confidence:n.confidence,reason:e.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}:{chunkId:e.id,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"}},Rc=e=>e.semanticTarget?{activeTarget:e.semanticTarget,regionTarget:e.regionTarget,quality:e.semanticTarget.quality==="exact-word"?"exact-word":e.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:e.confidence,reason:e.reason}:e.expressionTarget?{activeTarget:e.expressionTarget,regionTarget:e.regionTarget,quality:"expression",confidence:e.confidence,reason:e.reason}:{activeTarget:null,regionTarget:e.regionTarget,quality:"region",confidence:e.confidence,reason:e.reason},iA=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),wb="mi,mn,mo,mtext",oA="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",sA=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),aA=e=>e.type==="text-range"?e.node.parentElement:e.element,ag=e=>{let t=e;for(;t;){if(t.localName?.toLowerCase()==="mjx-container")return t;t=t.parentElement}return null},nT=e=>!e||ag(e)?!1:!ig(e),lA=e=>{let t=e.getBoundingClientRect?.();return!!(t&&t.width>0&&t.height>0)},Sb=e=>{let t=e;for(;t;){if(t.localName?.toLowerCase()==="math")return t;t=t.parentElement}return null},cA=(e,t)=>{if(e.length===0||e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=iA.get(e[r].localName.toLowerCase());if(!n||t[r].localName.toLowerCase()!==n)return!1}return!0},QW=(e,t)=>{if(!e||!iA.has(e.localName.toLowerCase())||t.querySelector(sA))return null;let r=Sb(e),n=t.querySelector("mjx-math");if(!r||!n)return null;let i=Array.from(r.querySelectorAll(wb)),o=i.indexOf(e);if(o<0)return null;let s=Array.from(n.querySelectorAll(oA));if(!cA(i,s))return null;let a=s[o];return!a||!lA(a)?null:a},ZW=e=>{let t=ag(e);if(t){if(t.querySelector(sA))return"expression";let n=Sb(e)??e,i=t.querySelector("mjx-math");if(!i)return"expression";let o=Array.from(n.querySelectorAll(wb)),s=Array.from(i.querySelectorAll(oA));return cA(o,s)&&s.some(a=>lA(a))?"token":"expression"}let r=Sb(e)??e;return Array.from(r.querySelectorAll(wb)).some(n=>!ig(n))?"token":"expression"},Ib=e=>{let t=aA(e),r=ag(t);if(r){let n=QW(t,r);return n?{type:"element",quality:"semantic-token",element:n}:{type:"element",quality:"expression",element:r}}return e.type==="text-range"?nT(e.node.parentElement)?{type:"text-range",quality:"semantic-token",node:e.node,startOffset:e.startOffset,endOffset:e.endOffset}:null:nT(e.element)?{type:"element",quality:e.quality==="region-fallback"?"expression":"semantic-token",element:e.element}:null},eV=Ib,tV=()=>{let e=new WeakMap;return t=>{let r=aA(t),n=ag(r);if(!r||!n)return Ib(t);if(e.has(r))return e.get(r)??null;let i=Ib(t);return e.set(r,i),i}},rV=(e,t,r,n=e.mathAlignments,i=eV)=>{if(t.chunkSpokenStart===null||t.chunkSpokenEnd===null)return null;let o=null;for(let s of n){let a=wW(s.alignment,{position:t.chunkSpokenStart,length:Math.max(1,t.chunkSpokenEnd-t.chunkSpokenStart),boundaryWord:r.word})||SW(s.alignment,{boundaryWord:r.word});if(!a)continue;let l=i(a);if(l){if(l.quality==="semantic-token")return l;o??(o=l)}}return o},xa=e=>e.node.getRootNode?.()??e.node,uA=(e,t)=>{try{let r=document.createRange();return r.setStart(e.node,e.offset),r.setEnd(t.node,t.offset+1),r}catch{return null}},dA=(e,t,r)=>{if(!e||typeof document>"u"||r<=t)return null;let n=e.get(t),i=e.get(Math.max(t,r-1));if(!n)return null;if(i||(i=n),xa(i)!==xa(n)){let o=xa(n);i=n;for(let s=t+1;s<r;s++){let a=e.get(s);a&&xa(a)===o&&(i=a)}}return uA(n,i)},Md=(e,t,r)=>{if(!e||typeof document>"u"||r<=t)return[];let n=e.get(t);if(!n)return[];let i=xa(n),o=!1;for(let u=t+1;u<r&&!o;u++){let d=e.get(u);d&&xa(d)!==i&&(o=!0)}if(!o){let u=dA(e,t,r);return u?[u]:[]}let s=[],a=null,l=null,c=()=>{if(a&&l){let u=uA(a,l);u&&s.push(u)}a=null,l=null};for(let u=t;u<r;u++){let d=e.get(u);d&&(a&&xa(a)!==xa(d)&&c(),a||(a=d),l=d)}return c(),s},nV=(e,t)=>{if(!e.catalogAlignment||t.chunkSpokenStart===null)return null;let r=Qq(e.catalogAlignment,t.chunkSpokenStart);if(!r)return null;let n=Md(e.visibleMap,r.start,r.end);return n.length===0?null:{type:"range",quality:e.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:n[0],ranges:n.length>1?n:void 0}},iV=e=>{let t=Md(e.visibleMap,0,e.visibleText.length);return t.length>1?t:void 0},oV=e=>e.regionRange?{type:"range",quality:"region",range:e.regionRange,ranges:iV(e)}:e.regionElement?{type:"element",quality:"region",element:e.regionElement}:null,iT=(e,t=e.chunk.mathAlignments)=>{if(t.length!==1)return null;let r=t[0]?.alignment.result.fallbackTarget;return r?e.renderedMathTargetResolver(r):null},sV=(e,t)=>e?t.mathAlignments.filter(({element:r})=>{try{return e.type==="range"?(e.ranges??[e.range]).some(n=>Vf(n,r)):e.type==="element"?Su(e.element,r):Su(Ps(e.node),r)}catch{return!1}}):t.mathAlignments,oT=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),sT=e=>e.length===1?e[0].element:null,aV=(e,t)=>t.length>0&&t.every(({element:r})=>e.mathCapabilityByElement.get(r)==="token"),fA=3,lV=(e,t,r)=>{if(!t||t.type!=="range")return!1;let{startContainer:n,endContainer:i}=t.range;return n===i&&n.nodeType===fA?!1:r.some(({element:o})=>e.mathCapabilityByElement.get(o)==="token"&&o.contains(n)&&o.contains(i))},hA=e=>e?.type==="range"&&ig(e.range.startContainer),cV=(e,t)=>{if(!hA(t))return null;let{startContainer:r,endContainer:n,startOffset:i,endOffset:o}=t.range;return r!==n||r.nodeType!==fA?null:e.renderedMathTargetResolver({type:"text-range",quality:"exact-word",node:r,startOffset:i,endOffset:o})},uV=(e,t)=>({chunk:e,regionTarget:oV(e),renderedMathTargetResolver:tV(),mathCapabilityByElement:new Map(e.mathAlignments.map(({element:r})=>[r,t?ZW(r):"expression"])),heldTokenByElement:new Map}),dV=e=>{let t=e.mathTokenHighlighting!==!1,r=new Map(e.chunks.map(n=>[n.id,uV(n,t)]));return{chunks:e.chunks,resolveInitial(n){let i=r.get(n);if(!i)return oT();let o=i.chunk.mathAlignments,s=o.length===1?o[0].element:null,a=s?i.mathCapabilityByElement.get(s):null;return Rc(a==="expression"?{semanticTarget:null,expressionTarget:iT(i),regionTarget:i.regionTarget,confidence:.5,reason:"initial expression (sticky expression mode)"}:{semanticTarget:null,expressionTarget:null,regionTarget:i.regionTarget,confidence:0,reason:a==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(n){let i=r.get(n.chunkId);if(!i)return oT();let{chunk:o}=i,s=JW(o,n),a=nV(o,s),l=sV(a,o),c=(!a||l.length>0?rV(o,s,n,l,i.renderedMathTargetResolver):null)||null,u=c?.quality==="semantic-token"?c:cV(i,a)??c,d=t&&u&&u.quality!=="expression"?u:null,f=u&&u.quality==="expression"?u:null;if(d){let h=sT(l);return h&&i.heldTokenByElement.set(h,d),Rc({semanticTarget:d,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason})}if(a&&!hA(a)&&(t?!lV(i,a,l):l.length===0))return Rc({semanticTarget:a,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason});if(aV(i,l)){let h=sT(l),g=h?i.heldTokenByElement.get(h)??null:null;return Rc({semanticTarget:g,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:g?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return Rc({semanticTarget:null,expressionTarget:f??iT(i,l),regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason})}}},fV=e=>e.alignment?.speech.boundaryOffsetSpace??e.mathAlignment?.speech.boundaryOffsetSpace??"plain-spoken-text",hV=e=>e.mathAlignments?.length?e.mathAlignments:e.mathAlignment&&e.sourceElement?[{element:e.sourceElement,alignment:e.mathAlignment}]:[],pV=e=>(e.chunks&&e.chunks.length?e.chunks:[{speechText:e.speechText||"",visibleText:e.visibleText||e.speechText||"",sourceElement:e.sourceElement||e.contentRoot,regionElement:e.regionElement||e.sourceElement||e.contentRoot,regionRange:e.regionRange,visibleMap:e.visibleMap}]).map((t,r)=>({id:`tts-chunk-${r}`,speechText:t.speechText,visibleText:t.visibleText,sourceElement:t.sourceElement,contentRoot:e.contentRoot,regionElement:t.regionElement??t.sourceElement,regionRange:t.regionRange,visibleMap:t.visibleMap,catalogAlignment:t.alignment,mathAlignments:hV(t),offsetSpace:fV(t)})),mV=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),pA=(e,t)=>{let r=$_(e,mV);return r&&Su(t,r)?r:e},lg=(e,t)=>{let r=t?.useSentenceSegmenter!==!1;try{if(!r)throw Error("Segmenter disabled by policy");let s=globalThis.Intl?.Segmenter;if(typeof s=="function"){let a=new s(t?.locale,{granularity:"sentence"}),l=Array.from(a.segment(e)).map(c=>({text:c.segment,offset:c.index})).filter(c=>c.text.trim().length>0);if(l.length>0)return l}}catch{}let n=e.match(/[^.!?]+(?:[.!?]+|$)/g)||[e],i=[],o=0;for(let s of n){let a=e.indexOf(s,o);a!==-1&&(i.push({text:s,offset:a}),o=a+s.length)}return i.length>0?i:[{text:e,offset:0}]},aT=(e,t,r)=>{let n=Math.max(1,Math.floor(t)),i=[],o=-1,s=-1,a=()=>{o>=0&&i.push({text:e.slice(o,s),offset:o}),o=-1},l=(c,u)=>{if(o>=0&&u-o<=n){s=u;return}a();let d=c;for(;u-d>n;){let f=e.slice(d,d+n+1).search(/\s\S*$/),h=f>0?d+f:d+n;for(i.push({text:e.slice(d,h).trimEnd(),offset:d}),d=h;d<u&&/\s/.test(e[d]);)d++}d<u&&(o=d,s=u)};for(let c of lg(e,r)){let u=c.text.search(/\S/);u!==-1&&l(c.offset+u,c.offset+c.text.trimEnd().length)}return a(),i},gV=(e,t)=>bw([e],t),vV=e=>(e||"en").split("-")[0].toLowerCase()||"en",yV=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),bV=new Set(["heading","listitem","option","radio"]),wV=e=>{if(e.type!=="text"||!e.sourceElement)return!1;let t=e.sourceElement.tagName.toUpperCase(),r=(e.sourceElement.getAttribute("role")||"").toLowerCase();return yV.has(t)||bV.has(r)},SV=async e=>{let t=e.resolveMathSpeech??gV,r=rA(e.mathSpeech),{visibleText:n}=e,i=[],o=0,s=l=>{let c=ln(l),u=n.indexOf(c,o),d=u>=0?u:o,f=d+c.length;return o=f,{start:d,end:f}},a=[];for(let l=0;l<e.chunks.length;l++){let c=e.chunks[l];if(c.type==="text"){let g=wV(c)?[{text:c.text,offset:0}]:lg(c.text,{locale:e.language});for(let m of g){let v=ln(m.text);if(!v)continue;let b=s(v);i.push({sourceChunkIndex:l,segment:{kind:"prose",spokenText:v,visibleText:v,visibleSpan:b}}),a.push(v)}continue}let u=s(c.fallbackText),d=await t(c,{language:e.language,produceSsml:e.produceSsml,mathSpeech:e.mathSpeech,loadSre:r}),f=!d.speechText,h=d.speechText||c.fallbackText;i.push({sourceChunkIndex:l,segment:{kind:"math",spokenText:h,mathml:c.mathml,fallbackText:c.fallbackText,visibleSpan:u,usedFallback:f,ssml:d.ssml}}),a.push(h)}return{segments:i,locale:vV(e.language),visibleText:n,plainSpeechText:ln(a.join(" "))}},IV=(e,t,r)=>{let n=new Map;for(let i=t;i<r;i++){let o=e.get(i);o&&n.set(i-t,o)}return n},kV=async e=>{let t=qc(e.contentRoot,e.textProcessingOptions,e.range),r=await SV({chunks:t.chunks,visibleText:t.visibleText,language:e.language,mathSpeech:e.mathSpeech,produceSsml:e.produceSsml,resolveMathSpeech:e.resolveMathSpeech});return{plan:{items:r.segments.map(({segment:n,sourceChunkIndex:i})=>{let o=t.chunks[i];if(n.kind==="prose"){let a=o?.type==="text"?o.sourceElement??e.contentRoot:e.contentRoot;return{segment:n,anchor:{sourceElement:a,regionElement:pA(a,e.contentRoot),visibleMap:IV(t.map,n.visibleSpan.start,n.visibleSpan.end)}}}let s=o?.type==="math"?o.sourceElement??null:null;return{segment:n,anchor:{sourceElement:s,regionElement:s}}}),locale:r.locale,visibleText:r.visibleText,plainSpeechText:r.plainSpeechText},containsMathMarkup:t.containsMathMarkup,visibleText:t.visibleText}},TV=(e,t)=>{let r=V_({speechText:e.spokenText,visibleText:e.spokenText});return{speechText:e.spokenText,visibleText:e.visibleText,sourceElement:t.sourceElement,regionElement:t.regionElement,regionRange:dA(t.visibleMap,0,e.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:r.playbackMode,alignment:r,visibleMap:t.visibleMap}},mA=(e,t)=>{let r=t.sourceElement;return{speechText:e.spokenText,visibleText:e.fallbackText,sourceElement:r,regionElement:t.regionElement,speechMatchesVisibleText:e.spokenText===e.fallbackText,mathAlignment:r?gm({mathElement:r,speechText:e.spokenText}):void 0}},EV=(e,t,r)=>{let n=t.sourceElement;return{speechText:r,visibleText:e.fallbackText,sourceElement:n,regionElement:t.regionElement,speechMatchesVisibleText:!1,mathAlignment:n?gm({mathElement:n,speechText:r}):void 0,plainFallback:mA(e,t)}},CV=(e,t={})=>e.items.map(({segment:r,anchor:n})=>r.kind==="prose"?TV(r,n):t.format==="ssml"&&r.ssml?EV(r,n,r.ssml):mA(r,n));function Cv(e){let t=e instanceof Error?e:Error(String(e));return t.code="tts-start-failed",t}var xV="pie-tts-control-handoff",cs=ei("tts-service",xu),Tt;(function(e){e.IDLE="idle",e.LOADING="loading",e.PLAYING="playing",e.PAUSED="paused",e.ERROR="error"})(Tt||(Tt={}));var Cl=e=>typeof e=="string"&&e.trim()?e.trim():void 0,lT=(e,t={})=>e?{locale:"locale"in e?Cl(e.locale):t.locale,textNormalization:e.textNormalization&&"locale"in e.textNormalization?Cl(e.textNormalization.locale):t.textNormalization,segmenter:e.segmenter&&"locale"in e.segmenter?Cl(e.segmenter.locale):t.segmenter}:t,cT=e=>"commonAncestorContainer"in e,gA=(e,t)=>e===t||e.startContainer===t.startContainer&&e.startOffset===t.startOffset&&e.endContainer===t.endContainer&&e.endOffset===t.endOffset,RV=(e,t)=>e===t?!0:!e||!t||e.type!==t.type||e.quality!==t.quality?!1:e.type==="range"&&t.type==="range"?gA(e.range,t.range):e.type==="element"&&t.type==="element"?e.element===t.element:e.type==="text-range"&&t.type==="text-range"?e.node===t.node&&e.startOffset===t.startOffset&&e.endOffset===t.endOffset:!1,PV=class{constructor(){T(this,"currentProvider",null),T(this,"provider",null),T(this,"highlightCoordinator",null),T(this,"highlightTargetResolverProvider",null),T(this,"catalogResolver",null),T(this,"state",Tt.IDLE),T(this,"resumeState",Tt.PLAYING),T(this,"ttsConfig",{}),T(this,"hostLocales",{}),T(this,"readLocale",pb),T(this,"disposed",!1),T(this,"readinessGate",null),T(this,"mathSpeechSource",null),T(this,"currentText",null),T(this,"currentContentElement",null),T(this,"normalizedToDOM",new Map),T(this,"listeners",new Set),T(this,"lastError",null),T(this,"speakRunId",0),T(this,"currentBoundaryOffset",0),T(this,"activeWordBoundaryOffset",0),T(this,"seekSegments",[]),T(this,"playbackChunks",[]),T(this,"activeRecordedAudio",null),T(this,"sentenceHighlightSegments",[]),T(this,"activeSentenceStartOffset",null),T(this,"playbackStartDeferredRunId",null),T(this,"pendingPlaybackStartHighlights",[]),T(this,"playbackStartBarrierCleanup",null),T(this,"pauseHold",null),T(this,"structuralPause",null),T(this,"playbackRateWriteQueue",Promise.resolve()),T(this,"playbackRateRequestId",0),T(this,"pendingPlaybackRateRequest",null),T(this,"activePlaybackRate",null),T(this,"activeHighlightMode","word"),T(this,"lastRenderedRegionTarget",null),T(this,"telemetryReporter",null),T(this,"generatedMathSpeechResolver",XW())}clearPlaybackStartBarrier(e=this.playbackStartBarrierCleanup){e?.(),this.playbackStartBarrierCleanup===e&&(this.playbackStartBarrierCleanup=null)}notifyPlaybackStarted(e){if(this.playbackStartDeferredRunId!==e||e!==this.speakRunId)return;this.state===Tt.PAUSED&&(this.activeRecordedAudio?.element.pause(),this.provider?.pause()),this.markPlaying();let t=this.pendingPlaybackStartHighlights.splice(0);for(let r of t)r()}installPlaybackStartBarrier(e,t=!1){this.clearPlaybackStartBarrier();let r=this.provider,n=r&&"onPlaybackStart"in r?r:null;if(!n&&!t)return null;let i=n?.onPlaybackStart,o=()=>{try{this.notifyPlaybackStarted(e)}finally{i?.()}};n&&(n.onPlaybackStart=o),this.playbackStartDeferredRunId=e;let s=()=>{n?.onPlaybackStart===o&&(n.onPlaybackStart=i),this.playbackStartDeferredRunId===e&&(this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[])};return this.playbackStartBarrierCleanup=s,s}runWhenPlaybackStarts(e,t){if(this.playbackStartDeferredRunId===e){this.pendingPlaybackStartHighlights.push(t);return}t()}async waitWhilePaused(e){for(;this.state===Tt.PAUSED&&e===this.speakRunId;){if(!this.pauseHold){let t=()=>{},r=new Promise(n=>{t=n});this.pauseHold={promise:r,release:t}}await this.pauseHold.promise}}releasePauseHold(){let e=this.pauseHold;this.pauseHold=null,e?.release()}waitStructuralPause(e){return this.cancelStructuralPause(),new Promise(t=>{let r=()=>{this.structuralPause?.finish===r&&(clearTimeout(this.structuralPause.timer),this.structuralPause=null),t()};this.structuralPause={timer:setTimeout(r,e),finish:r}})}cancelStructuralPause(){this.structuralPause?.finish()}abandonRun(){this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.cancelStructuralPause(),this.releasePauseHold()}beginRun(){let e=this.state===Tt.LOADING||this.state===Tt.PLAYING||this.state===Tt.PAUSED,t=++this.speakRunId;return this.abandonRun(),e&&this.provider?.stop(),this.setState(Tt.LOADING),t}markPlaying(){if(this.state===Tt.PAUSED){this.resumeState=Tt.PLAYING;return}this.setState(Tt.PLAYING)}assertNotDisposed(){if(this.disposed)throw Cv(Error("TTS service disposed"))}async emitTelemetry(e,t){try{await this.telemetryReporter?.(e,t)}catch(r){console.warn("[TTSService] telemetry callback failed:",r)}}async initialize(e,t={}){if(this.disposed)throw Error("TTS service disposed");this.currentProvider=e,this.ttsConfig={...t},this.hostLocales=lT(t.providerOptions);let r=this.providerOptions().__pieTelemetry;this.telemetryReporter=typeof r=="function"?r:null,this.provider=await e.initialize(t)}async updateSettings(e){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let t={...e,...e.providerOptions?{providerOptions:{...this.providerOptions(),...e.providerOptions}}:{}};await this.provider.updateSettings(t),this.ttsConfig={...this.ttsConfig,...t},this.hostLocales=lT(e.providerOptions,this.hostLocales)}setHighlightCoordinator(e){this.highlightCoordinator=e}setReadinessGate(e){this.readinessGate=e}setMathSpeechSource(e){this.mathSpeechSource=e}pendingReadiness(){return this.provider||!this.readinessGate?null:this.readinessGate().catch(e=>{throw Cv(e)})}setHighlightTargetResolverProvider(e){return this.highlightTargetResolverProvider=e,()=>{this.highlightTargetResolverProvider===e&&(this.highlightTargetResolverProvider=null)}}setCatalogResolver(e){this.catalogResolver=e}getHighlightResolverRuntime(){let e=null;try{e=this.highlightTargetResolverProvider?.()??null}catch{e=null}let t=e?.context??{},r=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...t,scopeElement:t.scopeElement??r},resolver:e?.resolver??null}}getNodeElement(e){return e?e.nodeType===Node.ELEMENT_NODE?e:Ps(e):null}isElementWithinScope(e,t){return t?Su(t,e):!0}isRangeWithinScope(e,t){let r=this.getNodeElement(e.startContainer),n=this.getNodeElement(e.endContainer);return!r||!n?!1:this.isElementWithinScope(r,t)&&this.isElementWithinScope(n,t)}resolveWordHighlightRange(e){let{context:t,resolver:r}=this.getHighlightResolverRuntime(),n=t.scopeElement??this.currentContentElement;try{let i=r?.resolveWordRange?.(e,t);if(i&&this.isRangeWithinScope(i,n))return{range:i,remapped:!gA(e,i)}}catch{}return{range:e,remapped:!1}}resolveSentenceHighlightTargets(e){let{context:t,resolver:r}=this.getHighlightResolverRuntime(),n=t.scopeElement??this.currentContentElement;try{let i=r?.resolveSentenceRanges?.(e,t);if(!i)return{ranges:e,elements:[]};let o=[],s=[];for(let a of i){if(typeof Range<"u"&&a instanceof Range){if(!this.isRangeWithinScope(a,n))return{ranges:e,elements:[]};o.push(a);continue}if(typeof Element<"u"&&a instanceof Element){if(!this.isElementWithinScope(a,n))return{ranges:e,elements:[]};s.push(a);continue}return{ranges:e,elements:[]}}return{ranges:o,elements:s}}catch{return{ranges:e,elements:[]}}}createTextRange(e,t,r){if(typeof document>"u"||typeof document.createRange!="function")return null;try{let n=document.createRange();return n.setStart(e,t),n.setEnd(e,r),n.startContainer!==e||n.endContainer!==e?null:n}catch{return null}}paintTTSWord(e){!this.highlightCoordinator||e.length===0||this.highlightCoordinator.highlightTTSWord(e.map(t=>this.resolveWordHighlightRange(t).range))}paintTTSSentenceRanges(e){if(!this.highlightCoordinator)return;let{ranges:t,elements:r}=this.resolveSentenceHighlightTargets(e);if(r.length>0&&t.length===0){this.highlightCoordinator.highlightTTSSentenceElements(r);return}let n=[...t];for(let i of r){let o=document.createRange();o.selectNodeContents(i),n.push(o)}this.highlightCoordinator.highlightTTSSentence(n)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}providerOptions(){let e=this.ttsConfig.providerOptions;return e&&typeof e=="object"?e:{}}maxTextLength(){let e=this.currentProvider?.getCapabilities?.().maxTextLength;return typeof e=="number"&&e>0?e:void 0}async speakWithinLimit(e,t){let r=this.provider;if(!r)return;let n=this.maxTextLength();if(!n||e.length<=n){if(await this.waitWhilePaused(t),t!==this.speakRunId||this.provider!==r)return;await r.speak(e);return}if(H_(e))throw Error(`[tts] SSML of ${e.length} characters exceeds the provider's limit of ${n}`);let i=r.onWordBoundary;try{for(let o of aT(e,n,{locale:this.readLocale})){if(await this.waitWhilePaused(t),t!==this.speakRunId||this.provider!==r)return;r.onWordBoundary=i?(s,a,l)=>i(s,a+o.offset,l):void 0,await r.speak(o.text)}}finally{this.provider===r&&t===this.speakRunId&&(r.onWordBoundary=i)}}segmentsWithinLimit(e){let t=this.maxTextLength();return t?e.flatMap(r=>{if(r.text.length<=t)return[r];let n=aT(r.text,t,{locale:this.readLocale});return n.map((i,o)=>({text:i.text,startOffset:r.startOffset+i.offset,pauseMsAfter:o===n.length-1?r.pauseMsAfter:void 0}))}):e}getTextProcessingOptions(e){let t=this.providerOptions().textNormalization?.boundarySpacingMode;return{locale:e,boundarySpacingMode:t==="none"||t==="alnum"||t==="segmenterPreferred"?t:void 0}}resolveReadLanguage(e,t){let r=D_(e,{contentLanguage:t})??Cl(this.providerOptions().lang_id);return{contentLanguage:r,locale:r??this.hostLocales.locale??this.hostLocales.textNormalization??pb}}getMathSpeechOptions(){return this.mathSpeechSource?ku(this.mathSpeechSource()):ku(this.providerOptions().mathSpeech)}buildPositionMap(e,t,r){this.normalizedToDOM.clear();let{text:n,map:i}=$d(e,this.getTextProcessingOptions(r));this.normalizedToDOM=i,xu()&&(cs.debug("Text comparison:",{spokenLength:t.length,normalizedDomLength:n.length,match:t===n,spokenPreview:t.substring(0,150),normalizedPreview:n.substring(0,150),differAtIndex:t===n?null:(()=>{for(let o=0;o<Math.min(t.length,n.length);o++)if(t[o]!==n[o])return{index:o,spokenChar:t[o],normalizedChar:n[o],spokenContext:t.substring(Math.max(0,o-20),o+20),normalizedContext:n.substring(Math.max(0,o-20),o+20)};return null})()}),cs.debug("Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:t.length,normalizedDomLength:n.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===t.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([o,{node:s,offset:a}])=>({pos:o,offset:a,char:s.textContent?.[a],expected:t[o]}))}))}getStructuralPauseProfile(){let e=this.providerOptions().structuralPauses||{},t=e.units||{},r=(n,i)=>{if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()){let o=Number(n);return Number.isFinite(o)?o:i}return i};return{baseMs:r(e.baseMs,280),units:{minor:r(t.minor,.65),section:r(t.section,1),major:r(t.major,1.35)},minMs:r(e.minMs,120),maxMs:r(e.maxMs,900)}}resolvePauseMsFromUnits(e){let t=this.getStructuralPauseProfile(),r=Math.max(.25,Math.min(4,Number(this.ttsConfig.rate||1))),n=t.baseMs*Math.max(0,e)/r;return Math.max(t.minMs,Math.min(t.maxMs,Math.round(n)))}resolveHighlightMode(){let e=this.providerOptions().highlightMode;if(e==="word"||e==="sentence")return e;let t=this.currentProvider?.getCapabilities();return t?.defaultHighlightMode?t.defaultHighlightMode:t?.supportsWordBoundary?"word":"sentence"}hasExplicitBreakSemantics(e){return e.includes("<")?/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(e):!1}isElementHidden(e){return j_(e)}getBoundaryStrength(e){let t=Number(e.getAttribute("data-tts-break-ms"));if(Number.isFinite(t)&&t>0)return"major";let r=e.tagName.toUpperCase();if(r.match(/^H[1-6]$/))return"major";let n=(e.getAttribute("role")||"").toLowerCase();if(n==="heading")return"major";if(n==="listitem"||n==="row"||n==="option"||n==="radio"||r==="LI")return"section";if(typeof window<"u"){let i=window.getComputedStyle(e).display;if(i==="block"||i==="list-item"||i.startsWith("table")||i==="flex"||i==="grid")return"minor"}return"minor"}getBoundaryAnchor(e,t){let r=ho(e),n=null;for(;r&&r!==t;){if(this.isElementHidden(r))return null;let o=Number(r.getAttribute("data-tts-break-ms"));if(Number.isFinite(o)&&o>0)return{anchor:r,units:o/this.getStructuralPauseProfile().baseMs};let s=(r.getAttribute("role")||"").toLowerCase(),a=r.tagName.toUpperCase();if(a.match(/^H[1-6]$/)||s==="heading"||s==="listitem"||a==="LI"){n=r;break}if(!n&&typeof window<"u"){let l=window.getComputedStyle(r).display;(l==="block"||l==="list-item"||l.startsWith("table")||l==="flex"||l==="grid")&&(n=r)}r=ho(r)}if(!n)return null;let i=this.getBoundaryStrength(n);return{anchor:n,units:this.getStructuralPauseProfile().units[i]}}createSpeechPlan(e,t,r,n){let i=this.collectSpeechPlanBoundaries(e,t,n);if(r===0)return this.createSpeechPlanSegments(t,i);let o=new Map;for(let[s,a]of i)o.set(s-r,a);return this.createSpeechPlanSegments(t,o)}collectSpeechPlanBoundaries(e,t,r){let n=new Map,{map:i}=$d(e,this.getTextProcessingOptions(r)),o=this.createNodeStartOffsets(i),s=null;for(let a of Wf(e)){let l=ho(a);if(l&&!this.isElementHidden(l)&&!mb(a)){let c=this.getBoundaryAnchor(a,e),u=o.get(a);c&&u!==void 0&&c.anchor!==s&&u>0&&(n.set(u,Math.max(n.get(u)||0,c.units)),s=c.anchor)}}return n}createNodeStartOffsets(e){let t=new Map;for(let[r,n]of e.entries())t.has(n.node)||t.set(n.node,r);return t}createSpeechPlanSegments(e,t){let r=Array.from(t.keys()).filter(a=>a>0&&a<e.length).sort((a,l)=>a-l),n=[],i=0;for(let a of r){let l=e.substring(i,a),c=l.match(/^\s*/)?.[0].length||0,u=l.match(/\s*$/)?.[0].length||0,d=i+c,f=a-u;if(f>d){let h=e.substring(d,f);n.push({text:h,startOffset:d,pauseMsAfter:this.resolvePauseMsFromUnits(t.get(a)||0)})}i=a}let o=e.substring(i).match(/^\s*/)?.[0].length||0,s=i+o;return s<e.length&&n.push({text:e.substring(s).trimEnd(),startOffset:s,pauseMsAfter:0}),n.filter(a=>a.text.trim().length>0)}segmentSentences(e){return lg(e,{locale:this.readLocale})}createSeekSegmentsFromText(e){return this.segmentSentences(e).map(t=>{let r=t.text.match(/^\s*/)?.[0].length||0;return{text:t.text.trim(),startOffset:t.offset+r,pauseMsAfter:0}}).filter(t=>t.text.length>0)}splitSegmentsAtBoundaries(e,t,r){if(e.length===0||t.length===0)return e;let n=Array.from(new Set(t)).filter(o=>Number.isFinite(o)&&o>0).sort((o,s)=>o-s);if(n.length===0)return e;let i=[];for(let o of e){let s=o.startOffset,a=o.startOffset+o.text.length,l=n.filter(u=>u>s&&u<a);if(l.length===0){i.push(o);continue}let c=s;for(let u of[...l,a]){let d=r.substring(c,u),f=d.match(/^\s*/)?.[0].length||0,h=d.match(/\s*$/)?.[0].length||0,g=c+f,m=u-h;m>g&&i.push({text:r.substring(g,m),startOffset:g,pauseMsAfter:0}),c=u}}return i}createSentenceHighlightSegments(e){let t=this.createSeekSegmentsFromText(e.contentToSpeak);if(!e.shouldUsePlan||e.playbackSegments.length===0)return t;let r=e.playbackSegments.map(n=>n.startOffset).filter(n=>n>0);return this.splitSegmentsAtBoundaries(t,r,e.contentToSpeak)}createSeekSegmentsFromSpeechChunks(e){let t=0;return e.map(r=>{let n=ln(r.plainFallback?.speechText||(this.hasExplicitBreakSemantics(r.speechText)?r.visibleText:r.speechText)||r.visibleText)||r.visibleText||"",i={text:n,startOffset:t,pauseMsAfter:0};return t+=Math.max(1,n.length+1),i})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let e=0;for(let t=0;t<this.seekSegments.length&&this.seekSegments[t].startOffset<=this.currentBoundaryOffset;t++)e=t;return e}async speakWithPlan(e,t,r){if(!this.provider||e.length===0)return;let n=r?.highlightMode==="sentence",i=this.provider;if(!n&&typeof i.speakSegments=="function"){if(await this.waitWhilePaused(t),t!==this.speakRunId||this.provider!==i)return;this.currentBoundaryOffset=0;let o=this.provider.onWordBoundary;this.provider.onWordBoundary=(s,a,l)=>{o?.(s,a,l),Number.isFinite(a)&&(this.currentBoundaryOffset=a)};try{await i.speakSegments(this.segmentsWithinLimit(e))}finally{t===this.speakRunId&&this.provider===i&&(this.provider.onWordBoundary=o)}return}this.configureWordBoundaryHighlighting({highlightMode:r?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let o of e){if(await this.waitWhilePaused(t),t!==this.speakRunId)return;this.currentBoundaryOffset=o.startOffset,n&&this.runWhenPlaybackStarts(t,()=>{this.highlightSentenceSegment(o.startOffset,o.text)}),await this.speakWithinLimit(o.text,t);let s=o.pauseMsAfter??0;s>0&&t===this.speakRunId&&await this.waitStructuralPause(s)}}highlightSentenceSegment(e,t){if(!this.highlightCoordinator||typeof document>"u")return;let r=t.trimEnd().length;if(r<=0)return;let n=e+this.activeWordBoundaryOffset,i=this.normalizedToDOM.get(n),o=this.normalizedToDOM.get(n+r-1);if(!i||!o)return;let s=Md(this.normalizedToDOM,n,n+r);s.length!==0&&(this.paintTTSSentenceRanges(s),this.activeSentenceStartOffset=e)}getSegmentIndexForOffset(e,t){if(e.length===0)return-1;let r=-1;for(let n=0;n<e.length&&e[n].startOffset<=t;n++)r=n;return r}highlightSentenceForOffset(e){let t=this.sentenceHighlightSegments;if(!this.highlightCoordinator||t.length===0)return;let r=this.getSegmentIndexForOffset(t,e);if(r<0)return;let n=t[r];n&&this.activeSentenceStartOffset!==n.startOffset&&this.highlightSentenceSegment(n.startOffset,n.text)}async speak(e,t={}){this.assertNotDisposed();let r=this.pendingReadiness(),n=r?this.beginRun():null;if(r){try{await r}catch(s){throw n===this.speakRunId&&this.setState(Tt.IDLE),s}if(this.assertNotDisposed(),n!==this.speakRunId)return}if(!this.provider)throw n!==null&&this.setState(Tt.IDLE),Cv(Error("TTS service not initialized"));let i=this.resolveReadLanguage(cT(e)?e.startContainer:e,t.language),o=cT(e)?this.resolveRangeTarget(e,t,i):this.resolveElementTarget(e,t,i);if(!o){n!==null&&this.setState(Tt.IDLE);return}await this.speakContent(o.text,o.options,n??this.beginRun())}isSuppressedTarget(e){return mb(e)?(console.warn("[tts] the content to read lies inside content marked not-to-be-spoken; nothing was spoken."),!0):!1}resolveElementTarget(e,t,r){if(this.isSuppressedTarget(e))return null;let n=qc(e,this.getTextProcessingOptions(r.locale)).visibleText.trim();return n?{text:n,options:{catalogId:t.catalogId,catalogContext:t.catalogContext,language:r.locale,contentLanguage:r.contentLanguage,contentElement:e}}:(console.warn("[tts] the content to read holds no speakable text; nothing was spoken."),null)}resolveRangeTarget(e,t,r){if(this.isSuppressedTarget(e.commonAncestorContainer))return null;let n=e.commonAncestorContainer,i=t.contentRoot||(n.nodeType===Node.ELEMENT_NODE?n:Ps(n));if(!i)return null;let o=Yk(e,i),s=o.text.trim();if(!s)return o.filtered&&console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken."),null;let a=this.selectMappedRangeText(e,i,r.locale),l=s,c=a?.offset??0;if(a)l=a.text;else{let u=document.createRange();u.selectNodeContents(i),u.setEnd(e.startContainer,e.startOffset);let d=Yk(u,i).text,f=ln(d);c=f.length+(/\s$/.test(d)&&f?1:0)}return cs.debug("selection offset calculation:",{selectedText:l,mapped:!!a,offset:c,rootTag:i.tagName}),{text:l,options:{catalogId:t.catalogId&&gb(e,i,i)?t.catalogId:void 0,catalogContext:t.catalogContext,language:r.locale,contentLanguage:r.contentLanguage,contentElement:i,contentRange:e,wordBoundaryOffset:c}}}async speakContent(e,t,r){let n=null;try{if(await this.applyLanguageSettings(t),r!==this.speakRunId)return;let i=await this.resolveSpeechContent(e,t);if(r!==this.speakRunId)return;let{contentToSpeak:o,speechText:s,highlightText:a,normalizedText:l,usedCatalogSpoken:c,speechSource:u,speechMatchesVisibleText:d,speechChunks:f}=i;this.logResolvedSpeechContent({contentToSpeak:o,speechSource:u,catalogId:t?.catalogId}),this.initializeSpeakTracking(a,t);let h=d?this.resolveHighlightMode():"sentence";this.activeHighlightMode=h,this.activeWordBoundaryOffset=t?.wordBoundaryOffset||0;let g=this.hasExplicitBreakSemantics(o),m=!!this.currentContentElement&&!c&&!g&&d;if(this.playbackChunks=f?.length?f:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):g||!d?[]:m&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,l,t?.wordBoundaryOffset||0,t?.language):this.createSeekSegmentsFromText(a),this.sentenceHighlightSegments=g?[]:this.createSentenceHighlightSegments({contentToSpeak:a,shouldUsePlan:m,playbackSegments:this.seekSegments}),n=this.installPlaybackStartBarrier(r,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:a,options:t,highlightMode:h,shouldUsePlan:m,runId:r}),d?this.configureWordBoundaryHighlighting({highlightMode:h,wordBoundaryOffset:t?.wordBoundaryOffset||0}):this.clearWordBoundaryHighlighting(),n||this.markPlaying(),this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:m,runId:r,highlightMode:h,contentToSpeak:s,speechChunks:f}),r!==this.speakRunId)return;this.setState(Tt.IDLE),this.clearHighlightsAndTracking()}catch(i){if(r!==this.speakRunId)return;throw console.error("TTS error:",i),this.lastError=i instanceof Error?i.message:String(i),this.setState(Tt.ERROR),this.clearHighlightsAndTracking(),i}finally{this.clearPlaybackStartBarrier(n)}}async applyLanguageSettings(e){if(!this.provider)return;this.readLocale=e.language;let t=e.contentLanguage,r=this.providerOptions(),n={locale:t??this.hostLocales.locale,textNormalization:t??this.hostLocales.textNormalization,segmenter:t??this.hostLocales.segmenter};if(r.contentLanguage===t&&Cl(r.locale)===n.locale&&Cl(r.textNormalization?.locale)===n.textNormalization&&Cl(r.segmenter?.locale)===n.segmenter)return;let i={...r,locale:n.locale,textNormalization:{...r.textNormalization,locale:n.textNormalization},segmenter:{...r.segmenter,locale:n.segmenter},contentLanguage:t};this.ttsConfig={...this.ttsConfig,providerOptions:i},await this.provider.updateSettings({providerOptions:i})}async resolveSpeechContent(e,t){let r=ln(e);if(t.catalogId&&this.catalogResolver){let i=this.catalogResolver.getAlternative(t.catalogId,{type:"spoken",language:t.language,useFallback:!0,context:t.catalogContext,form:"content"}),o=i?.content;if(i&&o!==void 0){let s=qc(t.contentElement,this.getTextProcessingOptions(t.language)).visibleText||r,a=ln(o);return cs.debug(`Using catalog content for "${t.catalogId}" (${i.language})`),{contentToSpeak:o,speechText:o,visibleText:s,highlightText:s,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:s,containsMathMarkup:!1,speechMatchesVisibleText:a===s}}cs.debug(`No catalog found for "${t.catalogId}", falling back to generated TTS`)}let n=this.resolveCatalogComposedSpeechContent(t.contentElement,r,t);return n||{...await this.resolveGeneratedSpeechContent(t.contentElement,r,t.language,t.contentRange),usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(e,t,r){if(!this.catalogResolver)return null;let n=this.collectCatalogSpeechChunks(e,r);if(!n.some(s=>s.sourceElement))return null;let i=ln(n.map(s=>s.speechText).join(" ")),o=r.contentRange?t:qc(e,this.getTextProcessingOptions(r.language)).visibleText||t;return{contentToSpeak:i,speechText:i,visibleText:o,highlightText:o,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:o,containsMathMarkup:!1,speechMatchesVisibleText:n.every(s=>s.speechMatchesVisibleText),speechChunks:n}}collectCatalogSpeechChunks(e,t){let r=[],n="",i=()=>{let u=ln(n);n="",u&&r.push({speechText:u,visibleText:u,sourceElement:null,speechMatchesVisibleText:!0})},o=t.contentRange,s=u=>{let d=u.getAttribute("data-catalog-idref");if(!d||o&&!gb(o,u,e))return null;let f={type:"spoken",language:N_(u,e)||t.language,useFallback:!0,context:t.catalogContext},h=this.catalogResolver.getAlternative(d,{...f,form:"payload"}),g=h?.payload?Rq({payload:h.payload})??void 0:void 0,m=this.catalogResolver.getAlternative(d,{...f,form:"content"})?.content;return g===void 0&&m===void 0?null:{script:m,audio:g}},a=(u,d)=>{let f=l(u);if(f.length!==1)return null;let h=f[0],g=qc(h,this.getTextProcessingOptions(t.language)).visibleText||ln(h.textContent||""),m=v=>ln(v).replace(/\s+/g,"");return m(g)===m(d)?h:null},l=u=>{let d=Eq(u,"math");return u.localName?.toLowerCase()==="math"?[u,...d]:d},c=u=>{if(zu(u,e))return;if(u.nodeType===Node.TEXT_NODE){o?Vf(o,u)&&(n+=` ${B_(u,o)}`):n+=` ${u.textContent||""}`;return}if(u.nodeType!==Node.ELEMENT_NODE)return;let d=u,f=s(d);if(f){i();let h=qc(d,this.getTextProcessingOptions(t.language)),g=h.visibleText||ln(Tq(d)),m=pA(d,e),v=f.script!==void 0?(()=>{let b=f.script,I=V_({speechText:b,visibleText:g}),C=a(d,g),x=C?gm({mathElement:C,speechText:b}):void 0,$=x?void 0:l(d).map(P=>({element:P,alignment:gm({mathElement:P,speechText:b})}));return{speechText:b,visibleText:g,sourceElement:d,regionElement:m,speechMatchesVisibleText:ln(b)===g,playbackMode:I.playbackMode,alignment:I,mathAlignment:x,mathAlignments:$,visibleMap:h.map}})():null;if(f.audio){r.push(v?{...v,audio:f.audio,plainFallback:v}:{speechText:g,visibleText:g,sourceElement:d,regionElement:m,speechMatchesVisibleText:!1,visibleMap:h.map,audio:f.audio});return}v&&r.push(v);return}for(let h of wu(d))c(h)};return c(e),i(),r}resolveGeneratedPlaybackFormat(){let e=this.currentProvider;return e&&e.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(e,t,r,n){let i=this.resolveGeneratedPlaybackFormat(),{plan:o,containsMathMarkup:s,visibleText:a}=await kV({contentRoot:e,range:n,language:r,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(r),produceSsml:i==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver});if(!s){let d=n?t:a||t;return{contentToSpeak:d,speechText:d,visibleText:d,highlightText:d,normalizedText:d,containsMathMarkup:!1,speechMatchesVisibleText:!0}}let l=a||t,c=CV(o,{format:i}),u=o.plainSpeechText;return{contentToSpeak:u,speechText:u,visibleText:l,highlightText:l,normalizedText:l,containsMathMarkup:!0,speechMatchesVisibleText:u===l,speechChunks:c}}logResolvedSpeechContent(e){let t=e.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);cs.debug("Speak resolved content",{source:e.speechSource,catalogId:e.catalogId||null,length:e.contentToSpeak.length,preview:t})}initializeSpeakTracking(e,t){this.currentText=e,this.currentContentElement=t.contentElement,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(e){if(!this.currentContentElement||!this.highlightCoordinator||(this.buildPositionMap(this.currentContentElement,e.contentToSpeak,e.options.language),e.highlightMode==="sentence"&&e.shouldUsePlan))return;let t=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(e.runId,()=>{if(t)this.highlightSentenceSegment(t.startOffset,t.text),cs.debug("Applied initial sentence highlighting");else try{let r=document.createRange();r.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([r])}catch{}})}configureWordBoundaryHighlighting(e){if(this.provider){if(e.highlightMode==="sentence"){this.provider.onWordBoundary=void 0;return}!this.highlightCoordinator||!this.currentContentElement||(this.provider.onWordBoundary=(t,r,n)=>{let i=n||t.length,o=r+this.currentBoundaryOffset,s=o+e.wordBoundaryOffset;this.highlightSentenceForOffset(o);let a=Md(this.normalizedToDOM,s,s+i);if(a.length===0){cs.debug(`no text at position ${s}, length ${i}, to highlight`);return}cs.debug(`Highlighting "${a.join("")}" (word: "${t}") at position ${s}`),this.paintTTSWord(a)})}}clearWordBoundaryHighlighting(){this.provider&&(this.provider.onWordBoundary=void 0)}highlightCatalogRegion(e){let t=e.regionElement||e.sourceElement;if(!(!t&&!e.regionRange||!this.highlightCoordinator))try{if(this.lastRenderedRegionTarget=null,e.regionRange){let n=Md(e.visibleMap,0,e.visibleText.length);this.highlightCoordinator.clearHighlights(so.TTS_WORD),this.paintTTSSentenceRanges(n.length>1?n:[e.regionRange]);return}if(!t)return;let r=document.createRange();r.selectNodeContents(t),this.highlightCoordinator.clearHighlights(so.TTS_WORD),this.paintTTSSentenceRanges([r])}catch{}}highlightRenderableRegionTarget(e){if(!(!this.highlightCoordinator||!e||typeof document>"u")&&!(!this.highlightTargetResolverProvider&&RV(this.lastRenderedRegionTarget,e)))try{let t=document.createRange();if(e.type==="element")t.selectNodeContents(e.element);else if(e.type==="range"){this.paintTTSSentenceRanges(e.ranges??[e.range]),this.lastRenderedRegionTarget=e;return}else t.setStart(e.node,e.startOffset),t.setEnd(e.node,e.endOffset);this.paintTTSSentenceRanges([t]),this.lastRenderedRegionTarget=e}catch{}}highlightRenderableActiveTarget(e){if(!this.highlightCoordinator||typeof document>"u")return;if(!e){this.highlightCoordinator.clearHighlights(so.TTS_WORD);return}if(e.type==="text-range"){let i=this.createTextRange(e.node,e.startOffset,e.endOffset);i&&this.paintTTSWord([i]);return}if(e.type==="range"){this.paintTTSWord(e.ranges??[e.range]);return}let t=document.createRange();t.selectNodeContents(e.element);let r=this.resolveWordHighlightRange(t);if(r.remapped){this.highlightCoordinator.highlightTTSWord([r.range]);return}let n=e.element.childNodes.length===1?e.element.firstChild:null;if(e.quality==="semantic-token"&&n?.nodeType===Node.TEXT_NODE){let i=document.createRange();i.selectNodeContents(n),this.highlightCoordinator.highlightTTSWord([i]);return}this.highlightCoordinator.highlightTTSWordElement(e.element)}renderHighlightDecision(e){this.highlightRenderableRegionTarget(e.regionTarget),this.highlightRenderableActiveTarget(e.activeTarget)}async speakCatalogChunk(e,t){try{await this.speakCatalogChunkOnce(e,t)}catch(r){if(e.plainFallback&&t===this.speakRunId){cs.debug("SSML chunk speak failed; retrying plain text",{message:r instanceof Error?r.message:String(r)}),this.playbackStartDeferredRunId===t&&this.provider&&!("onPlaybackStart"in this.provider)&&(this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.markPlaying()),await this.speakCatalogChunkOnce(e.plainFallback,t);return}throw r}}async playRecordedAudio(e,t){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let r=e.sources[0],n=document.createElement("audio");n.preload="auto",n.src=KD(r.src,e.fragment),n.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((i,o)=>{let s,a=!1,l=!1,c=()=>{l||a||(a=!0,t?.())},u=()=>{n.removeEventListener("ended",d),n.removeEventListener("error",f),n.removeEventListener("playing",c),s?.(),this.activeRecordedAudio?.element===n&&(this.activeRecordedAudio=null)},d=()=>{l||(l=!0,u(),i())},f=()=>{l||(l=!0,u(),o(Error(`[tts] recorded audio failed to play: ${r.src}`)))},h=()=>{Promise.resolve(n.play()).then(c).catch(g=>{g?.name==="AbortError"&&this.state===Tt.PAUSED||f()})};this.activeRecordedAudio={element:n,cancel:()=>{l||(l=!0,u(),n.pause(),i())},play:h},n.addEventListener("ended",d),n.addEventListener("error",f),n.addEventListener("playing",c),s=YD(n,e.fragment,d),h()}).finally(()=>{this.activeRecordedAudio?.element===n&&(this.activeRecordedAudio=null),n.pause(),n.removeAttribute("src")})}cancelRecordedAudio(){let e=this.activeRecordedAudio;e&&(this.activeRecordedAudio=null,e.cancel())}async speakCatalogChunkOnce(e,t){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,e.audio){this.runWhenPlaybackStarts(t,()=>{this.highlightCatalogRegion(e)}),await this.playRecordedAudio(e.audio,()=>{this.notifyPlaybackStarted(t)});return}let r=e.regionElement||e.sourceElement||this.currentContentElement,n=r?pV({contentRoot:r,chunks:[e]})[0]:null,i=this.ttsConfig.mathTokenHighlighting!==!1,o=n?dV({chunks:[n],mathTokenHighlighting:i}):null;if(this.runWhenPlaybackStarts(t,()=>{o&&n&&e.mathAlignment?this.renderHighlightDecision(o.resolveInitial(n.id)):this.highlightCatalogRegion(e)}),!(this.resolveHighlightMode()==="word"&&e.sourceElement&&(e.mathAlignment&&e.mathAlignment.speech.tokens.length>0||e.mathAlignments&&e.mathAlignments.length>0||e.alignment&&e.visibleMap&&(e.playbackMode==="exact-word"||e.playbackMode==="anchor-span")))){let c=this.provider,u=c.onWordBoundary;c.onWordBoundary=void 0;try{await this.speakWithinLimit(e.speechText,t)}finally{this.provider===c&&t===this.speakRunId&&c.onWordBoundary===void 0&&(c.onWordBoundary=u)}return}let s=this.provider,a=s.onWordBoundary,l=(c,u,d)=>{if(t===this.speakRunId&&o&&n){let f=n.offsetSpace==="unsupported"?"unknown":n.offsetSpace;this.renderHighlightDecision(o.resolveBoundary({chunkId:n.id,word:c,position:u,length:d,providerOffsetSpace:f}));return}};s.onWordBoundary=l;try{await this.speakWithinLimit(e.speechText,t)}finally{this.provider===s&&t===this.speakRunId&&s.onWordBoundary===l&&(s.onWordBoundary=a)}}async executeSpeakPlayback(e){if(e.speechChunks?.length&&this.provider){for(let t=0;t<e.speechChunks.length;t++){if(await this.waitWhilePaused(e.runId),e.runId!==this.speakRunId)return;let r=this.seekSegments[t];r&&(this.currentBoundaryOffset=r.startOffset);let n=e.speechChunks[t];await this.speakCatalogChunk(n,e.runId)}return}if(e.shouldUsePlan&&this.currentContentElement){let t=this.seekSegments;t.length>0?await this.speakWithPlan(t,e.runId,{highlightMode:e.highlightMode}):await this.speakWithinLimit(e.contentToSpeak,e.runId);return}await this.speakWithinLimit(e.contentToSpeak,e.runId)}clearHighlightsAndTracking(){this.clearWordBoundaryHighlighting(),this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator&&this.highlightCoordinator.clearTTS(),this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.activeSentenceStartOffset=null}selectMappedRangeText(e,t,r){if(typeof e.comparePoint!="function")return null;let{text:n,map:i}=$d(t,this.getTextProcessingOptions(r)),o=-1,s=-1;for(let[u,{node:d,offset:f}]of i)u>=n.length||fb(e,d,f)&&((o===-1||u<o)&&(o=u),u>s&&(s=u));if(o===-1)return null;let a=n.slice(o,s+1),l=a.length-a.trimStart().length,c=a.trim();return c?{text:c,offset:o+l}:null}pause(){this.state!==Tt.PLAYING&&this.state!==Tt.LOADING||(this.resumeState=this.state,this.activeRecordedAudio?.element.pause(),this.provider?.pause(),this.setState(Tt.PAUSED))}resume(){this.state===Tt.PAUSED&&(this.setState(this.resumeState),this.activeRecordedAudio?.play(),this.provider?.resume(),this.releasePauseHold())}normalizePlaybackRate(e){return Number.isFinite(e)?Math.max(.25,Math.min(4,e)):1}async restartFromSeekIndex(e){if(!this.provider||this.seekSegments.length===0)return;let t=Math.max(0,Math.min(this.seekSegments.length-1,e)),r=this.playbackChunks.length?this.playbackChunks.slice(t):null,n=this.state===Tt.PAUSED;this.speakRunId+=1,this.abandonRun(),this.provider.onWordBoundary=void 0,this.provider.stop();let i=++this.speakRunId,o=this.seekSegments.slice(t);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.currentBoundaryOffset=this.seekSegments[t].startOffset,!n&&this.setState(Tt.LOADING);let s=this.installPlaybackStartBarrier(i,!!r?.[0]?.audio);n?this.resumeState=s?Tt.LOADING:Tt.PLAYING:s||this.setState(Tt.PLAYING),this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),r)for(let a=0;a<r.length;a++){if(await this.waitWhilePaused(i),i!==this.speakRunId)return;let l=t+a,c=this.seekSegments[l];c&&(this.currentBoundaryOffset=c.startOffset),await this.speakCatalogChunk(r[a],i)}else await this.speakWithPlan(o,i,{highlightMode:this.activeHighlightMode});if(i!==this.speakRunId)return;this.setState(Tt.IDLE),this.clearHighlightsAndTracking()}catch(a){if(i!==this.speakRunId)return;throw this.lastError=a instanceof Error?a.message:String(a),this.setState(Tt.ERROR),this.clearHighlightsAndTracking(),a}finally{this.clearPlaybackStartBarrier(s)}}async setPlaybackRate(e){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let t=this.normalizePlaybackRate(e),r=this.pendingPlaybackRateRequest;if(r?.rate===t){await r.promise;return}let n=++this.playbackRateRequestId,i=this.playbackRateWriteQueue.then(async()=>{let a=this.speakRunId;if(n!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:a};let l=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));return t===l?{didUpdate:!1,playbackRunId:a}:(await this.updateSettings({rate:t}),{didUpdate:!0,playbackRunId:a})});this.playbackRateWriteQueue=i.then(()=>{},()=>{});let o=i.then(async a=>{if(n!==this.playbackRateRequestId||a.playbackRunId!==this.speakRunId)return;let l=this.activePlaybackRate!==null&&this.activePlaybackRate!==t;!a.didUpdate&&!l||this.state!==Tt.PLAYING&&this.state!==Tt.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText)||await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),s;s=o.finally(()=>{this.pendingPlaybackRateRequest?.promise===s&&(this.pendingPlaybackRateRequest=null)}),this.pendingPlaybackRateRequest={rate:t,promise:s},await s}async seekBy(e){if(!this.provider||!this.currentText||this.state!==Tt.PLAYING&&this.state!==Tt.PAUSED||this.hasExplicitBreakSemantics(this.currentText)||this.seekSegments.length===0)return;let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return;let r=this.getCurrentSeekSegmentIndex(),n=Math.max(0,Math.min(this.seekSegments.length-1,r+t));n!==r&&await this.restartFromSeekIndex(n)}async seekForward(e=1){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;await this.seekBy(t)}async seekBackward(e=1){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;await this.seekBy(-t)}stop(){this.speakRunId+=1,this.abandonRun(),this.provider&&(this.provider.onWordBoundary=void 0,this.provider.stop()),this.setState(Tt.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.activeSentenceStartOffset=null,this.activePlaybackRate=null}releaseProvider(){this.stop(),this.provider=null,this.currentProvider=null}dispose(){this.disposed||(this.releaseProvider(),this.disposed=!0,this.speakRunId+=1,this.abandonRun(),this.playbackRateRequestId+=1,this.pendingPlaybackRateRequest=null,this.listeners.clear(),this.readinessGate=null,this.mathSpeechSource=null,this.highlightTargetResolverProvider=null,this.highlightCoordinator=null,this.catalogResolver=null,this.telemetryReporter=null)}requestControlHandoff(){typeof window>"u"||window.dispatchEvent(new CustomEvent(xV,{detail:{source:"host"}}))}isPlaying(){return this.state===Tt.PLAYING}isPaused(){return this.state===Tt.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(e){let t=r=>e(r);return this.listeners.add(t),()=>{this.listeners.delete(t)}}setState(e){if(this.state===e)return;let t=this.state;this.state=e;for(let r of[...this.listeners])r(e);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",previousState:t,state:e}),e===Tt.PLAYING){let r=t===Tt.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(r,{toolId:"textToSpeech",previousState:t,state:e});return}if(e===Tt.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",previousState:t,state:e});return}if(e===Tt.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",previousState:t,state:e,message:this.lastError||void 0});return}e===Tt.IDLE&&(t===Tt.PLAYING||t===Tt.PAUSED||t===Tt.LOADING)&&this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",previousState:t,state:e})}},uT=ei("browser-tts-provider",xu),dT=5e3,vA=2e3,_V=["__pieTelemetry","contentLanguage","highlightMode","locale","mathSpeech","segmenter","structuralPauses","textNormalization"],AV=e=>{let t={};e.rate!==void 0&&(t.rate=e.rate),e.pitch!==void 0&&(t.pitch=e.pitch),e.mathTokenHighlighting!==void 0&&(t.mathTokenHighlighting=e.mathTokenHighlighting);let r=e.providerOptions;if(r&&typeof r=="object"){let n={};for(let i of _V)r[i]!==void 0&&(n[i]=r[i]);Object.keys(n).length>0&&(t.providerOptions=n)}return t},fT=e=>{if(!H_(e))return{text:e,sourceOffset:i=>i};let{spokenText:t,rawToSpokenOffsetMap:r}=q_(e),n=[];for(let[i,o]of r){let s=n[o];(s===void 0||i<s)&&(n[o]=i)}return{text:t,sourceOffset:i=>{for(let o=i;o>=0;o--){let s=n[o];if(s!==void 0)return s}return 0}}},kb=e=>String(e||"").trim().toLowerCase(),$V=()=>kb((typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"")||"en-US"),MV=(e,t)=>{let r=kb(t)||$V(),n=r.split("-")[0]||"en",i=kb(e.lang);return i===r||i.startsWith(`${n}-`)},OV=(e,t,r)=>{if(t)return e.find(o=>o.voiceURI===t)||e.find(o=>o.name===t)||null;let n=o=>MV(o,r),i=[o=>o.localService&&n(o),o=>o.default&&n(o),o=>n(o),o=>o.localService,o=>o.default];for(let o of i){let s=e.find(o);if(s)return s}return e[0]||null},LV=(e,t,r=()=>!0)=>{if(e.getVoices().length>0)return Promise.resolve(!0);let n=typeof e.addEventListener=="function"&&typeof e.removeEventListener=="function";return!n&&!("onvoiceschanged"in e)?Promise.resolve(!1):new Promise(i=>{let o=n?null:e.onvoiceschanged,s=!1,a=f=>{s||(s=!0,clearTimeout(d),n?e.removeEventListener("voiceschanged",c):e.onvoiceschanged===u&&(e.onvoiceschanged=o),i(f))},l=()=>{r()?e.getVoices().length>0&&a(!0):a(!1)},c=()=>l(),u=f=>{try{o?.call(e,f)}finally{l()}},d=setTimeout(()=>a(!1),t);n?e.addEventListener("voiceschanged",c):e.onvoiceschanged=u,l()})},NV=e=>!e.default,DV=class{constructor(){T(this,"providerId","browser"),T(this,"providerName","Browser Speech Synthesis"),T(this,"version","1.0.0")}async initialize(e){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return typeof e.voice=="string"&&e.voice.trim()&&await LV(window.speechSynthesis,vA),new jV(e)}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,defaultHighlightMode:"sentence",supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}},jV=class{constructor(e){T(this,"utterance",null),T(this,"config",null),T(this,"_isPlaying",!1),T(this,"_isPaused",!1),T(this,"speakRunId",0),T(this,"activeRunId",null),T(this,"releasePauseHold",null),T(this,"settlePendingChunk",null),T(this,"settlePendingGap",null),T(this,"onPlaybackStart",void 0),T(this,"onWordBoundary",void 0),this.config=e}async waitWhilePaused(e){for(;this._isPaused&&e===this.speakRunId;)await new Promise(t=>{this.releasePauseHold=t});return e===this.speakRunId}releaseHold(){let e=this.releasePauseHold;this.releasePauseHold=null,e?.()}resolveBrowserVoice(){let e=typeof this.config?.voice=="string"?this.config.voice.trim():"",t=speechSynthesis.getVoices();if(e&&t.length===0)throw Error(`Configured browser voice "${e}" could not be resolved because the browser did not publish its voice inventory within ${vA/1e3} seconds.`);let r=OV(t,e||void 0,this.getContentLocale());if(e&&!r)throw Error(`Configured browser voice "${e}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return r}async speak(e){if(!this.config)throw Error("TTS not initialized");this.stop();let t=this.speakRunId;this.activeRunId=t;try{let r=this.resolveBrowserVoice(),n=fT(e),i=this.splitIntoChunks(n.text);for(let o of i)if(this._isPaused&&!await this.waitWhilePaused(t)||!await this.speakChunk(o.text,o.offset,t,r,n.sourceOffset))break}finally{this.activeRunId===t&&(this.activeRunId=null)}}async speakSegments(e){if(!this.config)throw Error("TTS not initialized");this.stop();let t=this.speakRunId;this.activeRunId=t;try{let r=this.resolveBrowserVoice();for(let n of e){if(t!==this.speakRunId)break;let i=fT(n.text),o=this.splitIntoChunks(i.text);for(let a of o)if(this._isPaused&&!await this.waitWhilePaused(t)||!await this.speakChunk(a.text,a.offset,t,r,l=>n.startOffset+i.sourceOffset(l)))break;let s=Math.max(0,Number(n.pauseMsAfter||0));if(s>0&&t===this.speakRunId&&!await this.waitForPause(s,t))break}}finally{this.activeRunId===t&&(this.activeRunId=null)}}async waitForPause(e,t){return await new Promise(r=>{let n=()=>{clearTimeout(i),this.settlePendingGap===n&&(this.settlePendingGap=null),r()},i=setTimeout(n,e);this.settlePendingGap=n}),t===this.speakRunId}splitIntoChunks(e){if(e.length<=260)return[{text:e,offset:0}];let t=this.segmentSentences(e),r=[],n="",i=0;for(let o of t){let s=o.text.trim();if(!s)continue;let a=o.text.search(/\S/),l=o.offset+(a===-1?0:a);if(!n){n=s,i=l;continue}let c=`${n} ${s}`;c.length<=260?n=c:(r.push({text:n,offset:i}),n=s,i=l)}return n&&r.push({text:n,offset:i}),r.length?r:[{text:e,offset:0}]}getContentLocale(){let e=this.config?.providerOptions?.contentLanguage;return typeof e=="string"&&e.trim()?e.trim():void 0}getSegmentationPolicy(){let e=this.config?.providerOptions||{},t=e.segmenter||{},r=t.mode!=="regexOnly";return{useSentenceSegmenter:r,useWordSegmenter:r,locale:typeof t.locale=="string"&&t.locale.trim().length>0?t.locale:typeof e.locale=="string"&&e.locale.trim().length>0?e.locale:void 0}}segmentSentences(e){let t=this.getSegmentationPolicy();return lg(e,{locale:t.locale,useSentenceSegmenter:t.useSentenceSegmenter})}inferWordLength(e,t){let r=Math.max(0,Math.min(t,Math.max(0,e.length-1)));return e.slice(r).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(e,t,r,n,i){return new Promise((o,s)=>{if(r!==this.speakRunId){o(!1);return}let a=new SpeechSynthesisUtterance(e);this.utterance=a;let l=this.getContentLocale();l&&(a.lang=l),n&&NV(n)&&(a.voice=n),this.config?.rate&&(a.rate=this.config.rate),this.config?.pitch&&(a.pitch=this.config.pitch);let c=!1,u=!1,d=null,f=null,h=()=>{this.utterance===a&&(this.utterance=null)},g=()=>{d!==null&&(clearTimeout(d),d=null)},m=()=>{a.onstart=null,a.onend=null,a.onerror=null,a.onpause=null,a.onresume=null,a.onboundary=null},v=(I,C)=>{u||(u=!0,g(),m(),h(),f&&this.settlePendingChunk===f&&(this.settlePendingChunk=null),r===this.speakRunId&&(this._isPlaying=!1),C?s(C):o(I))},b=I=>Error(I==="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 ${dT/1e3} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);f=()=>v(!1),this.settlePendingChunk=f,a.onstart=()=>{if(r!==this.speakRunId){v(!1);return}c=!0,g(),this._isPlaying=!0,this._isPaused&&speechSynthesis.pause();try{this.onPlaybackStart?.()}catch(I){console.error("Browser TTS playback-start callback failed",I)}},a.onend=()=>{if(r!==this.speakRunId){v(!1);return}if(!c){v(!1,b("ended"));return}v(!0)},a.onerror=I=>{if(r!==this.speakRunId){v(!1);return}if(I.error==="interrupted"||I.error==="canceled"){v(!1);return}v(!1,Error(`Speech synthesis error: ${I.error}`))},a.onpause=()=>{r===this.speakRunId&&(this._isPaused=!0)},a.onresume=()=>{r===this.speakRunId&&(this._isPaused=!1)},a.onboundary=I=>{if(r!==this.speakRunId||(uT.debug(`boundary event: ${I.name}, charIndex ${I.charIndex}, charLength ${I.charLength}`),I.name!=="word"||!this.onWordBoundary))return;let C=Math.max(0,Math.min(I.charIndex,Math.max(0,e.length-1))),x=Number(I.charLength||0),$=this.inferWordLength(e,C),P=Number.isFinite(x)&&x>0&&x<=80&&C+x<=e.length?x:$,L=e.substring(C,Math.min(e.length,C+P)).trim(),J=t+C,V=i(J),Y=i(J+P-1)+1-V;uT.debug(`word boundary "${L}" at ${V}`),this.onWordBoundary(L,V,Y)},d=setTimeout(()=>{u||c||r!==this.speakRunId||(v(!1,b("timedOut")),speechSynthesis.cancel())},dT);try{speechSynthesis.speak(a)}catch(I){v(!1,I instanceof Error?I:Error("Browser speech synthesis failed to queue speech"))}})}pause(){this._isPaused||(this._isPlaying?(speechSynthesis.pause(),this._isPaused=!0):this.activeRunId===this.speakRunId&&(this._isPaused=!0))}resume(){this._isPaused&&(this._isPaused=!1,this._isPlaying&&speechSynthesis.resume(),this.releaseHold())}stop(){let e=this.utterance,t=this._isPlaying||e!==null;this.speakRunId+=1,this.activeRunId=null,this.settlePendingChunk?.(),this.settlePendingGap?.(),t&&speechSynthesis.cancel(),this.utterance=null,this._isPlaying=!1,this._isPaused=!1,this.releaseHold()}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(e){this.config||(this.config={}),e.rate!==void 0&&(this.config.rate=e.rate),e.pitch!==void 0&&(this.config.pitch=e.pitch),e.voice!==void 0&&(this.config.voice=e.voice),e.providerOptions!==void 0&&(this.config.providerOptions={...this.config.providerOptions||{},...e.providerOptions||{}})}},zV=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),yA=e=>e&&typeof e=="object"?e:{},us=(e,t)=>e===void 0?t:e,BV=(e,t="left-aligned")=>typeof e=="string"&&zV.has(e)?e:t;Object.freeze([{rate:.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);Object.freeze([.8,1,1.25]);var FV=e=>{let t={...e,layoutMode:BV(e.layoutMode)};if(e.backend!=="server")return t;let r={...t,apiEndpoint:us(t.apiEndpoint,"/api/tts"),transportMode:us(t.transportMode,"pie"),endpointValidationMode:us(t.endpointValidationMode,"voices"),validateEndpoint:us(t.validateEndpoint,!0),includeAuthOnAssetFetch:us(t.includeAuthOnAssetFetch,!1),rate:us(t.rate,1),language:us(t.language,"en-US")};return e.serverProvider==="polly"?{...r,engine:us(r.engine,"neural"),format:us(r.format,"mp3"),speechMarksMode:us(r.speechMarksMode,"word+sentence")}:r},hT=e=>{let{enabled:t,provider:r,...n}=yA(e);return FV(n)},bA=e=>e.backend||"browser",pT=e=>{let t=bA(e)==="server"?e.serverProvider:void 0,r=t==="polly",n=e.transportMode||(t==="custom"?"custom":"pie"),i=ku(e.mathSpeech);return{voice:e.defaultVoice,rate:e.rate,pitch:e.pitch,providerOptions:{...yA(e.providerOptions),...e.language?{locale:e.language}:{},...r&&e.engine?{engine:e.engine}:{},...r&&typeof e.sampleRate=="number"?{sampleRate:e.sampleRate}:{},...r&&e.format?{format:e.format}:{},...r?{speechMarkTypes:e.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...n==="custom"&&typeof e.cache=="boolean"?{cache:e.cache}:{},...n==="custom"&&e.speedRate?{speedRate:e.speedRate}:{},...n==="custom"&&e.lang_id?{lang_id:e.lang_id}:{},...i?{mathSpeech:i}:{}},apiEndpoint:e.apiEndpoint,provider:t,language:e.language,transportMode:n,endpointMode:e.endpointMode,endpointValidationMode:e.endpointValidationMode,includeAuthOnAssetFetch:e.includeAuthOnAssetFetch,assetOrigins:e.assetOrigins,credentials:e.credentials,headers:e.headers,validateEndpoint:e.validateEndpoint,...typeof e.mathTokenHighlighting=="boolean"?{mathTokenHighlighting:e.mathTokenHighlighting}:{}}},Pc=ei("ToolProviderRegistry",za),HV=class{constructor(){T(this,"providers",new Map),T(this,"configs",new Map),T(this,"initialized",new Map),T(this,"initializationPromises",new Map)}async emitTelemetry(e,t,r){try{await e.onTelemetry?.(t,r)}catch(n){console.warn("[ToolProviderRegistry] Telemetry callback failed:",n)}}register(e,t){let r=this.providers.get(e),n=this.initializationPromises.get(e);this.providers.set(e,t.provider),this.configs.set(e,t),this.initialized.set(e,!1),this.initializationPromises.delete(e),r&&(n?n.catch(()=>{}).then(()=>this.destroyProvider(e,r)):this.destroyProvider(e,r)),Pc.debug(`${r?"Replaced":"Registered"} provider "${e}" (${t.provider.providerName})`),t.lazy===!1&&this.initialize(e).catch(i=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${e}":`,i)})}async initialize(e){if(this.initialized.get(e))return;let t=this.initializationPromises.get(e);if(t)return t;let r=this.providers.get(e),n=this._doInitialize(e);this.initializationPromises.set(e,n);try{await n}catch(i){if(!this.isReplaced(e,r))throw i}finally{this.initializationPromises.get(e)===n&&this.initializationPromises.delete(e)}if(this.isReplaced(e,r))return this.initialize(e)}isReplaced(e,t){let r=this.providers.get(e);return r!==void 0&&r!==t}destroyProvider(e,t){try{t.destroy()}catch(r){console.warn(`[ToolProviderRegistry] Failed to destroy provider "${e}":`,r)}}async _doInitialize(e){let t=this.providers.get(e),r=this.configs.get(e);if(!t||!r)throw Error(`[ToolProviderRegistry] Provider "${e}" not registered`);let n={...r.config},i=s=>{let a=s&&typeof s=="object"?s.backend:void 0;return typeof a=="string"&&a?a:"unknown"},o=Date.now();if(await this.emitTelemetry(r,"pie-tool-init-start",{toolId:e,backend:i(n),operation:"provider-initialize"}),t.requiresAuth&&r.authFetcher){let s=Date.now();await this.emitTelemetry(r,"pie-tool-backend-call-start",{toolId:e,backend:i(n),operation:"auth-fetch"}),Pc.debug(`Fetching auth for "${e}"...`);try{let a=await r.authFetcher();n={...n,...a},await this.emitTelemetry(r,"pie-tool-backend-call-success",{toolId:e,backend:i(n),operation:"auth-fetch",duration:Date.now()-s})}catch(a){throw await this.emitTelemetry(r,"pie-tool-backend-call-error",{toolId:e,backend:i(n),operation:"auth-fetch",duration:Date.now()-s,errorType:"ProviderAuthFetchError",message:a instanceof Error?a.message:String(a)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${e}":`,a),Error(`Failed to fetch auth credentials for provider "${e}"`)}}try{await t.initialize(n),this.providers.get(e)===t&&this.initialized.set(e,!0),await this.emitTelemetry(r,"pie-tool-init-success",{toolId:e,backend:i(n),operation:"provider-initialize",duration:Date.now()-o}),Pc.debug(`Provider "${e}" initialized`)}catch(s){throw await this.emitTelemetry(r,"pie-tool-init-error",{toolId:e,backend:i(n),operation:"provider-initialize",duration:Date.now()-o,errorType:"ProviderInitializationError",message:s instanceof Error?s.message:String(s)}),console.error(`[ToolProviderRegistry] Initialization failed for "${e}":`,s),s}}async getProvider(e,t=!0){let r=this.providers.get(e);if(!r)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:e,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${e}" not registered`);return t&&!this.initialized.get(e)&&(Pc.debug("Auto-initializing provider:",e),await this.initialize(e)),r}getProvidersByCategory(e){return Array.from(this.providers.entries()).filter(([t,r])=>r.category===e).map(([t])=>t)}getProviderIds(){return Array.from(this.providers.keys())}has(e){return this.providers.has(e)}isInitialized(e){return this.initialized.get(e)===!0}isInitializing(e){return this.initializationPromises.has(e)}async unregister(e){let t=this.providers.get(e);if(t){let r=this.initializationPromises.get(e);if(r){try{await r}catch{}if(this.providers.get(e)!==t)return}this.destroyProvider(e,t),this.providers.delete(e),this.configs.delete(e),this.initialized.delete(e),this.initializationPromises.delete(e),Pc.debug(`Unregistered provider "${e}"`)}}async destroy(){let e=Array.from(this.providers.keys());await Promise.all(e.map(t=>this.unregister(t))),Pc.debug("Registry destroyed")}},UV=class{constructor(){T(this,"targets",new Set),T(this,"changeListeners",new Set)}registerTarget(e){return this.targets.add(e),this.notifyTargetsChange(),()=>{this.targets.delete(e)&&this.notifyTargetsChange()}}canRequest(e,t,r){return this.findTarget(e,t,r)!==null}request(e){let t=this.findTarget(e.toolId,e.level,e.scopeId);if(!t)return!1;try{t.open(e.toolId,e.params)}catch(r){return console.error(`[ToolRequestRegistry] Target failed to open "${e.toolId}":`,r),!1}return!0}onTargetsChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}findTarget(e,t,r){let n=this.findTargetAtLevel(e,t??"section",r);if(n||t!==void 0)return n;for(let i of this.targets)if(i.level!=="section"&&!(r!==void 0&&i.scopeId!==r)&&this.hostsTool(i,e))return i;return null}findTargetAtLevel(e,t,r){for(let n of this.targets)if(n.level===t&&!(r!==void 0&&n.scopeId!==r)&&this.hostsTool(n,e))return n;return null}hostsTool(e,t){try{return e.hostsTool(t)===!0}catch(r){return console.warn(`[ToolRequestRegistry] Target at level "${e.level}" failed the host check for "${t}":`,r),!1}}notifyTargetsChange(){for(let e of this.changeListeners)try{e()}catch(t){console.warn("[ToolRequestRegistry] Target change listener threw:",t)}}dispose(){this.targets.clear(),this.changeListeners.clear()}},qV=class{constructor(e){T(this,"provenance",void 0),T(this,"stepCounter",0),this.provenance={contextId:e,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(e,t){let r={id:t.id,name:t.name??t.id};switch(e){case"organization":this.provenance.sources.organization={...r,pnpDefaults:t.config};break;case"assessment":this.provenance.sources.assessment={...r,settings:t.config};break;case"section":this.provenance.sources.section={...r,settings:t.config};break;case"item":this.provenance.sources.item={...r,settings:t.config};break;case"student":this.provenance.sources.student={id:t.id,pnpProfile:t.config};break;case"host":this.provenance.sources.host={id:t.id,config:t.config}}return this}addDecision(e){let t={step:++this.stepCounter,precedence:e.precedence,rule:e.rule,featureId:e.featureId,action:e.action,source:{type:e.sourceType,id:e.sourceId,name:e.sourceName},reason:e.reason,value:e.value,timestamp:new Date};this.provenance.decisionLog.push(t);let r=this.provenance.features.get(e.featureId);return r||(r={featureId:e.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(e.featureId,r)),r.allDecisions.push(t),e.action==="advisory"?r.finalState==="not-configured"&&(r.finalState="advisory-only"):e.action!=="skip"&&(!r.winningDecision||t.precedence<r.winningDecision.precedence)&&(r.winningDecision=t,r.finalState=t.action==="enable"?"enabled":"blocked"),this.provenance.summary.bySource[e.sourceType]=(this.provenance.summary.bySource[e.sourceType]||0)+1,this.provenance.summary.byRule[e.rule]=(this.provenance.summary.byRule[e.rule]||0)+1,this}reconcileFinalStates(e){for(let t of e){let r=this.provenance.features.get(t);if(!r){r={featureId:t,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(t,r);continue}r.finalState="enabled"}for(let t of this.provenance.features.values()){if(e.has(t.featureId))continue;let r=t.allDecisions.some(i=>i.action!=="skip"&&i.action!=="advisory"),n=t.allDecisions.some(i=>i.action==="advisory");r?t.finalState="blocked":n?t.finalState="advisory-only":t.finalState="not-configured"}return this}build(){for(let e of this.provenance.features.values())e.explanation=WV(e);for(let e of this.provenance.features.values())this.provenance.summary.totalFeatures++,e.finalState==="enabled"?this.provenance.summary.enabled++:e.finalState==="blocked"?this.provenance.summary.blocked++:this.provenance.summary.notConfigured++;return this.provenance}};function WV(e){if(!e.winningDecision){if(e.finalState==="advisory-only"){let o=e.allDecisions.find(s=>s.action==="advisory");return o?`Feature "${e.featureId}" was kept in its host-decided state; ${o.reason}`:`Feature "${e.featureId}" carries an advisory note.`}return`Feature "${e.featureId}" was not configured at any level.`}let t=e.winningDecision,r=t.source.name||t.source.type,n=`Feature "${e.featureId}" is ${e.finalState}.
1644
+
1645
+ `;n+=`**Primary Reason** (${t.rule}):
1646
+ `,n+=`${t.reason}
1647
+ `,n+=`Source: ${r} (${t.source.type})
1648
+ `;let i=e.allDecisions.filter(o=>o.step!==t.step&&o.action!=="skip"&&o.action!=="advisory"&&o.precedence>t.precedence);if(i.length>0){n+=`
1649
+ **Overridden Rules**:
1650
+ `;for(let o of i)n+=`- ${o.rule}: ${o.reason}
1651
+ `}return n}function VV(e){let{request:t,tools:r,pnpPolicy:n,customSources:i,contextId:o}=e,s=new qV(o);s.addSource("host",{id:t.scope.scopeId,name:`${t.level}:${t.scope.scopeId}`,config:{placement:r.placement,policy:r.policy}});let a=gi(r.placement[t.level]),l=gi(r.policy.allowed),c=new Set(gi(r.policy.blocked)),u=[];for(let v of a)u.push(v),s.addDecision({precedence:0,rule:"placement-membership",featureId:v,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${t.level}`});if(u=u.filter(v=>r.providers?.[v]?.enabled===!1?(s.addDecision({precedence:0,rule:"provider-disabled",featureId:v,action:"block",sourceType:"host",reason:`tools.providers.${v}.enabled === false`,value:!1}),!1):!0),l.length>0){let v=new Set(l);u=u.filter(b=>v.has(b)?!0:(s.addDecision({precedence:0,rule:"host-allowlist",featureId:b,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:l}),!1))}u=u.filter(v=>c.has(v)?(s.addDecision({precedence:0,rule:"host-blocked",featureId:v,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:r.policy.blocked}),!1):!0);let d=[],f=new Set(u),h=null;if(n.enforcement==="on"&&n.source&&(n.assessment||n.item)){h=n.source.apply({assessment:n.assessment,item:n.item}),h.sources.assessment&&s.addSource("assessment",h.sources.assessment),h.sources.student&&s.addSource("student",h.sources.student),h.sources.item&&s.addSource("item",h.sources.item);for(let v of h.decisions)s.addDecision({precedence:v.precedence,rule:v.rule,featureId:v.featureId,action:v.action,sourceType:v.sourceType,reason:v.reason,value:v.value});for(let[v,b]of h.unmappedSupportIds)d.push(IA(v,b,t.level));for(let[v,b]of h.blockedOverrides)d.push(SA(v,b,t.level));u=u.filter(v=>!h.blockedToolIds.has(v));for(let v of h.mandatedToolIds){if(f.has(v))continue;let b=h.perToolFlags.get(v)?.rule??"required-tool",I=GV(v,{placement:a,allowed:l,blocked:c,providers:r.providers}),C={rule:b,hostRule:I.hostRule,hostValue:I.hostValue};d.push({code:"tool-policy.requiredToolBlocked",level:t.level,toolId:v,message:`Profile policy mandates "${v}" (${b}) but host policy removed it from level "${t.level}" via ${I.hostRule}.`,details:C}),s.addDecision({precedence:0,rule:"required-tool-blocked",featureId:v,action:"advisory",sourceType:"host",reason:`Host removed required tool "${v}" via ${I.hostRule}`,value:C})}}for(let v=0;v<i.length;v++){let b=i[v],I=u.slice(),C=b.refine({request:t,candidates:I}),x=new Set(C.refinedCandidates);for(let P of C.refinedCandidates)I.includes(P)||(d.push({code:"tool-policy.placementMissing",level:t.level,toolId:P,message:`Custom source "${b.id}" tried to add tool "${P}" that was not in candidates; ignored.`,details:{customSourceId:b.id}}),x.delete(P));u=I.filter(P=>x.has(P));let $=new Set;if(C.decisions)for(let P of C.decisions)s.addDecision({precedence:P.precedence??100+v,rule:P.rule,featureId:P.featureId,action:P.action,sourceType:P.sourceType,reason:P.reason,value:P.value}),P.action==="block"&&$.add(P.featureId);for(let P of I)x.has(P)||$.has(P)||s.addDecision({precedence:100+v,rule:"custom-source",featureId:P,action:"block",sourceType:"custom",reason:`Custom policy source "${b.id}" removed tool "${P}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:b.id}})}for(let v of u)for(let b of e.unappliedItems??[]){let I=["restrictedTools","requiredTools"].filter(x=>b.settings[x]?.includes(v)===!0);if(I.length===0)continue;let C={itemId:b.id,settings:I,toolbarLevel:t.scope.level};d.push({code:"tool-policy.itemSettingNotApplied",level:t.level,toolId:v,message:`Item "${b.id}" names "${v}" in ${I.join(" and ")}, but "${v}" is on the ${t.scope.level}-level toolbar, which item settings do not reach. Place "${v}" at item level to enforce the setting per item.`,details:C})}let g=new Set(u),m=u.map(v=>{let b=h?.perToolFlags.get(v);return{toolId:v,required:b?.required??!1,alwaysAvailable:b?.alwaysAvailable??!1,settings:b?.settings}});return s.reconcileFinalStates(g),{visibleTools:m,diagnostics:d,provenance:s.build()}}function GV(e,t){return t.placement.includes(e)?t.providers?.[e]?.enabled===!1?{hostRule:"provider-disabled",hostValue:!1}:t.allowed.length>0&&!t.allowed.includes(e)?{hostRule:"host-allowlist",hostValue:t.allowed}:t.blocked.has(e)?{hostRule:"host-blocked",hostValue:Array.from(t.blocked)}:{hostRule:"placement-missing",hostValue:t.placement}:{hostRule:"placement-missing",hostValue:t.placement}}var wA={"district-block":"settings.districtPolicy.blockedTools","test-admin-override":"settings.testAdministration.toolOverrides","item-restriction":"item settings.restrictedTools","pnp-prohibited":"personalNeedsProfile.prohibitedSupports","item-requirement":"item settings.requiredTools","district-requirement":"settings.districtPolicy.requiredTools","pnp-support":"personalNeedsProfile.supports"};function SA(e,t,r){return{code:"tool-policy.overrideBlocked",...r?{level:r}:{},toolId:e,message:`settings.testAdministration.toolOverrides grants "${e}", but ${wA[t]} withdraws it and outranks a granting override.`,details:{rule:t}}}function IA(e,t,r){let n=t.map(i=>wA[i]).join(", ");return{code:"tool-policy.unknownSupportId",...r?{level:r}:{},toolId:e,message:`No tool is registered under "${e}", named in ${n}, so it matches nothing. These lists name tools by tool id.`,details:{origins:[...t]}}}var YV=e=>`No assessment is bound, so no policy source could grant "${e}"`;function mT(e,t,r,n){return{featureId:e,granted:!1,action:"block",rule:t,precedence:0,sourceType:"host",reason:t==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${r.join(", ")})`,required:!1,assessmentBound:n.assessmentBound,diagnostics:[]}}function KV(e,t,r){let n=t.decisions[0],i=Array.from(t.perToolFlags.values())[0],o=n?.action==="enable",s=n?.reason??`Feature "${e}" not configured`;return{featureId:e,granted:o,action:n?.action??"skip",rule:n?.rule??"pnp-support",precedence:n?.precedence??8,sourceType:n?.sourceType??"system",reason:r.assessmentBound||o?s:YV(e),required:!!i?.required,parameters:i?.settings,assessmentBound:r.assessmentBound,diagnostics:[...Array.from(t.unmappedSupportIds,([a,l])=>IA(a,l)),...Array.from(t.blockedOverrides,([a,l])=>SA(a,l))]}}function XV(e){if(!e)return!1;let t=e.personalNeedsProfile;if(t&&(Array.isArray(t.supports)&&t.supports.length>0||Array.isArray(t.prohibitedSupports)&&t.prohibitedSupports.length>0))return!0;let r=e.settings;if(r){let n=r.districtPolicy;if(n&&(Array.isArray(n.blockedTools)&&n.blockedTools.length>0||Array.isArray(n.requiredTools)&&n.requiredTools.length>0))return!0;let i=r.testAdministration?.toolOverrides;if(i&&typeof i=="object"&&Object.keys(i).length>0)return!0}return!1}function JV(e){return e?!!(Array.isArray(e.requiredTools)&&e.requiredTools.length>0||Array.isArray(e.restrictedTools)&&e.restrictedTools.length>0||e.toolParameters&&typeof e.toolParameters=="object"&&Object.keys(e.toolParameters).length>0):!1}function QV(e){return XV(e.assessment)||JV(e.itemSettings)?"on":"off"}var gT=class{constructor(e){T(this,"id","pnp"),T(this,"toolRegistry",void 0),this.toolRegistry=e}apply(e){let{ctx:t,result:r}=this.prepare(e),{pnp:n,districtPolicy:i,testAdmin:o,itemSettings:s}=t,a=new Set;n?.supports?.forEach(l=>a.add(l)),n?.prohibitedSupports?.forEach(l=>a.add(l)),i?.blockedTools?.forEach(l=>a.add(l)),i?.requiredTools?.forEach(l=>a.add(l));for(let l of Object.keys(o?.toolOverrides??{}))a.add(l);s?.requiredTools?.forEach(l=>a.add(l)),s?.restrictedTools?.forEach(l=>a.add(l));for(let l of a)this.resolveSupport(l,t,r);return r}resolveFeature(e,t){let{ctx:r,result:n}=this.prepare(t);return this.resolveSupport(e,r,n),n}prepare(e){let{assessment:t,item:r}=e,n=t?.personalNeedsProfile,i=t?.settings,o=r?.settings,s={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],unmappedSupportIds:this.unmappedIds(n,i,o),blockedOverrides:new Map,sources:{}};return(i?.districtPolicy||i?.testAdministration)&&(s.sources.assessment={id:t?.id||"unknown",name:t?.name||t?.id||"Assessment",config:i}),n&&(s.sources.student={id:"student",name:"Student PNP Profile",config:n}),r&&(s.sources.item={id:r.id,name:r.id,config:r.settings}),{ctx:{pnp:n,districtPolicy:i?.districtPolicy,testAdmin:i?.testAdministration,itemSettings:o,toolConfigs:i?.toolConfigs},result:s}}resolveSupport(e,t,r){if(t.districtPolicy?.blockedTools?.includes(e)){r.blockedToolIds.add(e),r.decisions.push({precedence:1,rule:"district-block",featureId:e,action:"block",sourceType:"assessment",reason:`District policy blocks "${e}" for all assessments`,value:t.districtPolicy.blockedTools});return}let n=t.testAdmin?.toolOverrides?.[e];if(n===!1){r.blockedToolIds.add(e),r.decisions.push({precedence:2,rule:"test-admin-override",featureId:e,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${e}" for this session`,value:t.testAdmin?.toolOverrides});return}if(t.itemSettings?.restrictedTools?.includes(e)){r.blockedToolIds.add(e),n===!0&&r.blockedOverrides.set(e,"item-restriction"),r.decisions.push({precedence:3,rule:"item-restriction",featureId:e,action:"block",sourceType:"item",reason:`Item restricts "${e}" (e.g., mental math question blocks calculator)`,value:t.itemSettings.restrictedTools});return}if(t.pnp?.prohibitedSupports?.includes(e)){r.blockedToolIds.add(e),n===!0&&r.blockedOverrides.set(e,"pnp-prohibited"),r.decisions.push({precedence:4,rule:"pnp-prohibited",featureId:e,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${e}"`,value:t.pnp.prohibitedSupports});return}if(n===!0){r.perToolFlags.set(e,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(e,t),rule:"test-admin-override"}),r.decisions.push({precedence:5,rule:"test-admin-override",featureId:e,action:"enable",sourceType:"assessment",reason:`Test administrator enabled "${e}" for this session`,value:t.testAdmin?.toolOverrides});return}if(t.itemSettings?.requiredTools?.includes(e)){r.mandatedToolIds.add(e),r.perToolFlags.set(e,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(e,t),rule:"item-requirement"}),r.decisions.push({precedence:6,rule:"item-requirement",featureId:e,action:"enable",sourceType:"item",reason:`Item requires "${e}" for this question`,value:t.itemSettings.requiredTools});return}if(t.districtPolicy?.requiredTools?.includes(e)){r.mandatedToolIds.add(e),r.perToolFlags.set(e,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(e,t),rule:"district-requirement"}),r.decisions.push({precedence:7,rule:"district-requirement",featureId:e,action:"enable",sourceType:"assessment",reason:`District policy requires "${e}" for all assessments`,value:t.districtPolicy.requiredTools});return}if(t.pnp?.supports?.includes(e)){r.perToolFlags.set(e,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(e,t),rule:"pnp-support"}),r.decisions.push({precedence:8,rule:"pnp-support",featureId:e,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${e}"`,value:t.pnp.supports});return}r.decisions.push({precedence:8,rule:"pnp-support",featureId:e,action:"skip",sourceType:"system",reason:`Feature "${e}" not configured at any level`,value:{supportId:e}})}unmappedIds(e,t,r){let n=new Map;if(this.toolRegistry.getAllTools().length===0)return n;let i=[["district-block",t?.districtPolicy?.blockedTools],["test-admin-override",Object.keys(t?.testAdministration?.toolOverrides??{})],["item-restriction",r?.restrictedTools],["pnp-prohibited",e?.prohibitedSupports],["item-requirement",r?.requiredTools],["district-requirement",t?.districtPolicy?.requiredTools],["pnp-support",e?.supports]];for(let[o,s]of i)for(let a of s??[]){if(this.toolRegistry.has(a))continue;let l=n.get(a)??[];l.includes(o)||l.push(o),n.set(a,l)}return n}resolveToolSettings(e,t){return t.itemSettings?.toolParameters?.[e]??t.toolConfigs?.[e]}},vT=C0({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}}),ZV=class{constructor(e){T(this,"toolRegistry",void 0),T(this,"contextId",void 0),T(this,"pnpPolicySource",void 0),T(this,"customSources",void 0),T(this,"listeners",new Set),T(this,"tools",void 0),T(this,"assessment",void 0),T(this,"pnpEnforcementOverride",void 0),T(this,"itemSettings",new Map),T(this,"disposed",!1),this.toolRegistry=e.toolRegistry,this.contextId=e.contextId??"tool-policy",this.pnpPolicySource=new gT(this.toolRegistry),this.customSources=e.customSources?[...e.customSources]:[];let t=e.inputs??{};this.tools=t.tools??vT,this.assessment=t.assessment??null,this.pnpEnforcementOverride=t.pnpEnforcement??null}decide(e){this.assertNotDisposed();let t=e.scope.scopeId?`${this.contextId}:${e.level}:${e.scope.scopeId}`:`${this.contextId}:${e.level}`,r=e.level==="item"?this.itemForScope(e.scope):void 0,n=e.level!=="item"||e.scope.level==="section"||e.scope.level==="assessment";return VV({request:e,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,item:r,enforcement:this.enforcementFor(r)},unappliedItems:n?this.enforcedItems():void 0,customSources:this.customSources,contextId:t})}grantsFeatureAnywhere(e){if(this.decideFeature(e).granted)return!0;for(let t of this.itemSettings.keys())if(this.decideFeature(e,{level:"item",scopeId:t}).granted)return!0;return!1}registerItemSettings(e,t){this.assertNotDisposed();let r={settings:t},n=this.itemSettingsFor(e),i=this.itemSettings.get(e)??[];return i.push(r),this.itemSettings.set(e,i),this.emitIfItemSettingsChanged(e,n),()=>{if(this.disposed)return;let o=this.itemSettings.get(e),s=o?.indexOf(r)??-1;if(!o||s<0)return;let a=this.itemSettingsFor(e);o.splice(s,1),o.length===0&&this.itemSettings.delete(e),this.emitIfItemSettingsChanged(e,a)}}decideFeature(e,t){this.assertNotDisposed();let r=this.hostFeatureGate(e);return r||KV(e,this.pnpPolicySource.resolveFeature(e,{assessment:this.assessment??void 0,item:this.itemForScope(t)}),{assessmentBound:this.assessment!==null})}hostFeatureGate(e){let t={assessmentBound:this.assessment!==null},r=gi(this.tools.policy.blocked);if(r.includes(e))return mT(e,"host-blocked",r,t);let n=gi(this.tools.policy.allowed);return n.length>0&&!n.includes(e)?mT(e,"host-allowlist",n,t):null}getVisibleToolIds(e,t){return this.decide({level:e,scope:{level:e,scopeId:t}}).visibleTools.map(r=>r.toolId)}updateInputs(e){this.assertNotDisposed();let t=!1,r=!1;if("tools"in e){let n=e.tools??vT;Object.is(this.tools,n)||(this.tools=n,t=!0)}if("assessment"in e){let n=e.assessment??null;fu(this.assessment,n)||(t=!0),this.assessment=n}if("pnpEnforcement"in e){let n=e.pnpEnforcement??null;this.pnpEnforcementOverride!==n&&(this.pnpEnforcementOverride=n,r=!0)}(t||r)&&this.emit({reason:r&&!t?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(e,t){this.assertNotDisposed(),this.toolRegistry=e,this.pnpPolicySource=new gT(e),this.tools=t,this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(e){return this.assertNotDisposed(),this.customSources.push(e),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let t=this.customSources.indexOf(e);t!==-1&&(this.customSources.splice(t,1),!this.disposed&&this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()}))}}onPolicyChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getInputs(){return this.snapshotInputs()}dispose(){this.disposed||(this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.itemSettings.clear(),this.customSources.length=0)}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,pnpEnforcement:this.enforcementFor(),pnpEnforcementOverride:this.pnpEnforcementOverride})}enforcementFor(e){return this.pnpEnforcementOverride??QV({assessment:this.assessment,itemSettings:e?.settings})}itemSettingsFor(e){return this.itemSettings.get(e)?.at(-1)?.settings}emitIfItemSettingsChanged(e,t){fu(t,this.itemSettingsFor(e))||this.emit({reason:"item-settings",inputs:this.snapshotInputs()})}itemForScope(e){if(e?.level!=="item")return;let t=e.canonicalItemId||e.itemId||e.scopeId,r=t?this.itemSettingsFor(t):void 0;return r?{id:t,settings:r}:void 0}enforcedItems(){let e=[];for(let t of this.itemSettings.keys()){let r=this.itemSettingsFor(t);if(!r)continue;let n={id:t,settings:r};this.enforcementFor(n)==="on"&&e.push(n)}return e}emit(e){for(let t of Array.from(this.listeners))try{t(e)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}};function Tu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ym(e){return Tu(e)&&Tu(e.session)?e.session:e}function eG(e,t){let r=Tu(e)?e:{},n=Tu(t)?t:{},i=new Set([...Object.keys(r),...Object.keys(n)]);for(let o of i)if(!fu(ym(r[o]),ym(n[o])))return!1;return!0}function tG(e,t){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="itemSessions"){if(!eG(n,t.itemSessions))return!1;continue}if(!fu(n,t[r]))return!1}return!0}function kA(e,t){if(!e)return t;let r=Tu(t.itemSessions)?{...t.itemSessions}:{},n=Tu(e.itemSessions)?e.itemSessions:{};for(let[o,s]of Object.entries(n)){if(!Rp(ym(s)))continue;let a=ym(r[o]);Rp(a)||Pp(a)||(r[o]=s)}let i={...t,itemSessions:r};return tG(i,e)?null:i}var $i=class extends Error{constructor(){super("ToolkitCoordinator has been disposed."),this.name="ToolkitCoordinatorDisposedError"}},xv=class extends Error{constructor(){super("Section controller acquisition was retired during initialization."),this.name="SectionControllerRetiredError"}},yT=e=>!!e&&typeof e=="object"&&!Array.isArray(e),rG=(e,t,r)=>{let n={...t,...r};return e==="textToSpeech"&&yT(t.mathSpeech)&&yT(r.mathSpeech)&&(n.mathSpeech={...t.mathSpeech,...r.mathSpeech}),n},nG=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],iG=["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"],oG=class{resolveConfig(e){let t=T_(e.toolConfigStrictness),r=e.toolRegistry??new Iy,n=e.deferToolConfigValidation===!0?C0(e.tools):this.validateToolsConfig(e.tools,{strictness:t,source:"ToolkitCoordinator.init",toolRegistry:r});return{...e,toolConfigStrictness:t,toolRegistry:r,tools:{...n,providers:{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0},...n.providers}},accessibility:{language:"en-US",...e.accessibility??{},catalogs:e.accessibility?.catalogs??[]}}}validateToolsConfig(e,t){let{config:r,diagnostics:n}=E_(e,t.toolRegistry),i=this.reportedRegistryUnavailable||this.toolRegistryPending()?n.filter(o=>o.code!=="tools.registryUnavailable"):n;return C_(i,t),t.strictness!=="off"&&i.some(o=>o.code==="tools.registryUnavailable")&&(this.reportedRegistryUnavailable=!0),r}constructor(e){if(T(this,"assessmentId",void 0),T(this,"config",void 0),T(this,"ttsService",void 0),T(this,"toolCoordinator",void 0),T(this,"highlightCoordinator",void 0),T(this,"elementToolStateStore",void 0),T(this,"catalogResolver",void 0),T(this,"toolProviderRegistry",void 0),T(this,"hooks",void 0),T(this,"lazyInit",void 0),T(this,"ttsInitialized",!1),T(this,"ttsDegraded",!1),T(this,"ttsInitPromise",void 0),T(this,"ttsReconfigurePromise",void 0),T(this,"stateLoaded",!1),T(this,"stateLoadSettled",!1),T(this,"stateLoadPromise",void 0),T(this,"coordinatorReadyPromise",void 0),T(this,"coordinatorReadyNotified",!1),T(this,"providerInitPromises",new Map),T(this,"degradedTools",new Map),T(this,"toolModuleFailures",new Set),T(this,"readyChangeListeners",new Set),T(this,"eagerInit",void 0),T(this,"toolRegistry",void 0),T(this,"toolRegistrySupplied",void 0),T(this,"toolRegistrySettled",void 0),T(this,"toolRegistryAbsent",!1),T(this,"toolContextResolvers",new Map),T(this,"toolContextResolverChangeListeners",new Set),T(this,"toolRequests",new UV),T(this,"sectionControllers",new Map),T(this,"sectionControllerKeys",new Map),T(this,"sectionControllerInitEntries",new Map),T(this,"sectionControllerDisposePromises",new Map),T(this,"sectionPersistenceStrategies",new Map),T(this,"sectionControllerLifecycleListeners",new Set),T(this,"activeSubscriptions",new Map),T(this,"activeCohortMapKey",null),T(this,"latestRequestedActiveCohortMapKey",null),T(this,"telemetryListeners",new Set),T(this,"frameworkErrorBus",void 0),T(this,"ownsFrameworkErrorBus",void 0),T(this,"frameworkErrorHookUnsubscribe",null),T(this,"disposePromise",null),T(this,"policyEngine",void 0),T(this,"pnpEnforcementOverride",null),T(this,"warnedPolicyDiagnostics",new Set),T(this,"reportedUnboundFeaturePolicy",!1),T(this,"reportedMissingTTSProvider",!1),T(this,"heldMissingTTSProviderBackend",null),T(this,"reportedRegistryUnavailable",!1),!e.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=e.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let t=this.resolveConfig(e);this.assessmentId=t.assessmentId,this.config=t,this.toolRegistry=t.toolRegistry??new Iy,this.installToolContextResolvers(t.toolContextResolvers),this.hooks={...t.hooks},this.lazyInit=e.lazyInit===!0,this.eagerInit=e.eagerInit??!this.lazyInit,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=e.frameworkErrorBus??new A_,this.ownsFrameworkErrorBus=!e.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new z5,this.highlightCoordinator=new pw,this.elementToolStateStore=new vq,this.catalogResolver=new mq(t.accessibility?.catalogs||[],t.accessibility?.language||"en-US"),this.toolProviderRegistry=new HV,this._registerToolProviders(),this.ttsService=new PV,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.ttsService.setReadinessGate(()=>this.ensureTTSReady()),this.ttsService.setMathSpeechSource(()=>pT(hT(this.resolveTTSToolConfig())).providerOptions?.mathSpeech),this.setupStatePersistenceHooks(),this.policyEngine=new ZV({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,pnpEnforcement:this.pnpEnforcementOverride}}),this.policyEngine.onPolicyChange(r=>{r.reason!=="disposed"&&this.reportNewlyGrantedFailures()}),this.eagerInit&&this.waitUntilReady().catch(r=>{r instanceof $i||(console.error("[ToolkitCoordinator] Failed eager initialization:",r),this.handleError(r,{phase:"coordinator-ready",recoverable:!1}))})}assertNotDisposed(){if(this.disposePromise!==null)throw new $i}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors(e=>{let t=this.hooks.onFrameworkError;if(t)try{t(e)}catch(r){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",r)}})}async emitTelemetry(e,t){try{await this.hooks.onTelemetry?.(e,t)}catch(n){console.warn("[ToolkitCoordinator] telemetry hook failed:",n)}let r=t?{...t}:void 0;for(let n of this.telemetryListeners)try{n({eventName:e,payload:r?{...r}:void 0})}catch(i){console.warn("[ToolkitCoordinator] telemetry listener failed:",i)}}emitSectionControllerLifecycle(e){for(let t of this.sectionControllerLifecycleListeners)try{t(e)}catch(r){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",r)}}handleError(e,t,r="runtime"){let n=eq({error:e,context:t,recoverable:t.recoverable,scope:r});this.frameworkErrorBus.reportFrameworkError(n)}isToolGranted(e){try{return this.policyEngine.grantsFeatureAnywhere(e)}catch{return!1}}reportToolFailure(e,t,r,n=!1){let i=Array.from(r),o=n||!i.some(s=>this.isToolGranted(s));if(o&&!n)for(let s of i)this.degradedTools.set(s,{error:e,context:t});this.handleError(e,{...t,recoverable:o})}reportToolModuleFailure(e,t){if(this.toolRequests.notifyTargetsChange(),this.toolModuleFailures.has(e))return;this.toolModuleFailures.add(e);let r=t instanceof Error&&t.message.trim().length>0?t.message:String(t);this.reportToolFailure(Error(`Tool "${e}" failed to load: ${r}`,{cause:t}),{phase:"tool-module-load",details:{toolId:e}},[e])}reportNewlyGrantedFailures(){for(let[e,t]of this.degradedTools)this.isToolGranted(e)&&(this.degradedTools.delete(e),this.handleError(t.error,{...t.context,recoverable:!1}))}onReadyChange(e){return this.readyChangeListeners.add(e),()=>{this.readyChangeListeners.delete(e)}}notifyReadyChange(){for(let e of this.readyChangeListeners)try{e()}catch(t){console.warn("[ToolkitCoordinator] ready-change listener failed:",t)}}subscribeFrameworkErrors(e){return this.frameworkErrorBus.subscribeFrameworkErrors(e)}reportFrameworkError(e){this.frameworkErrorBus.reportFrameworkError(e)}getSectionControllerMapKey(e){return`${e.assessmentId}::${e.sectionId}::${e.attemptId||""}`}createDefaultSectionPersistence(){let e=(()=>{try{return typeof window>"u"?null:window.localStorage}catch{return null}})(),t=r=>{let{assessmentId:n,sectionId:i,attemptId:o}=r.key;return o?`pie:section-controller:v1:${n}:${i}:${o}`:null};return{async loadSession(r){let n=t(r);if(!e||!n)return null;let i=e.getItem(n);if(!i)return null;try{return JSON.parse(i)}catch{return null}},async saveSession(r,n){let i=t(r);!e||!i||e.setItem(i,JSON.stringify(n))},async clearSession(r){let n=t(r);!e||!n||e.removeItem(n)}}}async resolveSectionPersistence(e){let t=this.getSectionControllerMapKey(e.key),r=this.sectionPersistenceStrategies.get(t);if(r)return r;let n={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},i=await this.hooks.createSectionSessionPersistence?.(e,n)??await n.createDefaultPersistence();return this.sectionPersistenceStrategies.set(t,i),i}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange(e=>{this.hooks.saveToolState&&Promise.resolve(this.hooks.saveToolState(e)).catch(t=>{this.handleError(t,{phase:"state-save",recoverable:!0})})})}async ensureStateLoaded(){if(!this.stateLoadSettled)return this.stateLoadPromise?this.stateLoadPromise:(this.stateLoadPromise=(async()=>{let e=this.hooks.loadToolState;if(e)try{let t=await e();this.assertNotDisposed(),t&&typeof t=="object"&&this.elementToolStateStore.loadState(t),this.stateLoaded=!0,this.stateLoadSettled=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:!!t})}catch(t){if(t instanceof $i)throw t;this.stateLoadSettled=!0,this.handleError(t,{phase:"state-load",recoverable:!0})}})().finally(()=>{this.stateLoadPromise=void 0,this.notifyReadyChange()}),this.stateLoadPromise)}toolRegistryPending(){return!this.toolRegistrySettled&&!this.toolRegistryAbsent}reportMissingTTSProvider(e){if(this.toolRegistryPending()){this.heldMissingTTSProviderBackend=e;return}this.reportedMissingTTSProvider||(this.reportedMissingTTSProvider=!0,console.warn(`[ToolkitCoordinator] Text-to-speech is configured for the "${e}" backend but falls back to browser speech: no "textToSpeech" tool provider is registered. A coordinator registers tool providers only from its \`toolRegistry\`, or from its toolkit's when constructed without one, so supply one that carries the text-to-speech registration — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders". Reported once per coordinator.`))}adoptToolRegistry(e){if(this.disposePromise!==null||this.toolRegistrySettled||!e&&this.toolRegistryAbsent)return!1;let t=this.heldMissingTTSProviderBackend;this.heldMissingTTSProviderBackend=null;let r=this.config.toolConfigStrictness??"error",n="ToolkitCoordinator.adoptToolRegistry";if(!e)return this.toolRegistryAbsent=!0,this.validateToolsConfig(this.config.tools,{strictness:r,source:n,toolRegistry:this.toolRegistry}),t&&this.reportMissingTTSProvider(t),!1;this.toolRegistrySettled=!0,this.toolRegistry=e,this.config.toolRegistry=e;try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:r==="off"?"off":"warn",source:n,toolRegistry:e})}catch(o){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",o)}this.policyEngine.replaceToolRegistry(e,this.config.tools);let i=this.ttsInitialized||this.ttsInitPromise!==void 0||this.ttsReconfigurePromise!==void 0;for(let o of this.getProviderDescriptorTools())i&&o.toolId==="textToSpeech"||this.registerProviderFromTool(o);return i&&this.scheduleTTSReconfigure(),!0}_registerToolProviders(){let e=this.getProviderDescriptorTools();for(let t of e)this.registerProviderFromTool(t)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter(e=>!!e.provider)}async registerProviderFromTool(e,t=!1){let r=e.provider;if(!r)return;let{toolId:n}=e,i;try{let o=this.getToolConfig(n)||void 0;if(o?.enabled===!1){t&&this.toolProviderRegistry.unregister(n);return}if(!t&&this.toolProviderRegistry.has(n))return;let s=r.createProvider(o),a=r.getInitConfig?.(o)??o?.provider?.init??{},l=this.addToolTelemetryReporter(n,a),c=this.createToolTelemetryForwarder(n),u=r.getAuthFetcher?.(o)??o?.provider?.runtime?.authFetcher;i={provider:s,config:l,lazy:r.lazy??!0,authFetcher:u,onTelemetry:c}}catch(o){this.reportProviderRegisterFailure(o,n);return}await this.registerProvider(n,i)}createToolTelemetryForwarder(e){return async(t,r)=>{await this.emitTelemetry(t,{...r||{},toolId:e})}}addToolTelemetryReporter(e,t){let r=t&&typeof t=="object"?{...t}:{},n=typeof r.onTelemetry=="function"?r.onTelemetry:null,i=this.createToolTelemetryForwarder(e);return r.onTelemetry=async(o,s)=>{n&&await n(o,s),await i(o,s)},r}async registerProvider(e,t){try{this.toolProviderRegistry.register(e,t);let r={providerName:t.provider.providerName};await this.hooks.onProviderRegistered?.(e,r),await this.emitTelemetry("pie-toolkit-provider-registered",{toolId:e,providerName:t.provider.providerName})}catch(r){this.reportProviderRegisterFailure(r,e)}}reportProviderRegisterFailure(e,t){console.warn(`[ToolkitCoordinator] Failed to register the provider of tool "${t}":`,e),this.reportToolFailure(e,{phase:"provider-register",toolId:t},[t])}async ensureProviderReady(e){return this.initializeProvider(e,!1)}async initializeProvider(e,t){this.assertNotDisposed();let r=this.providerInitPromises.get(e);if(r)return r;let n=(async()=>{try{let i=await this.toolProviderRegistry.getProvider(e,!1);if(this.assertNotDisposed(),this.toolProviderRegistry.isInitialized(e))return i;let o={providerName:i.providerName};return await this.hooks.onProviderInitStart?.(e,o),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(e),this.assertNotDisposed(),i=await this.toolProviderRegistry.getProvider(e,!1),await this.hooks.onProviderReady?.(e,o),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{toolId:e}),this.assertNotDisposed(),i}catch(i){if(i instanceof $i)throw i;let o=i instanceof Error?i:Error(String(i));throw this.reportToolFailure(o,{phase:"provider-init",toolId:e},this.toolRegistry.get(e)?.provider?[e]:[],t),o}})().finally(()=>{this.providerInitPromises.delete(e)});return this.providerInitPromises.set(e,n),n}setHooks(e){Object.assign(this.hooks,e),this.setupStatePersistenceHooks(),this.disposePromise===null&&e.onCoordinatorReady&&this.isReady()&&Promise.resolve(e.onCoordinatorReady(this)).catch(t=>{this.handleError(t,{phase:"coordinator-ready",recoverable:!1})})}subscribeTelemetry(e){return this.telemetryListeners.add(e),()=>{this.telemetryListeners.delete(e)}}getSectionController(e){let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(t))}subscribeSectionEvents(e){if(this.activeCohortMapKey===null&&this.latestRequestedActiveCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let t=this.activeSubscriptions.get(e.listener);t&&(t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null);let r={listener:e.listener,eventTypes:e.eventTypes,itemIds:e.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(e.listener,r);let n=this.activeCohortMapKey===null?void 0:this.sectionControllers.get(this.activeCohortMapKey);n&&this.bindSubscriptionToController(r,n);let i=!1;return()=>{i||(i=!0,r.unsubscribeCurrent?.(),r.unsubscribeCurrent=null,this.activeSubscriptions.get(e.listener)===r&&this.activeSubscriptions.delete(e.listener))}}bindSubscriptionToController(e,t){e.unsubscribeCurrent?.(),e.unsubscribeCurrent=null;let r=t.subscribe;if(typeof r!="function")return;let n=this.buildSectionEventPredicate(e);e.unsubscribeCurrent=r.call(t,s=>{n(s)&&this.deliverSectionEventSafely(e.listener,s)});let i=this.buildContentLoadedReplayEvents(t);for(let s of i)n(s)&&this.deliverSectionEventSafely(e.listener,s);let o=this.buildLoadingCompleteReplayEvent(t);o&&n(o)&&this.deliverSectionEventSafely(e.listener,o)}deliverSectionEventSafely(e,t){try{e(t)}catch(r){console.warn("[ToolkitCoordinator] section-event listener failed:",r)}}setActiveCohort(e){if(this.activeCohortMapKey===e)return;this.activeCohortMapKey=e;let t=this.sectionControllers.get(e);if(t)for(let r of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(r,t)}setActiveCohortIfLatestRequest(e){this.latestRequestedActiveCohortMapKey===e&&this.setActiveCohort(e)}suspendActiveCohortIfSuperseded(e){if(this.activeCohortMapKey!==null&&this.activeCohortMapKey!==e){this.activeCohortMapKey=null;for(let t of Array.from(this.activeSubscriptions.values()))t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null}}clearActiveCohortIfMatches(e){if(this.activeCohortMapKey===e){this.activeCohortMapKey=null;for(let t of Array.from(this.activeSubscriptions.values()))t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null}}buildSectionEventPredicate(e){let t=e.eventTypes?new Set(e.eventTypes):null,r=e.itemIds?new Set(e.itemIds):null;return n=>{if(t||r){let i=n?.type||null;if(t&&(!i||!t.has(i))||r&&!Array.from(this.collectEventItemIds(n)).some(o=>r.has(o)))return!1}return!0}}collectEventItemIds(e){let t=new Set;return"itemId"in e&&typeof e.itemId=="string"&&t.add(e.itemId),"canonicalItemId"in e&&typeof e.canonicalItemId=="string"&&t.add(e.canonicalItemId),"currentItemId"in e&&typeof e.currentItemId=="string"&&t.add(e.currentItemId),"previousItemId"in e&&typeof e.previousItemId=="string"&&t.add(e.previousItemId),t}buildContentLoadedReplayEvents(e){let t=e.getRuntimeState?.(),r=t?.loadedRenderables;if(!Array.isArray(r)||r.length===0)return[];let n=typeof t?.currentItemIndex=="number"&&Number.isFinite(t.currentItemIndex)?t.currentItemIndex:0,i=Date.now(),o=[];for(let s of r){if(!s)continue;let a=s.itemId,l=typeof s.canonicalItemId=="string"&&s.canonicalItemId?s.canonicalItemId:a;typeof a!="string"||!a||o.push({type:"content-loaded",contentKind:s.contentKind??"unknown",itemId:a,canonicalItemId:l,currentItemIndex:n,timestamp:i})}return o}buildLoadingCompleteReplayEvent(e){let t=e.getRuntimeState?.();if(t?.loadingComplete!==!0)return null;let r=typeof t.totalRegistered=="number"&&Number.isFinite(t.totalRegistered)?Math.max(0,t.totalRegistered):0;return{type:"section-loading-complete",totalRegistered:r,totalLoaded:typeof t.totalLoaded=="number"&&Number.isFinite(t.totalLoaded)?Math.max(0,t.totalLoaded):r,currentItemIndex:t.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(e){return this.subscribeSectionEvents({eventTypes:e.eventTypes||nG,itemIds:e.itemIds,listener:e.listener})}subscribeSectionLifecycleEvents(e){return this.subscribeSectionEvents({eventTypes:e.eventTypes||iG,listener:e.listener})}onSectionControllerLifecycle(e){return this.sectionControllerLifecycleListeners.add(e),()=>{this.sectionControllerLifecycleListeners.delete(e)}}async getOrCreateSectionController(e){if(this.disposePromise!==null)throw new $i;let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId},r=this.getSectionControllerMapKey(t);this.latestRequestedActiveCohortMapKey=r,this.suspendActiveCohortIfSuperseded(r);let n;try{if(n=await this.resolveExistingSectionController({mapKey:r,key:t,input:e.input,updateExisting:e.updateExisting}),n){if(this.disposePromise!==null)throw new $i;e.initialSession&&await this.assignSessionToPublishedController(n,e.initialSession)}}catch(l){throw this.deliverSectionStartError(r,l),l}if(n)return n;let i=this.sectionControllerDisposePromises.get(r);if(i&&await Promise.allSettled([i]),this.disposePromise!==null)throw new $i;let o=this.sectionControllerInitEntries.get(r);if(o){if(!e.initialSession)return o.promise;let l=await o.promise;return await this.assignSessionToPublishedController(l,e.initialSession),l}let s={retired:!1,candidateClaimed:!1},a=this.initializeNewSectionController({args:e,key:t,mapKey:r,token:s}).catch(l=>{throw this.handleSectionControllerInitError(l,e),this.deliverSectionStartError(r,l),l}).finally(()=>{this.sectionControllerInitEntries.get(r)?.token===s&&this.sectionControllerInitEntries.delete(r)});return this.sectionControllerInitEntries.set(r,{key:t,token:s,promise:a}),a}async resolveExistingSectionController(e){let t=this.sectionControllers.get(e.mapKey);if(t&&(this.sectionControllerKeys.set(e.mapKey,e.key),e.updateExisting!==!1&&await t.updateInput?.(e.input),this.sectionControllers.get(e.mapKey)===t))return this.setActiveCohortIfLatestRequest(e.mapKey),t}createSectionControllerContext(e){return{key:e.key,coordinator:this,input:e.input}}async initializeNewSectionController(e){let t=this.createSectionControllerContext({key:e.key,input:e.args.input}),r=await this.resolveSectionPersistence(t);if(this.disposePromise!==null||e.token.retired)throw this.sectionPersistenceStrategies.get(e.mapKey)===r&&this.sectionPersistenceStrategies.delete(e.mapKey),this.createSectionControllerRetirementError();let n={createDefaultController:e.args.createDefaultController},i=await this.hooks.createSectionController?.(t,n)??await n.createDefaultController(),o={mapKey:e.mapKey,key:e.key,controller:i,persistence:r,token:e.token};try{await this.retireUnpublishedSectionControllerIfNeeded(o),await i.configureSessionPersistence?.({strategy:r,context:t}),await this.retireUnpublishedSectionControllerIfNeeded(o),await i.initialize?.(e.args.input),await this.retireUnpublishedSectionControllerIfNeeded(o);let s=e.args.initialSession;if(s){if(!i.applySession)throw Error("Section controller cannot apply the session it was created with: it has no applySession.");await i.applySession(s,{mode:"replace"})}else await i.hydrate?.();return await this.finalizeSectionControllerReady({...o,context:t}),i}catch(s){throw await this.cleanupUnpublishedSectionController(o),s}}async assignSessionToPublishedController(e,t){if(!t)return;if(!e.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");let r=kA(e.getSession?.()??null,t);r&&await e.applySession(r,{mode:"replace"})}createSectionControllerRetirementError(){return this.disposePromise!==null?new $i:new xv}async retireUnpublishedSectionControllerIfNeeded(e){if(!(this.disposePromise===null&&!e.token.retired))throw await this.cleanupUnpublishedSectionController(e),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(e){if(!e.token.candidateClaimed){e.token.candidateClaimed=!0;try{await e.controller.dispose?.()}catch(t){this.handleError(t,{phase:"section-controller-dispose",details:{sectionId:e.key.sectionId,attemptId:e.key.attemptId},recoverable:!0})}finally{this.sectionPersistenceStrategies.get(e.mapKey)===e.persistence&&this.sectionPersistenceStrategies.delete(e.mapKey)}}}retirePublishedSectionControllerIfNeeded(e){if(this.disposePromise!==null&&!e.token.retired&&this.disposeSectionController({sectionId:e.key.sectionId,attemptId:e.key.attemptId}),e.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(e){await this.retireUnpublishedSectionControllerIfNeeded(e),this.sectionControllers.set(e.mapKey,e.controller),this.sectionControllerKeys.set(e.mapKey,e.key),e.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(e.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:e.key,controller:e.controller}),await this.hooks.onSectionControllerReady?.(e.context,e.controller),this.retirePublishedSectionControllerIfNeeded(e),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:e.key.assessmentId,sectionId:e.key.sectionId,attemptId:e.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(e)}handleSectionControllerInitError(e,t){e instanceof $i||e instanceof xv||this.handleError(e,{phase:"section-controller-init",details:{sectionId:t.sectionId,attemptId:t.attemptId},recoverable:!1},"cohort")}deliverSectionStartError(e,t){if(t instanceof $i||t instanceof xv||this.latestRequestedActiveCohortMapKey!==e)return;let r={type:"section-error",source:"section-runtime",error:t,currentItemIndex:0,timestamp:Date.now()};for(let n of Array.from(this.activeSubscriptions.values()))this.buildSectionEventPredicate(n)(r)&&this.deliverSectionEventSafely(n.listener,r)}disposeSectionController(e){let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId},r=this.getSectionControllerMapKey(t),n=this.sectionControllerInitEntries.get(r);n&&(n.token.retired=!0);let i=this.sectionControllers.get(r);if(!i){let c=this.sectionControllerDisposePromises.get(r);if(c)return c;if(!n)return Promise.resolve();let u=Promise.allSettled([n.promise]).then(()=>{});return this.trackSectionControllerDisposal(r,u)}let o=this.sectionPersistenceStrategies.get(r);this.clearActiveCohortIfMatches(r),this.sectionControllers.get(r)===i&&(this.sectionControllers.delete(r),this.sectionControllerKeys.delete(r),this.sectionPersistenceStrategies.delete(r),this.emitSectionControllerLifecycle({type:"disposed",key:t}));let s=this.createSectionControllerContext({key:t,input:void 0}),a=this.disposeSectionControllerEntry({args:e,key:t,context:s,controller:i,persistenceStrategy:o}),l=n?Promise.allSettled([n.promise]).then(()=>a):a;return this.trackSectionControllerDisposal(r,l)}trackSectionControllerDisposal(e,t){this.sectionControllerDisposePromises.set(e,t);let r=()=>{this.sectionControllerDisposePromises.get(e)===t&&this.sectionControllerDisposePromises.delete(e)};return t.then(r,r),t}async disposeSectionControllerEntry(e){try{await this.runSectionControllerDisposePipeline({key:e.key,context:e.context,controller:e.controller,persistBeforeDispose:e.args.persistBeforeDispose})}catch(t){this.handleError(t,{phase:"section-controller-dispose",details:{sectionId:e.args.sectionId,attemptId:e.args.attemptId},recoverable:!0})}finally{await this.finalizeSectionControllerDispose({context:e.context,persistenceStrategy:e.persistenceStrategy,clearPersistence:e.args.clearPersistence})}}async runSectionControllerDisposePipeline(e){let t=[];if(e.persistBeforeDispose!==!1)try{await e.controller.persist?.()}catch(r){t.push(r)}try{await e.controller.dispose?.()}catch(r){t.push(r)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(e.context,e.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:e.key.assessmentId,sectionId:e.key.sectionId,attemptId:e.key.attemptId})}async finalizeSectionControllerDispose(e){e.clearPersistence&&await e.persistenceStrategy?.clearSession?.(e.context)}dispose(){return this.disposePromise?this.disposePromise:(this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise)}async disposeOwnedResources(){let e=[],t=async n=>{try{await n()}catch(i){e.push(i)}};await this.waitForAdmittedInitialization();let r=new Map;for(let[n,i]of this.sectionControllerInitEntries)r.set(n,i.key);for(let[n,i]of this.sectionControllerKeys)r.set(n,i);for(let n of r.values())this.disposeSectionController({sectionId:n.sectionId,attemptId:n.attemptId});await Promise.allSettled(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let n of this.activeSubscriptions.values())await t(()=>n.unsubscribeCurrent?.()),n.unsubscribeCurrent=null;this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await t(()=>this.ttsService.dispose()),await t(()=>this.toolProviderRegistry.destroy()),await t(()=>this.highlightCoordinator.destroy());for(let n of this.toolCoordinator.getRegisteredTools())await t(()=>this.toolCoordinator.releaseTool(n));if(await t(()=>this.catalogResolver.destroy()),await t(()=>this.toolRequests.dispose()),await t(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus&&this.frameworkErrorBus.dispose(),e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let e=new Set;this.coordinatorReadyPromise&&e.add(this.coordinatorReadyPromise),this.ttsInitPromise&&e.add(this.ttsInitPromise),this.ttsReconfigurePromise&&e.add(this.ttsReconfigurePromise);for(let t of this.providerInitPromises.values())e.add(t);await Promise.allSettled(e)}async ensureTTSReady(e){if(this.assertNotDisposed(),await this.waitForPendingTTSReconfigure(),this.assertNotDisposed(),!this.ttsInitialized)return this.ttsInitPromise?this.ttsInitPromise:(this.ttsInitPromise=this._initializeTTS(e).then(()=>this.assertNotDisposed()).finally(()=>{this.ttsInitPromise=void 0,this.notifyReadyChange()}),this.ttsInitPromise)}async waitForPendingTTSReconfigure(){let e=this.ttsReconfigurePromise;for(;e;)await e,e=this.ttsReconfigurePromise}async _initializeTTS(e){if(this.ttsInitialized)return;let t=hT(this.resolveTTSToolConfig(e)),r=bA(t),n=pT(t);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:r}}),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:r}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:r}),this.toolProviderRegistry.has("textToSpeech"))try{let o=await(await this.initializeProvider("textToSpeech",!0)).createInstance();await this.initializeTTSService(o,n),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:r,provider:"registry"});return}catch(o){if(o instanceof $i)throw o;let s=o instanceof Error?o:Error(String(o));await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",operation:"tts-init",backend:r,fromProvider:"registry",toProvider:"browser",reason:s.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",s)}else r!=="browser"&&this.reportMissingTTSProvider(r);let i=new DV;try{await this.initializeTTSService(i,r==="browser"?n:AV(n)),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:r,provider:"browser-fallback"})}catch(o){if(o instanceof $i)throw o;let s=o instanceof Error?o:Error(String(o));throw this.reportToolFailure(s,{phase:"tts-init"},["textToSpeech"]),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:s.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:r,errorType:"TTSInitError",message:s.message}),s}}resolveTTSToolConfig(e){return e||this.getTTSConfigFromProviders()||{}}async initializeTTSService(e,t){let r={...t.providerOptions,__pieTelemetry:async(i,o)=>{await this.emitTelemetry(i,{toolId:"textToSpeech",...o||{}})}},n={...t,providerOptions:r};await this.ttsService.initialize(e,n),this.assertNotDisposed(),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,this.ttsDegraded=!1,this.degradedTools.delete("textToSpeech"),await this.hooks.onTTSReady?.(),this.assertNotDisposed()}async waitUntilReady(){if(this.assertNotDisposed(),!this.isReady())return this.coordinatorReadyPromise?this.coordinatorReadyPromise:(this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded(),this.assertNotDisposed(),this.ttsRequiredForReadiness()&&await this.startTTSForReadiness(),this.assertNotDisposed(),!this.coordinatorReadyNotified&&(this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId}))})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise)}isReady(){return(this.stateLoadSettled||!this.hooks.loadToolState)&&(this.ttsInitialized||this.ttsDegraded||!this.ttsRequiredForReadiness())}ttsRequiredForReadiness(){return this.getTTSConfigFromProviders()?.enabled===!1?!1:!this.lazyInit||this.isToolGranted("textToSpeech")}async startTTSForReadiness(){try{await this.ensureTTSReady(this.getTTSConfigFromProviders())}catch(e){if(e instanceof $i||this.isToolGranted("textToSpeech"))throw e;this.ttsDegraded=!0,this.notifyReadyChange()}}getTTSConfigFromProviders(){return this.config.tools?.providers?.textToSpeech}assertCanonicalToolId(e){if(typeof e!="string"||e.trim().length===0)throw Error("Tool id must be a non-empty string.");if(this.toolRegistry.getAllToolIds().length!==0&&!this.toolRegistry.get(e))throw Error(`Unknown tool id "${e}".`)}installToolContextResolvers(e){if(e){for(let[t,r]of Object.entries(e))if(r!=null){if(this.assertCanonicalToolId(t),typeof r!="function")throw Error(`Invalid tool context resolver for "${t}": expected a function.`);this.toolContextResolvers.set(t,r)}}}setToolContextResolvers(e){this.toolContextResolvers.clear(),this.installToolContextResolvers(e??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let e of this.toolContextResolverChangeListeners)try{e()}catch(t){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",t)}}getToolConfig(e){return this.assertCanonicalToolId(e),this.config.tools?.providers?.[e]||null}updateToolConfig(e,t){this.assertCanonicalToolId(e);let r=this.getToolConfig(e)||{};this.config.tools||(this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry})),this.config.tools.providers||(this.config.tools.providers={});let n={...this.config.tools.providers||{},[e]:rG(e,r,t)};this.config.tools=this.validateToolsConfig({...this.config.tools,providers:n},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}),this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:e}),this._applyToolConfigChange(e)}updateToolsPlacement(e){this.config.tools||(this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}));let t=this.config.tools?.placement??{section:[],item:[],passage:[]},r={section:[...e.section??t.section??[]],item:[...e.item??t.item??[]],passage:[...e.passage??t.passage??[]]},n=this.validateToolsConfig({...this.config.tools,placement:r},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});n.placement=r,this.config.tools=n,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(e){let t=this.policyEngine.decide(e);return this.warnPolicyDiagnostics(t.diagnostics),t}warnPolicyDiagnostics(e){for(let t of e){let r=t.code==="tool-policy.itemSettingNotApplied"?t.details.itemId:"",n=`${t.code}\0${t.toolId}\0${r}`;this.warnedPolicyDiagnostics.has(n)||(this.warnedPolicyDiagnostics.add(n),console.warn(`[ToolkitCoordinator] ${t.message}`))}}registerItemSettings(e,t){return this.policyEngine.registerItemSettings(e,t)}decideFeaturePolicy(e,t){let r=this.policyEngine.decideFeature(e,t);this.warnPolicyDiagnostics(r.diagnostics);let n=this.config.assessmentOptional!==!0||this.pnpEnforcementOverride==="on";return!r.assessmentBound&&n&&!this.reportedUnboundFeaturePolicy&&(this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${e}" 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.`)),r}onPolicyChange(e){return this.policyEngine.onPolicyChange(e)}onCatalogsChange(e){return this.catalogResolver.onCatalogsChange(e)}updateAssessment(e){this.policyEngine.updateInputs({assessment:e})}setPnpEnforcement(e){this.pnpEnforcementOverride=e,this.policyEngine.updateInputs({pnpEnforcement:e})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(e){return this.policyEngine.registerPolicySource(e)}hasToolContextResolver(e){return this.assertCanonicalToolId(e),this.toolContextResolvers.has(e)}resolveToolContext(e){this.assertCanonicalToolId(e.toolId);let t=this.toolContextResolvers.get(e.toolId);if(!t)return null;let r;try{r=t(e)}catch(i){return console.error(`[ToolkitCoordinator] Tool context resolver for "${e.toolId}" threw:`,i),{toolId:e.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!r)return{toolId:e.toolId,visible:!0,params:{}};let n=r.params&&typeof r.params=="object"&&!Array.isArray(r.params)?r.params:{};return{toolId:e.toolId,visible:r.visible!==!1,params:n,reason:typeof r.reason=="string"?r.reason:void 0}}onToolContextResolverChange(e){return this.toolContextResolverChangeListeners.add(e),()=>{this.toolContextResolverChangeListeners.delete(e)}}getToolRegistry(){return this.toolRegistry}registerToolRequestTarget(e){return this.toolRequests.registerTarget(e)}requestTool(e){return this.assertCanonicalToolId(e.toolId),this.toolRequests.request(e)}canRequestTool(e,t,r){try{this.assertCanonicalToolId(e)}catch{return!1}return this.toolRequests.canRequest(e,t,r)}onToolRequestTargetsChange(e){return this.toolRequests.onTargetsChange(e)}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(e){if(this.disposePromise===null){if(e==="textToSpeech"){this.scheduleTTSReconfigure();return}this._registerChangedToolProvider(e)}}_registerChangedToolProvider(e){let t=this.getProviderDescriptorTools().find(r=>r.toolId===e);t&&(this.degradedTools.delete(e),this.registerProviderFromTool(t,!0))}scheduleTTSReconfigure(){let e=this.ttsInitPromise,t=e?e.catch(()=>{}).then(()=>this._reconfigureTTSProvider()):this._reconfigureTTSProvider();this.ttsReconfigurePromise=t,t.finally(()=>{this.ttsReconfigurePromise===t&&(this.ttsReconfigurePromise=void 0)}),t.then(async()=>{this.disposePromise===null&&this.ttsRequiredForReadiness()&&await this.startTTSForReadiness()}).catch(()=>{})}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsDegraded=!1,this.degradedTools.delete("textToSpeech"),this.ttsInitPromise=void 0,this.notifyReadyChange();try{this.ttsService.releaseProvider()}catch{}if(this.toolProviderRegistry.has("textToSpeech")&&await this.toolProviderRegistry.unregister("textToSpeech"),this.disposePromise!==null)return;let e=this.getProviderDescriptorTools().find(t=>t.toolId==="textToSpeech");e&&await this.registerProviderFromTool(e)}},sG=()=>{};function TA(e){return e===Tt.PLAYING||e===Tt.LOADING}function aG(e){let{ttsService:t,silence:r}=e;if(typeof t?.onStateChange!="function")return sG;let n=t.onStateChange(i=>{TA(i)&&r()});return()=>{try{n()}catch{}}}function lG(e){try{TA(e?.getState?.())&&e?.pause?.()}catch{}}function cG(e,t,r){let n=e.detail?.runtimeId;return typeof n=="string"&&n!==""?n===t:r(e.target)}function uG(e,t,r){let n=[e.catalogResolver.registerOwner({owner:{kind:t.kind,itemId:t.itemId,canonicalItemId:t.canonicalItemId,assessmentId:r.assessmentId,sectionId:r.sectionId},entity:t.item})];return t.kind==="item"&&t.settings&&n.push(e.registerItemSettings(t.canonicalItemId||t.itemId,t.settings)),n}var dG=["a[href]","button","label","summary",...["button","checkbox","combobox","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","switch","tab","treeitem"].map(e=>`[role="${e}"]`)].join(", "),bT=new Set(["mi","mn","mtext"]),fG=e=>bT.has(e.localName)||e.localName==="mrow"&&e.children.length===1&&bT.has(e.children[0].localName),hG=e=>Array.from(e.getElementsByTagName("mfrac")).every(t=>Array.from(t.children).every(fG))?"Fraction_Over":"Fraction_General",pG=e=>!e||e.toLowerCase().split("-")[0]==="en";function mG(e,t={}){if(typeof MutationObserver>"u")return()=>{};let r=new Map,n=!1,i=async(u,d,f)=>{let h=await bw([{type:"math",mathml:u,fallbackText:""}],{language:f,loadSre:t.loadSre,mathSpeech:{...pG(f)?{style:hG(d)}:{},engineOptions:t.getMathSpeech?.()?.engineOptions}});return h.usedMathSpeech?h.speechText:null},o=u=>{if(!Bk(u,dG))return;let d=ng(u,"math"),f=d&&up(d.outerHTML);if(!d||!f)return;let h=Aq(u,{contentLanguage:t.getContentLanguage?.()}),g=`${h??""}\0${f}`,m=r.get(g);m||(m=i(f,d,h),r.set(g,m)),m.then(v=>{n||!v||!u.isConnected||u.getAttribute("aria-label")!==v&&u.setAttribute("aria-label",v)})},s=new WeakSet,a=u=>{s.has(u)||(s.add(u),c.observe(u,{childList:!0,subtree:!0}))},l=u=>{if(u.nodeType!==1)return;let d=u,f=Bk(d,"mjx-container");if(f){o(f);return}d.shadowRoot&&a(d.shadowRoot),rg(d,h=>{if(h.nodeType!==1)return"skip";let g=h;if(g.localName==="mjx-container")return o(g),"skip";g.shadowRoot&&a(g.shadowRoot)})},c=new MutationObserver(u=>{for(let d of u)for(let f of d.addedNodes)l(f)});return a(e),l(e),()=>{n=!0,c.disconnect()}}function gG(e,t){if(e===t)return 0;let r=e.compareDocumentPosition(t);return r&Node.DOCUMENT_POSITION_PRECEDING?1:r&Node.DOCUMENT_POSITION_FOLLOWING?-1:0}var vG=class{constructor(){T(this,"shellsByElement",new Map)}register(e){let t=this.shellsByElement.get(e.element),r={...e,sortKey:Date.now()};return t&&t.kind===r.kind&&t.itemId===r.itemId&&t.canonicalItemId===r.canonicalItemId?!1:(this.shellsByElement.set(e.element,r),!0)}unregister(e){return this.shellsByElement.delete(e)}getOrderedShells(e){let t=Array.from(this.shellsByElement.values()).filter(r=>!e||r.kind===e);return t.sort((r,n)=>gG(r.element,n.element)),t}getCanonicalIdMap(){let e={};for(let t of this.getOrderedShells("item"))t.itemId&&(e[t.itemId]=t.canonicalItemId||t.itemId);return e}clear(){this.shellsByElement.clear()}},wT=ei("section-controller-binding",()=>za());function yG(e){let t=e?.renderables;if(!Array.isArray(t))return null;let r=new Set;for(let n of t){let i=n?.entity?.id;typeof i=="string"&&i&&r.add(i)}return r}var bG=class{constructor(){T(this,"registry",new vG),T(this,"controller",null),T(this,"coordinator",null),T(this,"sectionId",""),T(this,"attemptId",void 0),T(this,"unsubscribeController",null),T(this,"activeInitToken",0),T(this,"sectionRenderableIds",null),T(this,"boundSections",new Map),T(this,"loadedRenderableKeys",new Set)}async initialize(e){this.activeInitToken+=1;let t=this.activeInitToken;this.coordinator=e.coordinator,this.sectionId=e.sectionId,this.attemptId=e.attemptId,this.forgetUnregisteredLoads(e.coordinator.getSectionController({sectionId:e.sectionId,attemptId:e.attemptId}));let r;try{r=await e.coordinator.getOrCreateSectionController({sectionId:e.sectionId,attemptId:e.attemptId,input:{section:e.section,sectionId:e.sectionId,assessmentId:e.assessmentId,view:e.view},updateExisting:!0,initialSession:e.initialSession,createDefaultController:e.createDefaultController})}catch(i){throw t===this.activeInitToken&&(this.unsubscribeController?.(),this.unsubscribeController=null,this.controller=null),i}if(t!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=r,this.sectionRenderableIds=yG(r.getCompositionModel?.());let n=this.getSectionKey(e.sectionId,e.attemptId);this.boundSections.delete(n),this.boundSections.set(n,{sectionId:e.sectionId,attemptId:e.attemptId,renderableIds:this.sectionRenderableIds}),this.replayRegisteredShellsIntoController(r),e.onCompositionChanged?.(r.getCompositionModel?.()),this.unsubscribeController=r.subscribe?.(i=>{try{e.onControllerEvent?.(i)}catch(o){wT.warn("onControllerEvent handler threw",o)}e.onCompositionChanged?.(r.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(e){if(!e.handleContentRegistered)return;let t=this.registry.getOrderedShells().filter(n=>this.isSectionRenderable(n));if(t.length===0)return;for(let n of t){let i=n.canonicalItemId||n.itemId;e.handleContentRegistered({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind})}let r=Date.now();for(let n of t){let i=n.canonicalItemId||n.itemId,o=this.getLoadedKey(i,n.contentKind);this.loadedRenderableKeys.has(o)&&e.handleContentLoaded?.({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind,timestamp:r})}}getLoadedKey(e,t){return`${t??""}:${e}`}isSectionRenderable(e){let t=this.sectionRenderableIds;return t?t.has(e.itemId)||!!e.canonicalItemId&&t.has(e.canonicalItemId):!0}getSectionKey(e,t){return`${e}\0${t??""}`}controllerFor(e){if(this.isSectionRenderable(e))return this.controller;let t=this.getSectionKey(this.sectionId,this.attemptId),r=[...this.boundSections.entries()].reverse();for(let[n,i]of r){if(n===t||!i.renderableIds||!i.renderableIds.has(e.itemId)&&!(e.canonicalItemId&&i.renderableIds.has(e.canonicalItemId)))continue;let o=this.coordinator?.getSectionController({sectionId:i.sectionId,attemptId:i.attemptId});if(o)return o}return null}requireControllerFor(e,t){let r=this.controllerFor(e);return r||wT.warn(`Dropped ${t} for "${e.itemId}": no section this toolkit bound renders it.`),r}forgetUnregisteredLoads(e){if(!e||e===this.controller)return;let t=e.getRuntimeState?.()?.loadedRenderables??[];if(t.length===0)return;let r=new Set;for(let n of this.registry.getOrderedShells())r.add(n.itemId),n.canonicalItemId&&r.add(n.canonicalItemId);for(let n of t)r.has(n.canonicalItemId)||r.has(n.itemId)||e.handleContentUnregistered?.({itemId:n.itemId,canonicalItemId:n.canonicalItemId,contentKind:n.contentKind})}register(e){return this.registry.register(e)}unregister(e){return this.registry.unregister(e)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(e){return this.registry.getCanonicalIdMap()[e]||this.controller?.getCanonicalItemId?.(e)||e}handleContentRegistered(e){this.isSectionRenderable(e)&&this.controller?.handleContentRegistered?.({itemId:e.itemId,canonicalItemId:e.canonicalItemId||e.itemId,contentKind:e.contentKind||e.kind})}handleContentUnregistered(e){let t=e.canonicalItemId||e.itemId,r=this.getLoadedKey(t,e.contentKind);this.registry.getOrderedShells().some(n=>this.getLoadedKey(n.canonicalItemId||n.itemId,n.contentKind)===r)||(this.loadedRenderableKeys.delete(r),this.controllerFor(e)?.handleContentUnregistered?.({itemId:e.itemId,canonicalItemId:t,contentKind:e.contentKind||e.kind}))}handleContentLoaded(e){let t=e.canonicalItemId||e.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(t,e.contentKind)),this.isSectionRenderable(e)&&this.controller?.handleContentLoaded?.(e)}handleItemPlayerError(e){this.requireControllerFor(e,"an item player error")?.handleItemPlayerError?.(e)}reportSectionError(e){(e.itemId?this.requireControllerFor({itemId:e.itemId,canonicalItemId:e.canonicalItemId},"a section error"):this.controller)?.reportSectionError?.(e)}updateItemSession(e,t){let r=this.getCanonicalItemId(e);return this.requireControllerFor({itemId:e,canonicalItemId:r},"a session update")?.updateItemSession?.(r,t)??null}navigateToItem(e){return this.controller?.navigateToItem?.(e)??null}handleFormativeAction(e){if(!e?.itemId)return;let t=e.canonicalItemId||this.getCanonicalItemId(e.itemId),r=this.requireControllerFor({itemId:e.itemId,canonicalItemId:t},"a formative action");if(e.action==="retry"){r?.retryFormativeItem?.({itemId:t});return}r?.recordFormativeTry?.({itemId:t,outcomes:e.outcomes})}handleMediaTimeSource(e){if(!e?.renderableId)return;let t=this.requireControllerFor({itemId:e.renderableId,canonicalItemId:this.getCanonicalItemId(e.renderableId)},"a media time source");if(e.action==="detach"){t?.detachMediaTimeSource?.({origin:e.origin??"host"});return}e.source&&t?.attachMediaTimeSource?.(e.source,{origin:e.origin??"host",renderableId:e.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(){this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId&&await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId}),this.registry.clear(),this.loadedRenderableKeys.clear(),this.boundSections.clear(),this.controller=null,this.sectionRenderableIds=null,this.coordinator=null}};function wG(e){let t=e.section?.identifier;return e.sectionId||(typeof t=="string"?t:"")||`section-${e.assessmentId||"default"}`}function SG(e,t){return["pnpEnforcement","assessment"].filter(r=>e?!Object.is(e[r],t[r]):t[r]!==null)}function IG(e){if(!e)return;let t=Symbol.for("pie.assessmentToolkit.unclaimedRegistrationWatch"),r=e;r[t]||(r[t]=!0,e.addEventListener(_p,n=>{let i=n.detail,o=typeof i?.itemId=="string"?i.itemId:"";Vd(e,"unclaimedRegistration",`[pie-assessment-toolkit] Item "${o}" registered, but no toolkit claimed the registration, so its accessibility catalogs are not filed and it does not count toward its section's loading. Render its shell or scope inside the <pie-assessment-toolkit> that answered it. Reported once per page.`)}))}function nd(e,t){return typeof e=="function"?e:e===null?null:typeof t=="function"?t:null}function kG(e={}){let t=e.frameDeadlineMs??100,r=!1,n=null,i=null,o=null,s=null,a=null;function l(){r=!1,i!==null&&(s?.(i),i=null),o!==null&&(a?.(o),o=null),s=null,a=null}function c(f){if(!r)return;f==="frame"&&(i=null),f==="timer"&&(o=null);let h=n;n=null,l(),h?.()}function u(f){if(n=f,r)return;r=!0;let h=globalThis,g=nd(e.requestFrame,h.requestAnimationFrame);s=nd(e.cancelFrame,h.cancelAnimationFrame);let m=nd(e.setTimer,h.setTimeout);if(a=nd(e.clearTimer,h.clearTimeout),g){let b=g(()=>c("frame"));if(!r)return;if(i=b,m){let I=m(()=>c("timer"),t);r&&(o=I)}return}let v=nd(e.queueMicrotaskFn,h.queueMicrotask);if(v){v(()=>c("microtask"));return}if(m){let b=m(()=>c("timer"),0);r&&(o=b);return}c("microtask")}function d(){r&&(n=null,l())}return{schedule:u,cancel:d,isPending:()=>r}}function TG(e="runtime"){return`${e}-${Math.random().toString(16).slice(2)}-${Date.now()}`}function EG(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function CG(e){e.lastSessionEventSignatureByItemId.clear(),e.lastMetadataSignatureByItemId.clear()}function xG(e){let{state:t,itemId:r,payload:n}=e;if(PG(n)){let o=_G(n);if(t.lastMetadataSignatureByItemId.get(r)===o)return!1;t.lastMetadataSignatureByItemId.set(r,o)}let i=RG(n);return t.lastSessionEventSignatureByItemId.get(r)===i?!1:(t.lastSessionEventSignatureByItemId.set(r,i),!0)}function RG(e){let t={...e};delete t.timestamp,delete t.sourceRuntimeId;try{return JSON.stringify(t)}catch{return String(t.itemId||"")}}function PG(e){return e.intent==="metadata-only"}function _G(e){try{return JSON.stringify({itemId:e.itemId,canonicalItemId:e.canonicalItemId,intent:e.intent,complete:e.complete??null,component:e.component??null})}catch{return String(e.itemId||"")}}var AG=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},$G=xi('<div class="pie-assessment-toolkit-error svelte-15pthty" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-15pthty"> </div> <div class="pie-assessment-toolkit-error-message svelte-15pthty"> </div> <pre class="pie-assessment-toolkit-error-details svelte-15pthty"> </pre></div>'),MG=xi('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),OG={hash:"svelte-15pthty",code:`.pie-assessment-toolkit-anchor.svelte-15pthty {display:none;}.pie-assessment-toolkit-error.svelte-15pthty {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
1652
+ color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-15pthty {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-15pthty {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-15pthty {margin:0;white-space:pre-wrap;word-break:break-word;}`};function LG(e,t){Ef(t,!0),m0(e,OG);let r=ei("pie-assessment-toolkit",()=>za()),n=TG("toolkit"),i=new bG,o=new A_,s={mode:"gather",role:"student"},a={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},l=dt(t,"assessmentId",7,""),c=dt(t,"section",7,null),u=dt(t,"sectionId",7,""),d=dt(t,"attemptId",7,""),f=dt(t,"env",23,()=>({})),h=dt(t,"ndsIcons",7,!1),g=dt(t,"locale",7,""),m=dt(t,"contentLanguage",7,""),v=dt(t,"lazyInit",7,!1),b=dt(t,"toolConfigStrictness",7,"error"),I=dt(t,"tools",23,()=>({})),C=dt(t,"toolContextResolvers",7,null),x=dt(t,"enabledTools",7,""),$=dt(t,"toolRegistry",7,null),P=dt(t,"accessibility",23,()=>({})),L=dt(t,"player",7,null),J=dt(t,"playerType",7,""),V=dt(t,"coordinator",7,null),Y=dt(t,"createSectionController",7,null),Pe=dt(t,"onFrameworkError",7,null),M=dt(t,"errorRenderer",7,null),H=dt(t,"assessment",7,null),ne=dt(t,"isolation",7,"inherit"),ae=dt(t,"session",7,null),ye=Lr(null),te=Lr(null),z=Lr(null),A=null,K=null,Q=!1,_=null,B=null,U=null,fe=Lr(0),W=Lr(null),se=Lr(null),_e=Lr("Unable to initialize assessment toolkit."),Ue=Lr(Ea([])),it="",le="",de=null,Ne=null,Ae=null,ce=null,ie=null,De=null,Je=null,At=!1,pt=null,Et=!1,Re=Lr(""),Ze=null,Ye=kG(),yt=[],re=new Map,Qe=new WeakMap,lt=new Map,zt=EG(),Vt=Lr(!1);function ur(){if(!y(ye))return null;let k=y(ye).getRootNode();return k&&"host"in k?k.host:y(ye).parentElement}let st=Xe(()=>ur());function Rt(k,F){if(!y(st)){yt=[...yt,{name:k,detail:F}];return}Wd(y(st),k,F)}Ot(()=>{if(!y(st)||yt.length===0)return;let k=yt;yt=[],queueMicrotask(()=>{let F=y(st);if(!F){yt=[...k,...yt];return}for(let Oe of k)Wd(F,Oe.name,Oe.detail)})});function bt(k){if(!M())return{title:"Unable to initialize assessment toolkit.",details:k.details.length>0?k.details:[k.message]};try{let F=M()(k)||{};return{title:typeof F.title=="string"&&F.title.trim().length>0?F.title:"Unable to initialize assessment toolkit.",details:Array.isArray(F.details)&&F.details.length>0?F.details.map(Oe=>String(Oe)):k.details.length>0?k.details:[k.message]}}catch(F){let Oe=F instanceof Error&&F.message.trim().length>0?F.message:String(F||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...k.details,`Error renderer failed: ${Oe}`]}}}function ft(k){let F=k_({kind:k.kind,source:k.source,error:k.error,recoverable:k.recoverable,scope:k.scope});return o.reportFrameworkError(F),F}function me(k){if(k?.type==="timed-media-policy-degraded"){let Oe=k.degradations||[];o.reportFrameworkError(ab({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:Oe.map(je=>je?.message).filter(je=>typeof je=="string"),recoverable:!0,scope:"cohort"}));return}if(k?.type!=="timed-media-invalid")return;let F=k.errors||[];o.reportFrameworkError(ab({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:F.map(Oe=>Oe?.message).filter(Oe=>typeof Oe=="string"),recoverable:!1,scope:"cohort"}))}function Nt(k){k?.type==="timed-media-audio-started"&&y(X)&&lG(y(X).ttsService)}function tr(k){return k==="coordinator-init"||k==="runtime-init"||k==="tool-config"}function mt(k){return`${k.kind}|${k.source}|${k.message}`}function vr(k){if(Pe())try{Pe()(k),it=mt(k)}catch(F){console.error(`[pie-framework:${k.kind}:${k.source}] framework error hook failed`,F)}}let dr=new WeakSet,Ir=new WeakMap;function Qt(k){return typeof k!="object"||k===null?null:Ir.get(k)??null}function Nr(k){let F=bt(k);Ut(se,k,!0),Ut(_e,F.title,!0),Ut(Ue,F.details,!0)}function on(){Ut(se,null),Ut(_e,"Unable to initialize assessment toolkit."),Ut(Ue,[],!0)}Ot(()=>{let k=o.subscribeFrameworkErrors(F=>{console.error(tq(F),F.cause),typeof F.cause=="object"&&F.cause!==null&&Ir.set(F.cause,F),tr(F.kind)&&!dr.has(F)&&Nr(F),Rt("framework-error",F),vr(F)});return()=>{k()}}),Ot(()=>{let k=V();if(!(!k||y(X)!==k)&&typeof k.subscribeFrameworkErrors=="function")return Wr(()=>k.subscribeFrameworkErrors(F=>{dr.add(F),o.reportFrameworkError(F)}))}),Ot(()=>{let k=y(X),F=$();!k||y(ee)||typeof k.adoptToolRegistry=="function"&&Wr(()=>{let Oe=k===y(te);Oe&&!F||k.adoptToolRegistry(F)&&Oe&&de&&(de={...de,toolRegistry:F})})}),Ot(()=>{y(se)&&it!==mt(y(se))&&vr(y(se))});function Or(k){let F=5381;for(let Oe=0;Oe<k.length;Oe+=1)F=(F<<5)+F^k.charCodeAt(Oe);return(F>>>0).toString(36)}function yr(k){return k&&typeof k=="object"?k:{}}function fn(k){let F=yr(k.section),Oe=typeof F.identifier=="string"?F.identifier:"",je=typeof k.sectionId=="string"?k.sectionId:"";return Oe||je}function or(k){return typeof k.currentItemIndex=="number"?k.currentItemIndex:-1}function j(k){return(Array.isArray(k.renderables)?k.renderables:[]).map((F,Oe)=>{let je=yr(yr(F).entity),Se=typeof je.id=="string"&&je.id||`renderable-${Oe}`,E=yr(je.config);return{id:Se,version:typeof je.version=="string"&&je.version||(typeof je.version=="number"?String(je.version):"")||(typeof E.version=="string"?E.version:"")}})}function ke(k){let F=yr(k.itemSessionsByItemId);return Object.keys(F).sort((Oe,je)=>Oe.localeCompare(je)).map(Oe=>{let je=yr(F[Oe]),Se=typeof je.id=="string"?je.id:"",E=Array.isArray(je.data)?je.data:[],ue="";try{ue=Or(JSON.stringify(E))}catch{ue=String(E.length)}return{itemId:Oe,sessionId:Se,payloadSignature:ue}})}function Fe(k){let F=yr(yr(k.formative).states);return Object.entries(F).map(([Oe,je])=>{let Se=yr(je),E=yr(Se.lastOutcome).correctness??"";return`${Oe}:${Se.tryCount??0}:${Se.revealed===!0?1:0}:${String(E)}:${String(Se.revealOverride??"")}`}).sort().join("|")}function Ve(k){let F=k.timedMedia;return g_(F)}function Ft(k){let F=yr(k),Oe=j(F).map(Se=>`${Se.id}:${Se.version}`).join("|"),je=ke(F).map(Se=>`${Se.itemId}:${Se.sessionId}:${Se.payloadSignature}`).join("|");return{sectionId:fn(F),currentItemIndex:or(F),renderableSignature:Oe,itemSessionSignature:je,formativeSignature:Fe(F),timedMediaSignature:Ve(F)}}function Pr(k){let F=Ft(k);return`${F.sectionId}|${F.currentItemIndex}|${F.renderableSignature}|${F.itemSessionSignature}|${F.formativeSignature}|${F.timedMediaSignature}`}function en(k){return k==="iife"||k==="esm"||k==="preloaded"||k==="custom"}function En(k,F){let Oe=k?.type,je=en(Oe)?Oe:en(F)?F:k?.tagName?"custom":"iife",Se=k?.tagName?.trim();return je==="custom"&&!Se?{type:"iife",tagName:a.iife,version:void 0,source:void 0,isDefault:!0}:{type:je,tagName:Se||a[je],version:k?.version,source:k?.source,loaderConfig:k?.loaderConfig,loaderOptions:k?.loaderOptions,isDefault:!k&&!F}}function ri(k){let F=k||{};return{mode:typeof F.mode=="string"&&F.mode.trim()?F.mode.trim():s.mode,role:typeof F.role=="string"&&F.role.trim()?F.role.trim():s.role}}function ko(k){let F=ri(k);return F.mode==="author"?"author":F.role==="instructor"?"scorer":"candidate"}function ge(k,F){return k.sectionId===F.sectionId&&k.attemptId===F.attemptId}function fr(){!ae()||ae()===ce||(ce=ae(),Ae={value:ae(),cohort:{sectionId:y(et),attemptId:d()||void 0}})}function Nn(k,F){fr();let Oe=Ae;return Oe?ge(Oe.cohort,k)?(Ae=null,Oe.value):(F&&(Ae=null),null):null}function _r(){let k=ie,F=y(X);if(!k||!F)return;let Oe=Nn(k,!1);if(!Oe)return;let je=F.getSectionController(k);if(!je)return;let Se=kA(je.getSession?.()??null,Oe);Se&&Promise.resolve().then(()=>{if(!je.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");return je.applySession(Se,{mode:"replace"})}).catch(E=>{ft({kind:"unknown",source:"pie-assessment-toolkit",error:E,recoverable:!0})})}async function Ji(){if(Y())return Y()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function ni(){let k=I()||{},F=Rx(x());if(F.length===0)return k;let Oe=k.placement||{},je=Array.isArray(Oe.section)?Oe.section:null;return je&&je.length>0?k:{...k,placement:{...Oe,section:F}}}function Os(){return uq(ni(),{strictness:b(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:$()}).config}function Vn(){let k="",F="";try{k=JSON.stringify(ni())}catch{k="[unserializable-tools]"}try{F=JSON.stringify(Object.entries(C()??{}).map(([Oe,je])=>[Oe,typeof je]))}catch{F="[unserializable-resolvers]"}return[l()||"",String(b()||"error"),k,F].join("|")}function ua(k){let F=k?.pnpEnforcement;return F==="on"||F==="off"?F:null}function ns(k){let F=l()||c()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new oG({assessmentId:F,lazyInit:v(),eagerInit:!1,toolConfigStrictness:b(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:k,toolRegistry:$(),toolContextResolvers:C(),accessibility:P(),frameworkErrorBus:o})}function Qi(k){try{return JSON.stringify(k??null)}catch{return"[unserializable]"}}function Zi(){return{signatures:{assessmentId:l()||"",toolConfigStrictness:String(b()||"error"),lazyInit:String(v()),tools:Qi({...ni(),pnpEnforcement:void 0}),accessibility:Qi(P())},toolRegistry:$()}}function Ls(){let k=de;if(!k)return[];let F=Zi(),Oe=Object.keys(F.signatures).filter(je=>F.signatures[je]!==k.signatures[je]);return k.toolRegistry&&F.toolRegistry!==k.toolRegistry&&Oe.push("toolRegistry"),Oe}function is(k,F){At||(At=!0,console.warn(`[pie-assessment-toolkit] ${k.join(", ")} changed after ${F} with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section or the first item scope, pass a coordinator of your own, or update this one from runtime-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`))}function Ri(k){Et||(Et=!0,console.warn(`[pie-assessment-toolkit] The toolkit above this one (runtime "${k}") had no coordinator when this one connected, so this one built its own and keeps it: the two share no tool state, policy or read-aloud. Give the outer toolkit its coordinator before the inner one connects, or set isolation="force" on the inner one to keep them apart on purpose. Reported once per toolkit.`))}function Un(){let k=y(te);return k?(Ut(te,null),k.dispose()):Promise.resolve()}function O(k){ft({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:k,recoverable:!0})}let ee=Xe(()=>!V()&&ne()!=="force"&&y(z)?.coordinator!=null),X=Xe(()=>y(ee)?y(z)?.coordinator:V()||y(te)),he=Xe(()=>c()!=null);Ot(()=>{y(st),V(),ne(),y(z),C(),y(he),y(Vt),I(),x(),l(),b(),v(),P(),$(),Wr(()=>{if(y(st)){if(V()){y(te)&&Un().catch(O),_=null;return}if(ne()!=="force"&&y(z)?.coordinator){y(te)&&Un().catch(O),_=null;return}if(y(te)){let k=Ls();k.length>0&&Ne?is(k,Ne):k.length>0&&(c()||y(Vt))&&Un().catch(O)}if(y(te)&&_!==C()){try{y(te).setToolContextResolvers(C()),_=C()}catch(k){ft({kind:"coordinator-init",source:"pie-assessment-toolkit",error:k})}return}if(!y(te)){if(ne()!=="force"&&!Q){let F=Rw(y(st),Yh);if(F?.coordinator&&F.runtimeId!==n){Ut(z,F,!0),_=null;return}}let k=Vn();if(le===k)return;try{let F=Os();Ut(te,ns(F),!0),Q=ne()!=="force",de=Zi(),Ne=null,_=C(),le="",on()}catch(F){Ut(te,null),le=k,ft({kind:"coordinator-init",source:"pie-assessment-toolkit",error:F})}}}})}),Ot(()=>{if(!y(Vt)||!y(X))return;let k=y(X);Wr(()=>{k===y(te)&&(Ne??(Ne="an item registered"))})});let gt=QU(),kr=Lr(0);Ot(()=>gt.subscribe(()=>{Ut(kr,y(kr)+1)})),Ot(()=>{let k=typeof g()=="string"?g().trim():"";Wr(()=>{Promise.resolve(gt.setLocale(k||"en-US")).catch(F=>{ft({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:F instanceof Error?F:Error(String(F)),recoverable:!0})})})});let Ie=Xe(()=>l()||y(X)?.assessmentId||""),et=Xe(()=>wG({sectionId:u(),section:c(),assessmentId:y(Ie)})),jr=Xe(()=>ri(f())),$t=Xe(()=>ko(y(jr))),$e=Xe(()=>En(L(),J())),Ar=Xe(()=>Au({player:y($e),component:"pie-assessment-toolkit"})),Kr=Xe(()=>y(X)?{toolkitCoordinator:y(X),toolCoordinator:y(X).toolCoordinator,ttsService:y(X).ttsService,highlightCoordinator:y(X).highlightCoordinator,catalogResolver:y(X).catalogResolver,elementToolStateStore:y(X).elementToolStateStore,assessmentId:y(Ie),sectionId:y(et),itemPlayer:y($e),ndsIcons:h()===!0,locale:(y(kr),gt.getLocale()),i18n:gt,contentLanguage:m()?.trim()||void 0,reportSectionError:k=>{i.reportSectionError({source:"section-runtime",error:k,timestamp:Date.now()})}}:null),br=Xe(()=>!y(X)||!y(st)?null:{runtimeId:n,coordinator:y(X),sectionBound:y(he),eventTarget:y(st)});function Xr(k){if(k==null)return;let F=Pr(k);F!==y(Re)&&(Ut(Re,F,!0),Ut(fe,y(fe)+1),Ut(W,k,!0),Rt("composition-changed",{composition:y(W),version:y(fe)}))}function wr(k){Ze=k??i.getCompositionModel(),Ye.schedule(()=>{Xr(Ze)})}function Cr(){Ye.isPending()&&(Ye.cancel(),Xr(Ze))}function Dt(k){if(!k)return;let F=Qe.get(k);if(F){for(let Oe of F)Oe();Qe.delete(k)}}function Mt(){for(let k of re.values())Dt(k.element)}function Hr(k){Dt(k.element),y(X)&&Qe.set(k.element,uG(y(X),k,{assessmentId:y(Ie),sectionId:y(et)}))}function zr(){Mt();for(let k of re.values())Hr(k)}function Pt(k){k&&(lt.get(k)?.(),lt.delete(k))}function hr(k){Pt(k),lt.set(k,mG(k,{getMathSpeech:()=>y(X)?.ttsService.getMathSpeechOptions(),getContentLanguage:()=>m()}))}function Ur(k){let F={...k.result?.eventDetail||k.fallbackSession,itemId:k.itemId,canonicalItemId:k.canonicalItemId||k.itemId,sourceRuntimeId:n};xG({state:zt,itemId:k.itemId,payload:F})&&Rt("session-changed",F)}function Gn(k){return k instanceof HTMLElement?Rw(k,Yh)?.runtimeId===n:!1}function xr(k){return k.detail??null}function gn(k,F){for(let Oe of F)k.addEventListener(Oe.name,Oe.handler);return()=>{for(let Oe of F)k.removeEventListener(Oe.name,Oe.handler)}}Ot(()=>{let k=y(st),F=ne();return Wr(()=>{if(!k)return;if(F==="force")return Ut(z,null),()=>{Q=!1};let Oe=y0(k,je=>{if(je.runtimeId!==n){if(Q){Ri(je.runtimeId);return}Ut(z,je,!0)}});return()=>{Oe(),Ut(z,null),Q=!1}})}),Ot(()=>{let k=y(X);if(k)return Wr(()=>aG({ttsService:k.ttsService,silence:()=>i.requestMediaPauseForCompetingAudio()}))}),Ot(()=>{let k=y(ee)?y(z)?.runtimeId??null:null,F=k?"inherited":"owned";F!==A&&(A=F,Rt(F==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:n,parentRuntimeId:k}))}),Ot(()=>{let k=y(st);k&&Wr(()=>IG(k.ownerDocument))}),Ot(()=>{let k=y(X);if(!k)return;let F=y(ee)?"inherited":"owned";Wr(()=>{k!==K&&(K=k,Rt("runtime-ready",{runtimeId:n,coordinator:k,ownership:F}))})}),Ot(()=>{y(et),d(),CG(zt)}),Ot(()=>{y(st)&&(y(st).setAttribute("data-item-player-type",y($e).type),y(st).setAttribute("data-item-player-tag",y($e).tagName),y(st).setAttribute("data-env-mode",String(y(jr)?.mode||"")),y(st).setAttribute("data-env-role",String(y(jr)?.role||"")))}),Ot(()=>(y(X),y(Ie),y(et),zr(),()=>{Mt()})),Ot(()=>{if(y(st))return wf({host:y(st),instrumentationProvider:y(Ar),component:"pie-assessment-toolkit",eventMap:TO,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:y(Ie),sectionId:y(et),attemptId:d()||void 0}})});let qn=null;Ot(()=>{H(),I();let k=y(X);k&&k===y(te)&&Wr(()=>{let F={pnpEnforcement:ua(I()),assessment:H()??null},Oe=qn?.coordinator===k?qn.inputs:null;qn={coordinator:k,inputs:F};for(let je of SG(Oe,F))je==="pnpEnforcement"?k.setPnpEnforcement(F.pnpEnforcement):k.updateAssessment(F.assessment)})}),Ot(()=>{if(y(X))return y(X).subscribeTelemetry(({eventName:k,payload:F})=>{if(!bf(y(Ar))||!y(Ar).isReady())return;let Oe=k,je=new Date().toISOString(),Se={...F||{},instrumentationLayer:"toolkit",assessmentId:y(Ie),sectionId:y(et),attemptId:d()||void 0,component:"pie-assessment-toolkit",sourceEventName:k,timestamp:je};y(Ar).trackEvent(Oe,Se);let E=F&&typeof F.errorType=="string"?F.errorType:void 0;if(!k.endsWith("-error")&&!E)return;let ue=F&&typeof F.message=="string"?F.message:`Toolkit telemetry error: ${k}`;y(Ar).trackError(Error(ue),{component:"pie-assessment-toolkit",errorType:E||"ToolkitTelemetryError",...Se})})}),Ot(()=>{if(!c()||!y(X))return;let k=!1;y(X)===Wr(()=>y(te))&&(Ne??(Ne="a section initialized"));let F={sectionId:y(et),attemptId:d()||void 0},Oe=De;De=F,Oe&&(Oe.sectionId!==F.sectionId||Oe.attemptId!==F.attemptId)&&Wr(()=>Sf(y(st),{reason:"teardown",logger:r})),ie=null;let je=Wr(()=>Nn(F,!0));return i.initialize({coordinator:y(X),section:c(),sectionId:y(et),assessmentId:y(Ie),attemptId:d()||void 0,view:y($t),initialSession:je,createDefaultController:Ji,onCompositionChanged:Se=>{k||wr(Se)},onControllerEvent:Se=>{k||(Nt(Se),me(Se))}}).then(()=>{if(k)return;ie=F;let Se=Wr(()=>y(se));Se&&mt(Se)===Je&&on(),Je=null,Wr(()=>_r()),Wr(()=>Cr()),queueMicrotask(()=>{k||(Rt("toolkit-ready",{runtimeId:n,assessmentId:y(Ie),sectionId:y(et),itemPlayer:y($e),coordinator:y(X)}),Rt("section-ready",{sectionId:F.sectionId,attemptId:F.attemptId,controller:y(X).getSectionController(F)??null}))})}).catch(Se=>{if(k)return;let E=Wr(()=>Qt(Se));E?(Wr(()=>Nr(E)),Je=mt(E)):Je=mt(ft({kind:"runtime-init",source:"pie-assessment-toolkit",error:Se,scope:"cohort"}))}),()=>{k=!0}}),Ot(()=>{ae(),Wr(()=>{fr(),_r()})}),Ot(()=>{if(!y(st))return;let k=y(st),F=je=>cG(je,n,Gn)?(je.stopPropagation(),!0):!1,Oe=gn(k,[{name:_p,handler:je=>{if(!F(je))return;let Se=xr(je);if(!Se?.element||!Se?.itemId)return;let E=i.register(Se);re.set(Se.element,Se),Ut(Vt,!0),Hr(Se),hr(Se.element),i.handleContentRegistered(Se),E&&wr()}},{name:QE,handler:je=>{if(!F(je))return;let Se=xr(je);if(!Se?.itemId)return;let E=Se?.element?i.unregister(Se.element):!1;Dt(Se.element),Pt(Se.element),Se.element&&re.delete(Se.element),i.handleContentUnregistered(Se),E&&wr()}},{name:ZE,handler:je=>{if(!F(je))return;let Se=xr(je);if(!Se?.itemId)return;let E=i.updateItemSession(Se.itemId,Se.session);Ur({itemId:Se.itemId,canonicalItemId:i.getCanonicalItemId(Se.itemId),result:E,fallbackSession:Se.session})}},{name:Xb,handler:je=>{if(!F(je))return;let Se=xr(je);Se?.itemId&&i.handleContentLoaded({itemId:Se.itemId,canonicalItemId:Se.canonicalItemId,contentKind:Se.contentKind,detail:Se.detail,timestamp:Date.now()})}},{name:eC,handler:je=>{if(!F(je))return;let Se=xr(je);Se?.itemId&&i.handleItemPlayerError({itemId:Se.itemId,canonicalItemId:Se.canonicalItemId,contentKind:Se.contentKind,error:Se.error,timestamp:Date.now()})}},{name:WO,handler:je=>{if(!F(je))return;let Se=xr(je);Se?.itemId&&(Se.action!=="check"&&Se.action!=="retry"||i.handleFormativeAction({itemId:Se.itemId,canonicalItemId:Se.canonicalItemId,action:Se.action,outcomes:Se.outcomes}))}},{name:VO,handler:je=>{if(!F(je))return;let Se=xr(je);Se?.renderableId&&(Se.action!=="attach"&&Se.action!=="detach"||i.handleMediaTimeSource({renderableId:Se.renderableId,action:Se.action,source:Se.source,origin:Se.origin}))}}]);return()=>{Oe();for(let je of[...lt.keys()])Pt(je)}}),Ot(()=>{if(y(st))return()=>{U?.disconnect(),U=null,B?.disconnect(),B=null}}),Ot(()=>{let k=y(st),F=y(br);!k||!F||Wr(()=>{if(U){U.setValue(F);return}U=new Ql(k,{context:Yh,initialValue:F}),U.connect()})}),Ot(()=>{let k=y(st),F=y(Kr);!k||!F||Wr(()=>{if(B){B.setValue(F);return}B=new Ql(k,{context:v0,initialValue:F}),B.connect()})});async function S(){if(!y(X))throw Error("Coordinator not initialized");await y(X).waitUntilReady()}function Z(k){if(!y(X))throw Error("Coordinator not initialized");y(X).setHooks(k)}function oe(k){return i.navigateToItem(k)}function we(){return i.getCompositionModel()}function qe(){return y($e)}async function We(){await i.persist()}async function ot(){await i.hydrate()}Ot(()=>{let k=y(X);if(!k)return;let F=y(fe)>0||y(W)!==null,Oe=!y(he)&&y(Vt);!F&&!Oe||Wr(()=>{k!==pt&&(pt=k,k.waitUntilReady().catch(()=>{}))})}),Ot(()=>()=>{Ye.cancel(),i.dispose().catch(k=>{ft({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:k,recoverable:!0})}).then(()=>Un()).catch(O).finally(()=>{o.dispose()})});var Rr={waitUntilReady:S,setHooks:Z,navigateToItem:oe,getCompositionModel:we,getItemPlayerConfig:qe,persist:We,hydrate:ot,get assessmentId(){return l()},set assessmentId(k){l(k),ct()},get section(){return c()},set section(k){c(k),ct()},get sectionId(){return u()},set sectionId(k){u(k),ct()},get attemptId(){return d()},set attemptId(k){d(k),ct()},get env(){return f()},set env(k){f(k),ct()},get ndsIcons(){return h()},set ndsIcons(k){h(k),ct()},get locale(){return g()},set locale(k){g(k),ct()},get contentLanguage(){return m()},set contentLanguage(k){m(k),ct()},get lazyInit(){return v()},set lazyInit(k){v(k),ct()},get toolConfigStrictness(){return b()},set toolConfigStrictness(k){b(k),ct()},get tools(){return I()},set tools(k){I(k),ct()},get toolContextResolvers(){return C()},set toolContextResolvers(k){C(k),ct()},get enabledTools(){return x()},set enabledTools(k){x(k),ct()},get toolRegistry(){return $()},set toolRegistry(k){$(k),ct()},get accessibility(){return P()},set accessibility(k){P(k),ct()},get player(){return L()},set player(k){L(k),ct()},get playerType(){return J()},set playerType(k){J(k),ct()},get coordinator(){return V()},set coordinator(k){V(k),ct()},get createSectionController(){return Y()},set createSectionController(k){Y(k),ct()},get onFrameworkError(){return Pe()},set onFrameworkError(k){Pe(k),ct()},get errorRenderer(){return M()},set errorRenderer(k){M(k),ct()},get assessment(){return H()},set assessment(k){H(k),ct()},get isolation(){return ne()},set isolation(k){ne(k),ct()},get session(){return ae()},set session(k){ae(k),ct()}},qr=MG(),Br=oi(qr);g0(Br,k=>Ut(ye,k),()=>y(ye));var Gt=Ll(Br,2),Fr=k=>{var F=$G(),Oe=fl(F),je=Eg(Oe,!0),Se=Ll(Oe,2),E=Eg(Se,!0),ue=Ll(Se,2),Le=Eg(ue,!0);ro(F),nn(Ge=>{Rg(je,y(_e)),Rg(E,y(se).message),Rg(Le,Ge)},[()=>y(Ue).join(`
1653
+ `)]),Zt(k,F)},sr=k=>{var F=Mi(),Oe=oi(F);nx(Oe,t,"default",{},null),Zt(k,F)};return Oi(Gt,k=>{y(se)&&!y(se).recoverable?k(Fr):k(sr,-1)}),Zt(e,qr),Cf(Rr)}AG("pie-assessment-toolkit",zm(LG,{assessmentId:{attribute:"assessment-id",type:"String"},section:{attribute:"section",type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},env:{attribute:"env",type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},contentLanguage:{attribute:"content-language",type:"String"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},assessment:{type:"Object"},isolation:{attribute:"isolation",type:"String"},session:{type:"Object"}},["default"],["waitUntilReady","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"},ja));var NG=class{createUniqueId(e,t,r){const n=e.trim()||r;let i=n,o=2;for(;t.has(i);)i=`${n}-${o++}`;return t.add(i),i}resolvePassageBaseId(e,t){return(e?.id||e?.identifier||e?.name||"").trim()||t}normalizePassageEntity(e,t,r){const n=this.resolvePassageBaseId(e,r),i=this.createUniqueId(n,t,r);return{...e,id:i}}build(e,t){if(!e)return{passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],adapterItemRefs:[],stimulusRenderableIdsByRef:{}};const r=new Map,n=new Set,i=new Set,o={},s=(e.rubricBlocks||[]).filter(d=>d.view.includes(t)),a=s.filter(d=>d.class==="instructions");for(const[d,f]of(e.rubricBlocks||[]).entries())if(f.class==="stimulus"&&f.passage&&(f.view.includes("candidate")||f.view.includes(t))){const h=this.normalizePassageEntity(f.passage,n,`passage-${d+1}`);r.set(h.id,h),f.identifier&&(o[f.identifier]=h.id);const g=typeof f.passage.id=="string"?f.passage.id.trim():"";g&&(o[g]=h.id),o[h.id]=h.id}const l=[],c=[];for(const[d,f]of(e.assessmentItemRefs||[]).entries()){if(!f.item)continue;const h=f.item.id||f.identifier||f.item.name||`item-${d+1}`,g=this.createUniqueId(String(h),i,`item-${d+1}`),m=f.item.passage&&typeof f.item.passage=="object"?(()=>{const I=typeof f.item?.passage?.id=="string"?f.item.passage.id.trim():"";return I&&r.has(I)?r.get(I):this.normalizePassageEntity(f.item.passage,n,`passage-${d+1}`)})():void 0,v={...f.item,id:g,passage:m||f.item.passage};l.push(v);const b=f.identifier||g||f.item.name||"";c.push({identifier:b,item:{id:g,identifier:b},formative:f.formative,settings:f.settings}),m&&typeof m=="object"&&m.id&&!r.has(m.id)&&r.set(m.id,m)}const u=[...Array.from(r.values()).map(d=>({flavor:"passage",entity:d})),...l.map(d=>({flavor:"item",entity:d})),...s.filter(d=>d.class==="rubric").map((d,f)=>d?.passage?this.normalizePassageEntity(d.passage,n,`rubric-passage-${f+1}`):null).filter(d=>!!d?.config).map(d=>({flavor:"rubric",entity:d}))];return{passages:Array.from(r.values()),items:l,rubricBlocks:s,instructions:a,renderables:u,adapterItemRefs:c,stimulusRenderableIdsByRef:o}}},DG=class{navigate(e){if(e.index<0||e.index>=e.items.length)return null;const t=e.items[e.currentItemIndex]?.id||"",r=e.items[e.index],n=r?.id||"",i=typeof r?.title=="string"&&r.title.trim()||void 0,o=bj(wj(e.testAttemptSession,{currentItemIndex:e.index,currentSectionIdentifier:e.sectionIdentifier}),n);return{nextIndex:e.index,testAttemptSession:o,eventDetail:{previousItemId:t,currentItemId:n,itemIndex:e.index,totalItems:e.items.length,timestamp:Date.now(),itemLabel:i}}}},jG=class{createEmptyCanonicalAttempt(e){const t=e.adapterItemRefs.map(r=>r?.identifier||r?.item?.id).filter(r=>typeof r=="string"&&!!r);return yj({testAttemptSessionIdentifier:`tas_${e.assessmentId}_${e.sectionId}`,assessmentId:e.assessmentId,seed:`${e.assessmentId}:${e.sectionId}`,itemIdentifiers:t})}toSessionState(e){const t=e.navigationState?.currentItemIndex??0;return{currentItemIndex:t>=0?t:0,visitedItemIdentifiers:e.navigationState?.visitedItemIdentifiers||[],itemSessions:e.itemSessions||{}}}resolve(e){const t=this.createEmptyCanonicalAttempt(e);return{testAttemptSession:t,itemSessions:Ty(t)}}applyItemSessionChanged(e){const t=Kb({itemId:e.itemId,sessionDetail:e.sessionDetail,previousItemSession:e.itemSessions[e.itemId]}),r=t.itemId,n=t.session;let i=e.testAttemptSession;n&&r&&(i=Sj(e.testAttemptSession,{itemIdentifier:r,pieSessionId:String(n.id||r),isCompleted:!!t.complete,session:n}));const o=Ty(i),s=t.intent==="metadata-only"?null:o[r]||n||(e.sessionDetail&&typeof e.sessionDetail=="object"?e.sessionDetail.session??e.sessionDetail:{id:r,data:[]});return{testAttemptSession:i,itemSessions:o,sessionState:this.toSessionState(i),eventDetail:{itemId:r,session:s,intent:t.intent,complete:t.complete,component:t.component,...t.elementId?{elementId:t.elementId}:{},...t.sessionCommitReason?{sessionCommitReason:t.sessionCommitReason}:{},timestamp:Date.now()}}}},zG=5e3,_c=ei("section-controller",()=>za()),BG=class{constructor(){this.contentService=new NG,this.sessionService=new jG,this.itemNavigationService=new DG,this.sessionPersistence=null,this.pendingSessionCommit=null,this.state={input:null,viewModel:{passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],adapterItemRefs:[],stimulusRenderableIdsByRef:{},currentItemIndex:0,isPageMode:!1},testAttemptSession:null},this.listeners=new Set,this.trackedRenderables=new Map,this.loadedRenderableKeys=new Set,this.heldContentLoads=new Map,this.itemCompletionByCanonicalId=new Map,this.elementCompletionByCanonicalId=new Map,this.reportedCompletionIds=new Set,this.sectionLoadingComplete=!1,this.totalRegistered=0,this.totalLoaded=0,this.sectionItemsComplete=!1,this.completedCount=0,this.totalItems=0,this.nextApplyRevision=0,this.lastReplayedApplyRevision=0,this.pendingApplyReplay=null,this.formativePolicies={},this.formativeStates={},this.formativeEnabled=!1,this.lastMasterySignature="",this.timedMediaData=null,this.timedMediaState=lp(),this.mediaTimeSource=null,this.mediaTimeSourceOrigin="native-adapter",this.unsubscribeMediaTimeSource=null,this.lastTimedMediaSignature="",this.lastTimedMediaInvalidSignature="",this.reportedDegradationKeys=new Set,this.mediaAttachWatch=null}emitChange(e){for(const t of Array.from(this.listeners))try{t(e)}catch(r){_c.warn("listener failed",r)}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setPendingSessionCommit(e){this.pendingSessionCommit=e}commitPendingItemSessions(){if(this.pendingSessionCommit)try{this.pendingSessionCommit()}catch(e){_c.warn("pending session commit failed",e)}}async initialize(e){const t=e;if(!t)return;const r=this.state.input?.section?.identifier||this.state.input?.sectionId||void 0,n=this.contentService.build(t.section,t.view),i=this.sessionService.resolve({...t,adapterItemRefs:n.adapterItemRefs}),o=i.testAttemptSession?.navigationState?.currentItemIndex??0;this.state={input:t,viewModel:{...n,currentItemIndex:o,isPageMode:!!t.section&&"keepTogether"in t.section&&t.section.keepTogether===!0},testAttemptSession:i.testAttemptSession};const s=t.section?.identifier||t.sectionId||void 0,a=r!==s;if(a&&this.resetLifecycleTracking(),this.rebuildFormativePolicies(),this.rebuildTimedMedia(),this.bootstrapCompletionFromSessions(),a){const l={type:"section-navigation-change",previousSectionId:r,currentSectionId:s,reason:"input-change",timestamp:Date.now()};this.emitChange(l)}}async updateInput(e){this.commitPendingItemSessions();const t=this.getSession();await this.initialize(e),t&&this.applySessionState(t,"replace",!1)}configureSessionPersistence(e){this.sessionPersistence=e}async hydrate(){if(!this.sessionPersistence)return;const e=await this.sessionPersistence.strategy.loadSession(this.sessionPersistence.context);e&&await this.applySession(e,{mode:"replace"})}async persist(){this.sessionPersistence&&(this.commitPendingItemSessions(),await this.sessionPersistence.strategy.saveSession(this.sessionPersistence.context,this.getSession()))}dispose(){this.pendingSessionCommit=null,this.clearMediaAttachWatch(),this.detachMediaTimeSource(),this.listeners.clear(),this.resetLifecycleTracking(),this.pendingApplyReplay=null,this.nextApplyRevision=0,this.lastReplayedApplyRevision=0}getViewModel(){return this.cloneForRead(this.state.viewModel)}getCompositionModel(){const e=this.getItemViewModels();return{section:this.state.input?.section||null,assessmentItemRefs:this.state.input?.section?.assessmentItemRefs||[],passages:this.state.viewModel.passages,items:this.state.viewModel.items,rubricBlocks:this.state.viewModel.rubricBlocks,instructions:this.state.viewModel.instructions,renderables:this.state.viewModel.renderables,currentItemIndex:this.state.viewModel.currentItemIndex,currentItem:this.getCurrentItem(),isPageMode:this.state.viewModel.isPageMode,itemSessionsByItemId:this.getItemSessionsByItemId(),testAttemptSession:this.getResolvedTestAttemptSession(),itemViewModels:e,formative:this.getFormativeProjection(),timedMedia:this.getTimedMediaProjection()}}getInstructions(){return this.cloneForRead(this.state.viewModel.instructions)}getSectionLoadedEventDetail(){return{sectionId:this.state.input?.section?.identifier||this.state.input?.sectionId||"",itemCount:this.state.viewModel.items.length,passageCount:this.state.viewModel.passages.length,isPageMode:this.state.viewModel.isPageMode}}getResolvedItemSessions(){return this.state.testAttemptSession?Ty(this.state.testAttemptSession):{}}getResolvedTestAttemptSession(){return this.cloneForRead(this.state.testAttemptSession)}getCanonicalItemId(e){return e&&(this.state.viewModel.adapterItemRefs.find(t=>t.item?.id===e)?.identifier||e)}getItemViewModels(){const e=this.getItemSessionsByItemId();return this.state.viewModel.items.map((t,r)=>{const n=t.id||"",i=this.getCanonicalItemId(n),o=this.state.viewModel.adapterItemRefs.find(s=>s.item?.id===n)?.settings;return{item:t,itemId:n,canonicalItemId:i,index:r,isCurrent:r===this.state.viewModel.currentItemIndex,session:e[n]??e[i],...o?{settings:o}:{}}})}getItemSessionsByItemId(){const e=this.getResolvedItemSessions(),t=Object.fromEntries(this.state.viewModel.adapterItemRefs.map(r=>{const n=r.item?.id;if(!n)return null;const i=r.identifier||n;return[n,e[i]??e[n]]}).filter(r=>!!r&&typeof r[0]=="string"&&!!r[0]));for(const[r,n]of Object.entries(e))r in t||(t[r]=n);return t}getSession(){if(!this.state.testAttemptSession)return null;const e=this.sessionService.toSessionState(this.state.testAttemptSession),t=this.formativeEnabled?{...e,formative:Hj(this.formativeStates)}:e;return this.timedMediaData?{...t,timedMedia:g9(this.timedMediaState)}:t}rebuildFormativePolicies(){const e=this.state.input?.section?.formative??null,t=this.state.viewModel.adapterItemRefs.map(r=>({identifier:r.identifier||r.item?.id||"",policy:r.formative??null})).filter(r=>!!r.identifier);this.formativePolicies=kj({sectionPolicy:e,items:t}),this.formativeEnabled=Tj(this.formativePolicies)}computeMastery(){return Nj({itemIdentifiers:this.getSectionItemIdentifiers(),states:this.formativeStates})}getFormativeProjection(){return this.formativeEnabled?this.cloneForRead({version:1,enabled:!0,policies:this.formativePolicies,states:this.formativeStates,mastery:this.computeMastery()}):null}recordFormativeTry(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=Rj(e.outcomes??[]),i=this.formativeStates[t],o=_j({state:i,itemIdentifier:t,policy:r,outcome:n});if(o===i)return;this.formativeStates={...this.formativeStates,[t]:o};const s=Date.now(),a={type:"formative-try-recorded",itemId:e.itemId,canonicalItemId:t,tryCount:o.tryCount,outcome:n,revealed:o.revealed,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:s};this.emitChange(a),this.emitMasteryIfChanged(s),this.notifyTimedMediaDeliveryChanged()}retryFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=this.formativeStates[t],i=Aj({state:n,policy:r});!i||i===n||this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"learner"})}revealFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled||e.feedback!=="correctness"&&e.feedback!=="solution")return;const n=this.formativeStates[t],i=$j({state:n,itemIdentifier:t,policy:r,feedback:e.feedback});i!==n&&this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"host"})}hideFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=this.formativeStates[t],i=Mj({state:n,policy:r});!i||i===n||this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"host"})}commitFormativeReveal(e){this.formativeStates={...this.formativeStates,[e.canonicalItemId]:e.next};const t={type:"formative-reveal-changed",itemId:e.itemId,canonicalItemId:e.canonicalItemId,revealed:e.next.revealed,feedback:e.next.revealOverride,tryCount:e.next.tryCount,source:e.source,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(t),this.notifyTimedMediaDeliveryChanged()}emitMasteryIfChanged(e){if(!this.formativeEnabled)return;const t=this.computeMastery(),r=JSON.stringify(t);if(r===this.lastMasterySignature)return;this.lastMasterySignature=r;const n={type:"section-mastery-changed",mastery:t,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(n)}getSectionItemIdentifiers(){const e=this.state.viewModel.adapterItemRefs.map(t=>t.identifier||t.item?.id).filter(t=>typeof t=="string"&&!!t);return e.length>0?e:this.state.viewModel.items.map(t=>t.id).filter(t=>typeof t=="string"&&!!t)}rebuildTimedMedia(){const e=this.state.input?.section??null;if(this.clearMediaAttachWatch(),!e||e.sectionType!=="timed-media"){this.timedMediaData=null,this.lastTimedMediaInvalidSignature="";return}const t=o9({timedMedia:e.timedMedia,itemIdentifiers:this.getSectionItemIdentifiers(),resolveStimulusRenderableId:r=>this.state.viewModel.stimulusRenderableIdsByRef?.[r],resolveItemTryBudget:r=>{const n=this.formativePolicies[r];return n?.enabled?n.maxTries==="unlimited"?"unlimited":"finite":"not-formative"}});if(this.timedMediaData=t.data,t.data){this.lastTimedMediaInvalidSignature="";return}this.reportTimedMediaInvalid(t.errors)}reportTimedMediaInvalid(e){const t=JSON.stringify(e);if(t===this.lastTimedMediaInvalidSignature)return;this.lastTimedMediaInvalidSignature=t;const r={type:"timed-media-invalid",errors:e,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(r)}resolveTimedMediaView(e){return this.timedMediaData?m9({data:this.timedMediaData,state:this.timedMediaState,delivery:e??this.getTimedMediaDeliveryState(),capabilities:this.mediaTimeSource?.capabilities??null}):null}getTimedMediaProjection(){return this.cloneForRead(this.resolveTimedMediaView())}getTimedMediaDeliveryState(){const e={};for(const[r,n]of this.itemCompletionByCanonicalId)e[r]=n===!0;const t={};for(const[r,n]of Object.entries(this.formativeStates)){const i=n.lastOutcome?.correctness;i&&(t[r]=i)}return{respondedByItemId:e,correctnessByItemId:t,itemsComplete:this.sectionItemsComplete}}attachMediaTimeSource(e,t){if(!e||typeof e.subscribe!="function"||this.mediaTimeSource===e)return;const r=t?.origin??"host";r==="native-adapter"&&t?.renderableId&&this.timedMediaData&&t.renderableId!==this.timedMediaData.stimulusRenderableId||r==="native-adapter"&&this.mediaTimeSource&&this.mediaTimeSourceOrigin==="host"||(this.detachMediaTimeSource(),this.mediaTimeSource=e,this.mediaTimeSourceOrigin=r,this.timedMediaData&&(this.clearMediaAttachWatch(),this.reportedDegradationKeys.clear(),this.unsubscribeMediaTimeSource=e.subscribe(n=>{switch(n.type){case"time":this.advanceTimedMedia({kind:"time",currentTimeSeconds:n.currentTime});return;case"seek":this.advanceTimedMedia({kind:"seek",currentTimeSeconds:n.currentTime});return;case"ended":this.advanceTimedMedia({kind:"ended",currentTimeSeconds:n.currentTime});return;case"play":this.advanceTimedMedia({kind:"time",currentTimeSeconds:n.currentTime}),this.announceMediaAudioStarted();return;default:return}}),this.reportTimedMediaDegradations(),this.syncMediaPositionFromState(),this.advanceTimedMedia({kind:"time",currentTimeSeconds:e.currentTime})))}detachMediaTimeSource(e){e?.origin==="native-adapter"&&this.mediaTimeSource&&this.mediaTimeSourceOrigin==="host"||(this.unsubscribeMediaTimeSource?.(),this.unsubscribeMediaTimeSource=null,this.mediaTimeSource=null)}armMediaAttachWatch(){this.timedMediaData&&(this.mediaTimeSource||this.mediaAttachWatch===null&&(this.mediaAttachWatch=setTimeout(()=>{this.mediaAttachWatch=null,this.reportStimulusExposesNoTimeSource()},zG),this.mediaAttachWatch.unref?.()))}clearMediaAttachWatch(){this.mediaAttachWatch!==null&&(clearTimeout(this.mediaAttachWatch),this.mediaAttachWatch=null)}reportStimulusExposesNoTimeSource(){const e=this.timedMediaData;!e||this.mediaTimeSource||(this.timedMediaData=null,this.lastTimedMediaSignature="",this.reportTimedMediaInvalid([{code:"stimulus-exposes-no-time-source",message:`timedMedia.stimulusRef "${e.stimulusRef}" resolved to renderable "${e.stimulusRenderableId}", which exposed no Media Time Source, so no cue could fire. The section delivers every item instead.`}]))}syncMediaPositionFromState(){const e=this.mediaTimeSource;if(!e)return;const t=this.timedMediaState.mediaCurrentTime;if(t>0&&!(e.currentTime>=t-.5))try{e.seekTo(t)}catch(r){_c.warn("media time source rejected a resume seek",r)}}advanceTimedMedia(e){const t=this.timedMediaData;if(!t)return;const r=this.getTimedMediaDeliveryState(),n=d9({state:this.timedMediaState,data:t,delivery:r,input:e});this.timedMediaState=n.state,this.applyTimedMediaEffects(n.effects),this.emitTimedMediaIfChanged(n.effects,r)}pauseMediaForCompetingAudio(){const e=this.mediaTimeSource;if(!e||e.paused)return!0;if(!e.capabilities.canPause)return!1;try{e.pause()}catch(t){return _c.warn("media time source rejected an audio-handoff pause",t),!1}return!0}announceMediaAudioStarted(){if(!this.timedMediaData||this.mediaTimeSource?.paused!==!1)return;const e={type:"timed-media-audio-started",currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(e)}applyTimedMediaEffects(e){const t=this.mediaTimeSource;if(t){if(e.seekToSeconds!==void 0&&t.capabilities.canRestrictSeeking)try{t.seekTo(e.seekToSeconds)}catch(r){_c.warn("media time source rejected a seek clamp",r)}if(e.pause&&t.capabilities.canPause&&!t.paused)try{t.pause()}catch(r){_c.warn("media time source rejected a pause",r)}}}reportTimedMediaDegradations(){const e=this.timedMediaData;if(!e)return;const{degradations:t}=p_({playbackPolicy:e.playbackPolicy,capabilities:this.mediaTimeSource?.capabilities??null,hasGate:e.cues.some(i=>i.activation==="gate")}),r=t.filter(i=>!this.reportedDegradationKeys.has(i.policy));if(r.length===0)return;for(const i of r)this.reportedDegradationKeys.add(i.policy);const n={type:"timed-media-policy-degraded",degradations:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(n)}emitTimedMediaIfChanged(e,t){const r=this.resolveTimedMediaView(t);if(!r)return;const n=g_(r);if(n===this.lastTimedMediaSignature)return;this.lastTimedMediaSignature=n;const i={type:"timed-media-cue-changed",activatedCueIdentifier:e.activatedCueIdentifier,releasedCueIdentifier:e.releasedCueIdentifier,activeCueIdentifier:r.activeCueIdentifier,visitedCueIdentifiers:r.visitedCueIdentifiers,completedCueIdentifiers:r.completedCueIdentifiers,revealedItemIds:r.revealedItemIds,gateCueIdentifier:r.gate?.cueIdentifier??null,mediaCompleted:r.mediaCompleted,aggregateComplete:r.aggregateComplete,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(i)}notifyTimedMediaDeliveryChanged(){this.timedMediaData&&this.advanceTimedMedia({kind:"delivery-changed"})}getRuntimeState(){if(!this.state.testAttemptSession)return null;const e=this.getSectionItemIdentifiers(),t=e[this.state.viewModel.currentItemIndex]||"",r=new Set(this.state.testAttemptSession.navigationState.visitedItemIdentifiers||[]),n=e.filter(s=>r.has(s)),i={};for(const s of this.state.viewModel.adapterItemRefs){const a=s.identifier||s.item?.id,l=s.item?.id;if(!a)continue;const c=this.state.testAttemptSession?.itemSessions?.[a]?.session??(l?this.state.testAttemptSession?.itemSessions?.[l]?.session:void 0);c&&(i[a]=c)}const o=this.collectLoadedRenderableSnapshot();return{sectionId:this.state.input?.sectionId||"",sectionIdentifier:this.state.input?.section?.identifier||this.state.input?.sectionId||void 0,currentItemIndex:this.state.viewModel.currentItemIndex,currentItemId:t,itemIdentifiers:e,visitedItemIdentifiers:n,itemSessions:i,loadingComplete:this.sectionLoadingComplete,totalRegistered:this.totalRegistered,totalLoaded:this.totalLoaded,itemsComplete:this.sectionItemsComplete,completedCount:this.completedCount,totalItems:this.totalItems,loadedRenderables:o}}collectLoadedRenderableSnapshot(){if(this.loadedRenderableKeys.size===0)return[];const e=[];for(const[t,r]of this.trackedRenderables)this.loadedRenderableKeys.has(t)&&e.push({itemId:r.itemId,canonicalItemId:r.canonicalItemId,contentKind:r.contentKind});return e}getCurrentItem(){return this.state.viewModel.items[this.state.viewModel.currentItemIndex]||null}getCurrentItemSession(){const e=this.getCurrentItem();if(e?.id)return this.getItemSessionsByItemId()[e.id]}getNavigationState(e=!1){const t=this.state.viewModel.currentItemIndex,r=this.state.viewModel.items.length;return{currentIndex:t,totalItems:r,canNext:t<r-1,canPrevious:t>0,isLoading:e}}updateItemSession(e,t){if(!this.state.testAttemptSession)return null;const r=this.getResolvedItemSessions(),n=this.sessionService.applyItemSessionChanged({itemId:e,sessionDetail:t,testAttemptSession:this.state.testAttemptSession,itemSessions:r});this.state.testAttemptSession=n.testAttemptSession;const i=this.getCanonicalItemId(n.eventDetail.itemId),o=n.eventDetail.timestamp,s=n.eventDetail.intent,a=typeof n.eventDetail.complete=="boolean"?n.eventDetail.complete:this.readCompleteFromSession(n.eventDetail.session),{elementId:l,sessionCommitReason:c}=n.eventDetail,u={...l?{elementId:l}:{},sectionId:this.state.input?.sectionId||"",...c?{sessionCommitReason:c}:{}};if(s==="metadata-only"){const d={type:"item-session-meta-changed",itemId:n.eventDetail.itemId,canonicalItemId:i,complete:n.eventDetail.complete,component:n.eventDetail.component,...u,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:o};this.emitChange(d)}else{const d={type:"item-session-data-changed",itemId:n.eventDetail.itemId,canonicalItemId:i,session:n.eventDetail.session,intent:n.eventDetail.intent,complete:n.eventDetail.complete,component:n.eventDetail.component,...u,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:o};this.emitChange(d)}return typeof a=="boolean"&&(this.reportedCompletionIds.add(i),this.updateItemCompleteState({itemId:n.eventDetail.itemId,canonicalItemId:i,complete:this.recordElementCompletion(i,l,a),timestamp:o})),n}async applySession(e,t){!this.state.testAttemptSession||!e||this.applySessionState(e,t?.mode||"replace",!0)}applySessionState(e,t,r){if(!this.state.testAttemptSession)return;const n=this.normalizeApplySession(e);this.applyNormalizedSessionToState(n,t),this.bootstrapCompletionFromSessions(r?new Set(Object.keys(n.itemSessions)):void 0),this.emitMasteryIfChanged(Date.now()),this.syncMediaPositionFromState(),this.notifyTimedMediaDeliveryChanged();const i=++this.nextApplyRevision;this.sectionLoadingComplete||(this.pendingApplyReplay={revision:i,mode:t,session:this.cloneForRead(e),restore:r});const o={type:"section-session-applied",mode:t,itemSessionCount:n.itemSessionCount,replay:!1,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(o)}navigateToItem(e){if(!this.state.testAttemptSession)return null;this.commitPendingItemSessions();const t=this.itemNavigationService.navigate({index:e,items:this.state.viewModel.items,currentItemIndex:this.state.viewModel.currentItemIndex,sectionIdentifier:this.state.input?.section?.identifier||this.state.input?.sectionId,testAttemptSession:this.state.testAttemptSession});if(!t)return null;this.state.viewModel.currentItemIndex=t.nextIndex,this.state.testAttemptSession=t.testAttemptSession;const r={type:"item-selected",previousItemId:t.eventDetail.previousItemId,currentItemId:t.eventDetail.currentItemId,itemIndex:t.eventDetail.itemIndex,totalItems:t.eventDetail.totalItems,itemLabel:t.eventDetail.itemLabel,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t.eventDetail.timestamp};return this.emitChange(r),t}handleContentRegistered(e){const t=this.getCanonicalItemId(e.canonicalItemId||e.itemId),r=this.getRenderableKey(t,e.contentKind),n=this.toSectionContentKind(e.contentKind),i=this.trackedRenderables.get(r);if(i&&i.itemId===e.itemId&&i.canonicalItemId===t&&i.contentKind===n)return;this.trackedRenderables.set(r,{itemId:e.itemId,canonicalItemId:t,contentKind:n}),this.evaluateSectionLoadingState(Date.now());const o=this.heldContentLoads.get(r);o&&(this.heldContentLoads.delete(r),this.handleContentLoaded(o))}handleContentUnregistered(e){const t=this.getCanonicalItemId(e.canonicalItemId||e.itemId),r=this.getRenderableKey(t,e.contentKind);this.trackedRenderables.delete(r),this.loadedRenderableKeys.delete(r),this.heldContentLoads.delete(r),this.evaluateSectionLoadingState(Date.now())}handleContentLoaded(e){const t=e.timestamp??Date.now(),r=this.getCanonicalItemId(e.canonicalItemId||e.itemId),n=this.toSectionContentKind(e.contentKind),i=this.getRenderableKey(r,n);if(this.loadedRenderableKeys.has(i))return;if(!this.trackedRenderables.has(i)){this.heldContentLoads.set(i,{...e,timestamp:t});return}this.loadedRenderableKeys.add(i);const o={type:"content-loaded",contentKind:n,itemId:e.itemId,canonicalItemId:r,detail:e.detail,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t};this.emitChange(o),this.evaluateSectionLoadingState(t)}handleItemPlayerError(e){const t=e.timestamp??Date.now(),r=this.getCanonicalItemId(e.canonicalItemId||e.itemId),n=this.toSectionContentKind(e.contentKind),i={type:"item-player-error",contentKind:n,itemId:e.itemId,canonicalItemId:r,error:e.error,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t};this.emitChange(i),this.reportSectionError({source:"item-player",error:e.error,itemId:e.itemId,canonicalItemId:r,contentKind:n,timestamp:t})}reportSectionError(e){const t={type:"section-error",source:e.source,error:e.error,itemId:e.itemId,canonicalItemId:e.canonicalItemId,contentKind:e.contentKind?this.toSectionContentKind(e.contentKind):void 0,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e.timestamp??Date.now()};this.emitChange(t)}resetLifecycleTracking(){this.trackedRenderables.clear(),this.loadedRenderableKeys.clear(),this.heldContentLoads.clear(),this.itemCompletionByCanonicalId.clear(),this.elementCompletionByCanonicalId.clear(),this.reportedCompletionIds.clear(),this.sectionLoadingComplete=!1,this.totalRegistered=0,this.totalLoaded=0,this.sectionItemsComplete=!1,this.completedCount=0,this.totalItems=0,this.formativeStates={},this.lastMasterySignature="",this.timedMediaState=lp(),this.lastTimedMediaSignature="",this.reportedDegradationKeys.clear()}toSectionContentKind(e){const t=String(e||"").toLowerCase();return t==="item"||t.includes("assessment-item")?"item":t==="passage"?"passage":t==="rubric"||t.includes("rubric")?"rubric":"unknown"}getRenderableKey(e,t){return`${this.toSectionContentKind(t)}:${e}`}readCompleteFromSession(e){if(!e||typeof e!="object")return;const t=e.complete;return typeof t=="boolean"?t:void 0}sessionHoldsResponse(e){if(!e||typeof e!="object")return!1;const t=e.data;return Yb(Array.isArray(t)?t:e)}bootstrapCompletionFromSessions(e=new Set){const t=this.getItemViewModels();for(const r of t){const n=r.canonicalItemId,i=this.readCompleteFromSession(r.session);typeof i=="boolean"?(this.elementCompletionByCanonicalId.delete(n),this.itemCompletionByCanonicalId.set(n,i)):(e.has(n)||!this.reportedCompletionIds.has(n))&&(this.elementCompletionByCanonicalId.delete(n),this.reportedCompletionIds.delete(n),this.itemCompletionByCanonicalId.set(n,this.sessionHoldsResponse(r.session)))}this.emitSectionItemsCompleteIfChanged(Date.now()),this.notifyTimedMediaDeliveryChanged()}recordElementCompletion(e,t,r){if(!t)return this.elementCompletionByCanonicalId.delete(e),r;let n=this.elementCompletionByCanonicalId.get(e);n||(n=new Map,this.elementCompletionByCanonicalId.set(e,n)),n.set(t,r);for(const i of n.values())if(!i)return!1;return!0}updateItemCompleteState(e){const t=this.itemCompletionByCanonicalId.get(e.canonicalItemId)??!1;if(t===e.complete){this.emitSectionItemsCompleteIfChanged(e.timestamp);return}this.itemCompletionByCanonicalId.set(e.canonicalItemId,e.complete);const r={type:"item-complete-changed",itemId:e.itemId,canonicalItemId:e.canonicalItemId,complete:e.complete,previousComplete:t,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e.timestamp};this.emitChange(r),this.emitSectionItemsCompleteIfChanged(e.timestamp),this.notifyTimedMediaDeliveryChanged()}emitSectionItemsCompleteIfChanged(e){const t=this.getItemViewModels(),r=t.length;if(this.totalItems=r,r===0){this.completedCount=0,this.sectionItemsComplete=!1;return}let n=0;for(const s of t)this.itemCompletionByCanonicalId.get(s.canonicalItemId)===!0&&(n+=1);const i=n===r;if(this.completedCount=n,this.sectionItemsComplete===i)return;this.sectionItemsComplete=i;const o={type:"section-items-complete-changed",complete:i,completedCount:n,totalItems:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(o)}evaluateSectionLoadingState(e){const t=this.trackedRenderables.size,r=this.loadedRenderableKeys.size;this.totalRegistered=t,this.totalLoaded=r;let n=t>0;for(const o of this.trackedRenderables.keys()){if(!n)break;n=this.loadedRenderableKeys.has(o)}if(n===this.sectionLoadingComplete||(this.sectionLoadingComplete=n,!n))return;const i={type:"section-loading-complete",totalRegistered:t,totalLoaded:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(i),this.armMediaAttachWatch(),this.replayPendingAppliedSession()}async replayPendingAppliedSession(){const e=this.pendingApplyReplay;if(!e||e.revision<=this.lastReplayedApplyRevision||!this.sectionLoadingComplete)return;const t=this.normalizeApplySession(e.session);if(!this.state.testAttemptSession)return;this.applyNormalizedSessionToState(t,e.mode),this.bootstrapCompletionFromSessions(e.restore?new Set(Object.keys(t.itemSessions)):void 0),this.lastReplayedApplyRevision=e.revision;const r={type:"section-session-applied",mode:e.mode,itemSessionCount:t.itemSessionCount,replay:!0,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(r)}normalizeApplySession(e){const t=e.itemSessions&&typeof e.itemSessions=="object"?e.itemSessions:{},r=new Set(this.state.viewModel.adapterItemRefs.map(s=>this.getCanonicalItemId(s.identifier||s.item?.id||"")).filter(s=>typeof s=="string"&&!!s)),n={};for(const[s,a]of Object.entries(t)){const l=this.getCanonicalItemId(s);if(!r.has(l))continue;const c=this.normalizeItemSessionEntry(l,a);c&&(n[l]=c)}const i=Array.isArray(e.visitedItemIdentifiers)?Array.from(new Set(e.visitedItemIdentifiers.map(s=>this.getCanonicalItemId(s)).filter(s=>r.has(s)))):void 0,o=Math.max(0,this.state.viewModel.items.length-1);return{currentItemIndex:typeof e.currentItemIndex=="number"&&Number.isFinite(e.currentItemIndex)?Math.min(Math.max(0,e.currentItemIndex),o):void 0,visitedItemIdentifiers:i,itemSessions:n,itemSessionCount:Object.keys(n).length,formativeStates:Uj({slice:e.formative,allowedItemIdentifiers:Array.from(r)}),timedMediaState:v9({slice:e.timedMedia,data:this.timedMediaData})}}normalizeItemSessionEntry(e,t){if(!t||typeof t!="object")return null;const r=t,n=r;if(typeof n.itemIdentifier=="string"&&n.session&&typeof n.session=="object")return{itemIdentifier:e,attemptCount:typeof n.attemptCount=="number"&&Number.isFinite(n.attemptCount)?n.attemptCount:1,isCompleted:!!n.isCompleted,session:n.session};const i=n.session&&typeof n.session=="object"?n.session:r;return{itemIdentifier:e,attemptCount:1,isCompleted:typeof n.complete=="boolean"?n.complete:!!i.complete,session:i}}applyNormalizedSessionToState(e,t){this.state.testAttemptSession&&(t==="merge"?this.state.testAttemptSession.itemSessions={...this.state.testAttemptSession.itemSessions,...e.itemSessions}:this.state.testAttemptSession.itemSessions=e.itemSessions,Array.isArray(e.visitedItemIdentifiers)?this.state.testAttemptSession.navigationState.visitedItemIdentifiers=e.visitedItemIdentifiers:t==="replace"&&(this.state.testAttemptSession.navigationState.visitedItemIdentifiers=[]),typeof e.currentItemIndex=="number"?(this.state.testAttemptSession.navigationState.currentItemIndex=e.currentItemIndex,this.state.viewModel.currentItemIndex=e.currentItemIndex):t==="replace"&&(this.state.testAttemptSession.navigationState.currentItemIndex=0,this.state.viewModel.currentItemIndex=0),e.formativeStates?this.formativeStates=t==="merge"?{...this.formativeStates,...e.formativeStates}:e.formativeStates:t==="replace"&&(this.formativeStates={}),e.timedMediaState?this.timedMediaState=e.timedMediaState:t==="replace"&&this.timedMediaData&&(this.timedMediaState=lp()),this.lastMasterySignature="",this.lastTimedMediaSignature="")}cloneForRead(e){if(e==null)return e;try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return e}}}},ST=new WeakMap;function FG(e,t){let r;try{const i=e.getPolicyInputs().tools.placement;r=new Set(Object.values(i).flatMap(o=>Array.isArray(o)?o:[]))}catch{return}let n=ST.get(e);for(const i of r)n?.has(i)||t.get(i)?.provider&&e.getToolConfig(i)?.enabled!==!1&&(e.toolProviderRegistry.has(i)||(n||(n=new Set,ST.set(e,n)),n.add(i),console.warn(`[pie-section-player] Placed tool "${i}" has a provider the host-supplied coordinator (runtime.coordinator) has not registered. That coordinator registers tool providers only from the \`toolRegistry\` it was constructed with: include this tool's registration there — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders" — or construct it without one to use the section player's. Reported once per tool and coordinator.`)))}function HG(e,t){let r=!1;const n=()=>{if(r)return;let s=!1;try{s=e.isReady()}catch{return}s&&FG(e,t)},i=e.onReadyChange(n),o=e.onPolicyChange(s=>{if(s.reason==="disposed"){r=!0;return}queueMicrotask(n)});return n(),()=>{r=!0,i?.(),o()}}var UG=2147483647;function EA(e,t,r){return new Promise(n=>{let i;const o=a=>{i!==void 0&&clearTimeout(i),e?.removeEventListener("toolkit-ready",s),n(a)},s=a=>{const l=t(a);l&&o(l)};e?.addEventListener("toolkit-ready",s),r>=0&&r<=UG&&(i=setTimeout(()=>o(t()),r))})}var qG=Wt('<pie-assessment-toolkit><div class="pie-section-player-surface-anchor svelte-k22ow9"></div> <!></pie-assessment-toolkit>',2),WG={hash:"svelte-k22ow9",code:`:host {display:block;width:100%;height:100%;min-height:0;}
1654
+
1655
+ /* Layout-transparent: the anchor is always present, and a permanent flex item
1656
+ would shift \`gap\` and child-index selectors in the column below it whether or
1657
+ not any capability is mounted. */.pie-section-player-surface-anchor.svelte-k22ow9 {display:contents;}pie-assessment-toolkit.svelte-k22ow9 {display:flex;flex-direction:column;flex:1;width:100%;height:100%;min-height:0;overflow:hidden;}`};function VG(e,t){pn(t,!0),Ln(e,WG);const r=ei("pie-section-player",()=>!1);let n=D(t,"runtime",7,null),i=D(t,"ndsIcons",7,!1),o=D(t,"locale",7,""),s=D(t,"section",7,null),a=D(t,"session",7,null),l=D(t,"assessment",7,null),c=D(t,"sectionId",7,""),u=D(t,"attemptId",7,""),d=D(t,"toolRegistry",7,null),f=D(t,"toolConfigStrictness",7,void 0),h=Be(null),g=Be(null);const m=q(()=>n()?.assessmentId),v=q(()=>n()?.playerType),b=q(()=>n()?.player??null),I=q(()=>n()?.lazyInit),C=q(()=>n()?.tools??null),x=q(()=>n()?.toolContextResolvers??null),$=q(()=>{const ie=f();return ie==="off"||ie==="warn"||ie==="error"?ie:"error"}),P=q(()=>n()?.accessibility??null),L=q(()=>n()?.coordinator??null),J=q(()=>n()?.createSectionController),V=q(()=>n()?.isolation??"inherit"),Y=q(()=>n()?.env??o_),Pe=q(()=>i()===!0?!0:void 0),M=q(()=>o()||void 0),H=q(()=>n()?.contentLanguage||void 0);let ne=Be(null);const ae=q(()=>Ba(p(ne)));vt(()=>{const ie=p(U);if(ie)return sf(ie,De=>{be(ne,De,!0)})});const ye=I_({toolModuleLoaders:S_}),te=q(()=>d()??ye),z=q(()=>n()?.onFrameworkError),A=q(()=>ju({sectionId:c(),section:s(),assessmentId:p(m)}));let K=!1;vt(()=>{const ie=s()?.personalNeedsProfile;K||!ie||(K=!0,console.warn("[pie-section-player] section.personalNeedsProfile is not read: tool policy reads the profile from the assessment entity. Set this element's `assessment` property to an assessment carrying it, or call updateAssessment(...) on a coordinator you pass. Reported once per element."))});function Q(ie){const De=ie.detail?.coordinator;return De||null}function _(ie){const De=Q(ie);De&&be(g,De,!0)}vt(()=>{const ie=p(g),De=p(te);if(!(!ie||ie!==p(L)))return Dr(()=>HG(ie,De))});const B="section-overlay";let U=Be(null);const fe=sw(()=>{},{hostLabel:"pie-section-player"});vt(()=>{const ie=p(g);p(ae),fe.update({anchor:p(U),surface:B,registry:p(te),services:{toolkitCoordinator:ie,ttsService:ie?.ttsService??null,catalogResolver:ie?.catalogResolver??null,i18n:p(ae)},scope:{kind:"section",assessmentId:p(m)||ie?.assessmentId||"",sectionId:p(A)}})}),_m(()=>fe.destroy()),vt(()=>{if(!p(h))return;const ie=p(h),De=p(J),Je=typeof De=="function"?De:()=>new BG,At=Ze=>{Ze?.setPendingSessionCommit?.(()=>Sf(ie,{reason:"navigate",logger:r}))},pt=()=>{const Ze=Je();return At(Ze),Ze},Et=Dr(()=>ie.createSectionController);ie.createSectionController=pt,At(Ue());const Re=Ze=>{At(Ue(Q(Ze)))};return ie.addEventListener("toolkit-ready",Re),()=>{ie.removeEventListener("toolkit-ready",Re),Dr(()=>ie.createSectionController)===pt&&(ie.createSectionController=Et)}}),vt(()=>{if(typeof window>"u")return;const ie=p(h);if(ie)return UO({root:()=>ie,logger:r})}),vt(()=>{if(p(h))return p(h).onFrameworkError=p(z),()=>{p(h).onFrameworkError=void 0}});function W(ie){return p(h)?.navigateToItem?p(h).navigateToItem(ie):null}function se(){return p(h)?.getCompositionModel?p(h).getCompositionModel():null}function _e(){const ie=se(),De=ie?.items||[],Je=Math.max(0,Math.min(typeof ie?.currentItemIndex=="number"?ie.currentItemIndex:0,Math.max(0,De.length-1)));return{currentIndex:Je,totalItems:De.length,canNext:Je<De.length-1,canPrevious:Je>0,currentItemId:De[Je]?.id||void 0}}function Ue(ie=null){const De=u()||void 0,Je=ie||p(g)||p(L);return Je?.getSectionController&&Je.getSectionController({sectionId:p(A),attemptId:De})||null}function it(){return Ue()}async function le(ie=5e3){return ie>0?Ue()??EA(p(h),De=>Ue(De?Q(De):null),ie):null}var de={navigateToItem:W,getCompositionModelSnapshot:se,getNavigationStateSnapshot:_e,getSectionController:it,waitForSectionController:le,get runtime(){return n()},set runtime(ie=null){n(ie),N()},get ndsIcons(){return i()},set ndsIcons(ie=!1){i(ie),N()},get locale(){return o()},set locale(ie=""){o(ie),N()},get section(){return s()},set section(ie=null){s(ie),N()},get session(){return a()},set session(ie=null){a(ie),N()},get assessment(){return l()},set assessment(ie=null){l(ie),N()},get sectionId(){return c()},set sectionId(ie=""){c(ie),N()},get attemptId(){return u()},set attemptId(ie=""){u(ie),N()},get toolRegistry(){return d()},set toolRegistry(ie=null){d(ie),N()},get toolConfigStrictness(){return f()},set toolConfigStrictness(ie=void 0){f(ie),N()}},Ne=qG();ve(()=>Ce(Ne,"assessment-id",p(m))),ve(()=>Ce(Ne,"section",s())),ve(()=>Ce(Ne,"session",a())),ve(()=>Ce(Ne,"assessment",l())),ve(()=>Ce(Ne,"section-id",c())),ve(()=>Ce(Ne,"attempt-id",u())),ve(()=>Ce(Ne,"player-type",p(v))),ve(()=>Ce(Ne,"player",p(b))),ve(()=>Ce(Ne,"env",p(Y))),ve(()=>Ce(Ne,"nds-icons",p(Pe))),ve(()=>Ce(Ne,"locale",p(M))),ve(()=>Ce(Ne,"content-language",p(H))),ve(()=>Ce(Ne,"lazy-init",p(I))),ve(()=>Ce(Ne,"tool-config-strictness",p($))),ve(()=>Ce(Ne,"tools",p(C))),ve(()=>Ce(Ne,"toolContextResolvers",p(x))),ve(()=>Ce(Ne,"toolRegistry",p(te))),ve(()=>Ce(Ne,"accessibility",p(P))),ve(()=>Ce(Ne,"coordinator",p(L))),ve(()=>Ce(Ne,"isolation",p(V))),yn(Ne,1,"svelte-k22ow9");var Ae=Er(Ne);at(Ae,"data-pie-tool-surface",B),$r(Ae,ie=>be(U,ie),()=>p(U));var ce=mr(Ae,2);return _u(ce,t,"default",{},null),Tr(Ne),$r(Ne,ie=>be(h,ie),()=>p(h)),ld("toolkit-ready",Ne,_),ht(e,Ne),mn(de)}GG("pie-section-player-base",Tn(VG,{runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},session:{type:"Object"},assessment:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},toolRegistry:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"}},["default"],["navigateToItem","getCompositionModelSnapshot","getNavigationStateSnapshot","getSectionController","waitForSectionController"],{mode:"open"},ja));function GG(e,t){customElements.get(e)||customElements.define(e,t)}var YG=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},KG=xi("<pie-item-toolbar></pie-item-toolbar>",2);function XG(e,t){Ef(t,!0);let r=dt(t,"enabledTools",7,""),n=dt(t,"position",7,"bottom"),i=dt(t,"sectionId",7,""),o=dt(t,"size",7,"md"),s=dt(t,"language",7,""),a=dt(t,"toolRegistry",7,null),l=dt(t,"item",7,null),c=dt(t,"hostButtons",23,()=>[]);var u={get enabledTools(){return r()},set enabledTools(f){r(f),ct()},get position(){return n()},set position(f){n(f),ct()},get sectionId(){return i()},set sectionId(f){i(f),ct()},get size(){return o()},set size(f){o(f),ct()},get language(){return s()},set language(f){s(f),ct()},get toolRegistry(){return a()},set toolRegistry(f){a(f),ct()},get item(){return l()},set item(f){l(f),ct()},get hostButtons(){return c()},set hostButtons(f){c(f),ct()}},d=KG();return jn(d,"level","section"),nn(()=>jn(d,"scope-id",i())),nn(()=>jn(d,"section-id",i())),nn(()=>jn(d,"tools",r())),jn(d,"content-kind","section"),nn(()=>jn(d,"position",n())),nn(()=>jn(d,"size",o())),nn(()=>jn(d,"language",s())),nn(()=>jn(d,"toolRegistry",a())),nn(()=>jn(d,"item",l())),nn(()=>jn(d,"hostButtons",c())),Zt(e,d),Cf(u)}YG("pie-section-toolbar",zm(XG,{enabledTools:{attribute:"enabled-tools",type:"String"},position:{attribute:"position",type:"String"},sectionId:{attribute:"section-id",type:"String"},size:{attribute:"size",type:"String"},language:{attribute:"language",type:"String"},toolRegistry:{type:"Object"},item:{type:"Object"},hostButtons:{type:"Object"}},[],[],{mode:"open"}));var IT=Wt("<pie-section-toolbar></pie-section-toolbar>",2),JG=Wt('<aside class="pie-section-player-toolbar-pane pie-section-player-toolbar-pane--left svelte-1f2vjx6"><pie-section-toolbar></pie-section-toolbar></aside>',2),QG=Wt('<aside class="pie-section-player-toolbar-pane pie-section-player-toolbar-pane--right svelte-1f2vjx6"><pie-section-toolbar></pie-section-toolbar></aside>',2),ZG=Wt("<div><!> <div><!> <!> <!></div> <!></div>"),eY={hash:"svelte-1f2vjx6",code:`:host {display:block;width:100%;height:100%;min-height:0;}.pie-section-player-shell.svelte-1f2vjx6 {display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-layout-body.svelte-1f2vjx6 {display:grid;grid-template-columns:minmax(0, 1fr);flex:1;min-height:0;overflow:hidden;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-layout-body--inline.svelte-1f2vjx6 {gap:0;}.pie-section-player-layout-body--inline-left.svelte-1f2vjx6 {grid-template-columns:auto minmax(0, 1fr);}.pie-section-player-layout-body--inline-right.svelte-1f2vjx6 {grid-template-columns:minmax(0, 1fr) auto;}.pie-section-player-toolbar-pane.svelte-1f2vjx6 {min-height:0;overflow:auto;padding:0.25rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-toolbar-pane--right.svelte-1f2vjx6 {border-left:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-toolbar-pane--left.svelte-1f2vjx6 {border-right:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-toolbar.svelte-1f2vjx6 {margin:0.25rem;}.pie-section-player-toolbar-pane.svelte-1f2vjx6 pie-section-toolbar:where(.svelte-1f2vjx6) {margin:0.25rem;}
1658
+
1659
+ @media (max-width: 1100px) {.pie-section-player-layout-body--inline.svelte-1f2vjx6 {grid-template-columns:1fr;}.pie-section-player-toolbar-pane--left.svelte-1f2vjx6,
1660
+ .pie-section-player-toolbar-pane--right.svelte-1f2vjx6 {border:none;padding:0;}
1661
+ }`};function tY(e,t){pn(t,!0),Ln(e,eY);const r=1100;let n=D(t,"showToolbar",7,"false"),i=D(t,"toolbarPosition",7,"right"),o=D(t,"enabledTools",7,""),s=D(t,"toolRegistry",7,null),a=D(t,"sectionHostButtons",23,()=>[]),l=Be(null);const c=Hf(()=>p(l));let u=Be(!1);vt(()=>{if(typeof window>"u")return;const M=window.matchMedia(`(max-width: ${r}px)`),H=()=>{be(u,M.matches,!0)};return H(),M.addEventListener("change",H),()=>M.removeEventListener("change",H)});const d=q(()=>p(u)&&(i()==="left"||i()==="right")?"top":i()),f=q(()=>Eb(n(),!1)&&p(d)!=="none"),h=q(()=>p(d)==="top"),g=q(()=>p(d)==="bottom"),m=q(()=>p(d)==="left"||p(d)==="right");var v={get showToolbar(){return n()},set showToolbar(M="false"){n(M),N()},get toolbarPosition(){return i()},set toolbarPosition(M="right"){i(M),N()},get enabledTools(){return o()},set enabledTools(M=""){o(M),N()},get toolRegistry(){return s()},set toolRegistry(M=null){s(M),N()},get sectionHostButtons(){return a()},set sectionHostButtons(M=[]){a(M),N()}},b=ZG(),I=Er(b),C=M=>{var H=IT();ve(()=>Ce(H,"position",p(d))),ve(()=>Ce(H,"enabled-tools",o())),ve(()=>Ce(H,"toolRegistry",s())),ve(()=>Ce(H,"hostButtons",a())),ve(()=>yn(H,1,`pie-section-player-toolbar pie-section-player-toolbar--${p(d)}`,"svelte-1f2vjx6")),ht(M,H)};cn(I,M=>{p(f)&&p(h)&&M(C)});var x=mr(I,2),$=Er(x),P=M=>{var H=JG(),ne=Er(H);Ce(ne,"position","left"),ve(()=>Ce(ne,"enabled-tools",o())),ve(()=>Ce(ne,"toolRegistry",s())),ve(()=>Ce(ne,"hostButtons",a())),yn(ne,1,"svelte-1f2vjx6"),Tr(H),ve(ae=>at(H,"aria-label",ae),[()=>c.t("player.sectionToolsA11y")]),ht(M,H)};cn($,M=>{p(f)&&p(m)&&p(d)==="left"&&M(P)});var L=mr($,2);_u(L,t,"default",{},null);var J=mr(L,2),V=M=>{var H=QG(),ne=Er(H);Ce(ne,"position","right"),ve(()=>Ce(ne,"enabled-tools",o())),ve(()=>Ce(ne,"toolRegistry",s())),ve(()=>Ce(ne,"hostButtons",a())),yn(ne,1,"svelte-1f2vjx6"),Tr(H),ve(ae=>at(H,"aria-label",ae),[()=>c.t("player.sectionToolsA11y")]),ht(M,H)};cn(J,M=>{p(f)&&p(m)&&p(d)==="right"&&M(V)}),Tr(x),$r(x,M=>be(l,M),()=>p(l));var Y=mr(x,2),Pe=M=>{var H=IT();ve(()=>Ce(H,"position",p(d))),ve(()=>Ce(H,"enabled-tools",o())),ve(()=>Ce(H,"toolRegistry",s())),ve(()=>Ce(H,"hostButtons",a())),ve(()=>yn(H,1,`pie-section-player-toolbar pie-section-player-toolbar--${p(d)}`,"svelte-1f2vjx6")),ht(M,H)};return cn(Y,M=>{p(f)&&p(g)&&M(Pe)}),Tr(b),ve(()=>{yn(b,1,`pie-section-player-shell pie-section-player-shell--${p(d)}`,"svelte-1f2vjx6"),yn(x,1,`pie-section-player-layout-body ${p(f)&&p(m)?`pie-section-player-layout-body--inline pie-section-player-layout-body--inline-${p(d)}`:""}`,"svelte-1f2vjx6")}),ht(e,b),mn(v)}rY("pie-section-player-shell",Tn(tY,{showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"}},["default"],[],{mode:"open"}));function rY(e,t){customElements.get(e)||customElements.define(e,t)}var nY=Wt('<div class="pie-section-player-layout-scaffold-anchor svelte-11yyrx2" aria-hidden="true"></div> <div class="pie-section-player-nav-status svelte-11yyrx2" role="alert" aria-live="assertive" aria-atomic="true"> </div> <pie-section-player-base><pie-section-player-shell><!></pie-section-player-shell></pie-section-player-base>',3),iY={hash:"svelte-11yyrx2",code:`.pie-section-player-layout-scaffold-anchor.svelte-11yyrx2 {display:none;}
1662
+
1663
+ /* Visually hidden but available to screen readers (WCAG 4.1.3). */.pie-section-player-nav-status.svelte-11yyrx2 {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;}`};function CA(e,t){pn(t,!0),Ln(e,iY);let r=D(t,"runtime",7,null),n=D(t,"ndsIcons",7,void 0),i=D(t,"locale",7,""),o=D(t,"toolConfigStrictness",7,void 0),s=D(t,"section",7,null),a=D(t,"session",7,null),l=D(t,"assessment",7,null),c=D(t,"sectionId",7,""),u=D(t,"attemptId",7,""),d=D(t,"showToolbar",7,"false"),f=D(t,"toolbarPosition",7,"right"),h=D(t,"enabledTools",7,""),g=D(t,"toolRegistry",7,null),m=D(t,"sectionHostButtons",23,()=>[]),v=D(t,"cardRenderContext",7,null),b=D(t,"layoutContext",7,null),I=D(t,"onCompositionChanged",7),C=D(t,"onSectionReady",7),x=D(t,"onFrameworkErrorEvent",7),$=D(t,"onToolkitReady",7),P=Be(null),L=Be(""),J=null,V=null;function Y(ce){const ie=typeof ce.itemIndex=="number"?ce.itemIndex+1:null,De=typeof ce.totalItems=="number"?ce.totalItems:null;return ce.itemLabel&&ie!==null&&De!==null?`${ce.itemLabel}, question ${ie} of ${De}`:ie!==null&&De!==null?`Question ${ie} of ${De}`:""}function Pe(ce){!ce||ce===V||(J?.(),V=ce,J=ce.subscribeSectionEvents({eventTypes:["item-selected"],listener:ie=>{be(L,Y(ie),!0)}}))}_m(()=>{J?.()});let M=Be(null),H=null,ne=null;const ae=q(()=>oa(p(P))),ye=q(()=>Eb(d(),!1));function te(ce){I()?.(ce)}function z(ce){const ie=ce.composedPath()[0],De=ce.currentTarget;return!!De?.shadowRoot&&ie?.getRootNode?.()===De?.shadowRoot}function A(ce){z(ce)&&C()?.(ce)}function K(ce){x()?.(ce)}function Q(ce){z(ce)&&($()?.(ce),Pe(ce.detail?.coordinator??null))}function _(ce){if(typeof ce!="number"||!Number.isFinite(ce)||!p(M)?.navigateToItem)return!1;const ie=U(),De=p(M).navigateToItem(ce);return U().currentIndex!==ie.currentIndex?!0:De!=null&&De!==!1}function B(){return p(M)?.getCompositionModelSnapshot?.()??null}function U(){return p(M)?.getNavigationStateSnapshot?.()||{currentIndex:0,totalItems:0,canNext:!1,canPrevious:!1}}function fe(){return p(M)?.getSectionController?.()??null}async function W(ce=5e3){return p(M)?.waitForSectionController?p(M).waitForSectionController(ce):null}vt(()=>{if(p(ae))return()=>{H?.disconnect(),H=null,ne?.disconnect(),ne=null}}),vt(()=>{const ce=p(ae),ie=v();!ce||!ie||Dr(()=>{if(H){H.setValue(ie);return}H=EH(ce,ie)})}),vt(()=>{const ce=p(ae),ie=b();!ce||!ie||Dr(()=>{if(ne){ne.setValue(ie);return}ne=R9(ce,ie)})});var se={navigateToItem:_,getCompositionModelSnapshot:B,getNavigationStateSnapshot:U,getSectionController:fe,waitForSectionController:W,get runtime(){return r()},set runtime(ce=null){r(ce),N()},get ndsIcons(){return n()},set ndsIcons(ce=void 0){n(ce),N()},get locale(){return i()},set locale(ce=""){i(ce),N()},get toolConfigStrictness(){return o()},set toolConfigStrictness(ce=void 0){o(ce),N()},get section(){return s()},set section(ce=null){s(ce),N()},get session(){return a()},set session(ce=null){a(ce),N()},get assessment(){return l()},set assessment(ce=null){l(ce),N()},get sectionId(){return c()},set sectionId(ce=""){c(ce),N()},get attemptId(){return u()},set attemptId(ce=""){u(ce),N()},get showToolbar(){return d()},set showToolbar(ce="false"){d(ce),N()},get toolbarPosition(){return f()},set toolbarPosition(ce="right"){f(ce),N()},get enabledTools(){return h()},set enabledTools(ce=""){h(ce),N()},get toolRegistry(){return g()},set toolRegistry(ce=null){g(ce),N()},get sectionHostButtons(){return m()},set sectionHostButtons(ce=[]){m(ce),N()},get cardRenderContext(){return v()},set cardRenderContext(ce=null){v(ce),N()},get layoutContext(){return b()},set layoutContext(ce=null){b(ce),N()},get onCompositionChanged(){return I()},set onCompositionChanged(ce){I(ce),N()},get onSectionReady(){return C()},set onSectionReady(ce){C(ce),N()},get onFrameworkErrorEvent(){return x()},set onFrameworkErrorEvent(ce){x(ce),N()},get onToolkitReady(){return $()},set onToolkitReady(ce){$(ce),N()}},_e=nY(),Ue=bn(_e);$r(Ue,ce=>be(P,ce),()=>p(P));var it=mr(Ue,2),le=La(it,!0),de=mr(it,2);ve(()=>Ce(de,"runtime",r())),ve(()=>Ce(de,"ndsIcons",n())),ve(()=>Ce(de,"locale",i())),ve(()=>Ce(de,"toolConfigStrictness",o())),ve(()=>Ce(de,"section",s())),ve(()=>Ce(de,"session",a())),ve(()=>Ce(de,"assessment",l())),ve(()=>Ce(de,"section-id",c())),ve(()=>Ce(de,"attempt-id",u())),ve(()=>Ce(de,"toolRegistry",g()));var Ne=Er(de);ve(()=>Ce(Ne,"show-toolbar",p(ye))),ve(()=>Ce(Ne,"toolbar-position",f())),ve(()=>Ce(Ne,"enabled-tools",h())),ve(()=>Ce(Ne,"toolRegistry",g())),ve(()=>Ce(Ne,"sectionHostButtons",m()));var Ae=Er(Ne);return _u(Ae,t,"default",{},null),Tr(Ne),Tr(de),$r(de,ce=>be(M,ce),()=>p(M)),ve(()=>ks(le,p(L))),ld("composition-changed",de,te),ld("section-ready",de,A),ld("framework-error",de,K),ld("toolkit-ready",de,Q),ht(e,_e),mn(se)}Tn(CA,{runtime:{},ndsIcons:{},locale:{},toolConfigStrictness:{},section:{},session:{},assessment:{},sectionId:{},attemptId:{},showToolbar:{},toolbarPosition:{},enabledTools:{},toolRegistry:{},sectionHostButtons:{},cardRenderContext:{},layoutContext:{},onCompositionChanged:{},onSectionReady:{},onFrameworkErrorEvent:{},onToolkitReady:{}},["default"],["navigateToItem","getCompositionModelSnapshot","getNavigationStateSnapshot","getSectionController","waitForSectionController"],{mode:"open"});var oY={cohort:!1,runtime:!1,bootstrap:null};function sY(e){return e==="coordinator-init"||e==="runtime-init"||e==="tool-config"}function aY(e,t,r){return!t||t.recoverable===!0||t.kind==="element-preload"?e:t.scope==="cohort"?{...e,cohort:!0}:sY(t.kind)?e.bootstrap?e:{...e,bootstrap:{coordinator:r}}:{...e,runtime:!0}}function lY(e){return{...e,cohort:!1}}function cY(e,t){return!e.bootstrap||e.bootstrap.coordinator===t?e:{...e,bootstrap:null}}function uY(e){return e.cohort||e.runtime||e.bootstrap!==null}function Gf(e,t){pn(t,!0);let r=D(t,"runtime",7,null),n=D(t,"ndsIcons",7,void 0),i=D(t,"locale",7,""),o=D(t,"section",7,null),s=D(t,"session",7,null),a=D(t,"assessment",7,null),l=D(t,"sectionId",7,""),c=D(t,"attemptId",7,""),u=D(t,"iifeBundleHost",7),d=D(t,"showToolbar",7,"false"),f=D(t,"toolbarPosition",7,"right"),h=D(t,"toolConfigStrictness",7,"error"),g=D(t,"toolRegistry",7,null),m=D(t,"sectionHostButtons",23,()=>[]),v=D(t,"itemHostButtons",23,()=>[]),b=D(t,"passageHostButtons",23,()=>[]),I=D(t,"debug",7,void 0),C=D(t,"baseHeadingLevel",7,void 0),x=D(t,"playerActionConfig",23,()=>({stateKey:"__sectionPlayerAppliedParams",includeSessionRefInState:!1})),$=D(t,"policies",7,sb),P=D(t,"hooks",7,void 0),L=D(t,"onElementPreloadRetry",7,void 0),J=D(t,"onElementPreloadError",7,void 0),V=D(t,"sourceCe",7,"pie-section-player"),Y=D(t,"host",7,null);const Pe=typeof window<"u"&&typeof document<"u",M=q(()=>{if(I()!==void 0&&I()!==null){const ge=String(I()),fr=!(ge.toLowerCase()==="false"||ge==="0"||ge==="");if(Pe)try{window.PIE_DEBUG=fr}catch{}return fr}return za()}),H=ei("section-player-layout-kernel",()=>p(M));let ne=Be(ui(s_($0))),ae=Be(null),ye=Be({items:null,passages:null});const te=P9({onChange:ge=>{be(ye,ge)}});let z=Be(!1),A=Be(null),K=Be(!1),Q=Be(ui(oY));const _=q(()=>uY(p(Q)));let B=null,U=null;const fe=new X6;let W=null;const se=q(()=>p(ne).compositionModel),_e=q(()=>p(ne).passages),Ue=q(()=>p(ne).items),it=q(()=>p(ne).renderables),le=q(()=>p(ne).renderablesSignature),de=q(()=>p(z)&&p(ae)?.renderablesSignature===p(le)?p(ae).warmup:"pending"),Ne=q(()=>p(de)==="loaded"),Ae=q(()=>p(K)&&p(Ne)),ce=q(()=>p(K)&&p(de)==="failed"),ie=q(()=>oH({runtime:r(),toolConfigStrictness:h()})),De=q(()=>p(ie).effectiveRuntime),Je=q(()=>o()||l()?ju({sectionId:l(),section:o(),assessmentId:p(De).assessmentId}):""),At=q(()=>p(ie).effectiveToolsConfig),pt=I_({toolModuleLoaders:S_}),Et=q(()=>g()??pt),Re=q(()=>p(ie).playerRuntime),Ze=q(()=>{const ge=p(At)?.placement?.section;return Array.isArray(ge)?ge.join(","):""}),Ye=q(()=>{const ge=p(At)?.placement?.item;return Array.isArray(ge)?ge.join(","):""}),yt=q(()=>{const ge=p(At)?.placement?.passage;return Array.isArray(ge)?ge.join(","):""}),re=q(()=>p(Re).resolvedPlayerDefinition),Qe=q(()=>p(Re).resolvedPlayerTag),lt=q(()=>p(Re).resolvedPlayerAttributes),zt=q(()=>p(Re).resolvedPlayerProps),Vt=q(()=>I()===void 0||I()===null?p(zt):{...p(zt)||{},debug:I()}),ur=q(()=>p(Re).resolvedPlayerEnv),st=q(()=>p(Re).strategy),Rt=q(()=>ow(C())),bt=q(()=>qU(x())),ft=q(()=>P()?.cardTitleFormatter),me=q(()=>({resolvedPlayerTag:p(Qe),playerAction:p(bt),cardTitleFormatter:p(ft)})),Nt=q(()=>Eb(d(),!1)),tr=q(()=>qf($())),mt=q(()=>p(tr).preload.enabled),vr=q(()=>({componentTag:V(),items:p(Ue),passages:p(_e),compositionModel:p(se),preloadedRenderables:p(it),preloadedRenderablesSignature:p(le),preloadEnabled:p(mt),resolvedPlayerEnv:p(ur),resolvedPlayerAttributes:p(lt),resolvedPlayerProps:p(Vt),playerStrategy:p(st),baseHeadingLevel:p(Rt),iifeBundleHost:u()??null,toolRegistry:p(Et),itemToolbarTools:p(Ye),passageToolbarTools:p(yt),itemHostButtons:v(),passageHostButtons:b(),elementsLoaded:p(Ne),activePanes:p(ye),registerPane:te.register,reportWarmup:Qt,reportPreloadRetry:Nr,reportPreloadError:on}));function dr(ge){be(ne,vH(ge),!0),be(z,!0)}function Ir(ge){return te.active().items===ge}function Qt(ge,fr){Ir(ge)&&be(ae,{warmup:fr.warmup,renderablesSignature:fr.renderablesSignature},!0)}function Nr(ge,fr){Ir(ge)&&L()?.({...fr,assessmentId:p(De).assessmentId,sectionId:p(Je),attemptId:c()||void 0})}function on(ge,fr){Ir(ge)&&J()?.({...fr,assessmentId:p(De).assessmentId,sectionId:p(Je),attemptId:c()||void 0})}let Or=null;function yr(ge){be(K,!0);const fr=ge.detail,Nn=ck({sectionId:fr?.sectionId,attemptId:fr?.attemptId});if(Nn){if(!fr?.controller){Or?.reportFrameworkError?.(P0({kind:"section-controller-init",severity:"warning",source:V(),message:"The toolkit's section-ready carried no section controller, so the stage chain stays at booting-section.",recoverable:!0,scope:"cohort"}));return}B={cohort:Nn,controller:fr.controller},fn()}}function fn(){!B||!_d(B.cohort,W)||_d(U,W)||(U=W,fe.dispatchInput({kind:"section-controller-resolved"}))}function or(ge){Or=ge.detail?.coordinator??null,be(Q,cY(p(Q),Or),!0)}function j(ge){const fr=ge.detail;be(Q,aY(p(Q),fr,Or),!0)}function ke(){return p(A)?.getNavigationStateSnapshot?.()||{currentIndex:0,totalItems:p(Ue).length,canNext:p(Ue).length>1,canPrevious:!1,currentItemId:p(Ue)[0]?.id||void 0}}function Fe(){return{composition:{itemsCount:p(Ue).length,passagesCount:p(_e).length},navigation:ke()}}function Ve(ge){return p(A)?.navigateToItem?.(ge)===!0}function Ft(){const ge=ke();return ge.canNext?Ve(ge.currentIndex+1):!1}function Pr(){const ge=ke();return ge.canPrevious?Ve(ge.currentIndex-1):!1}function en(){return p(A)?.getSectionController?.()||null}async function En(ge=5e3){return await p(A)?.waitForSectionController?.(ge)||null}vt(()=>{p(re)?.ensureDefined?.().catch(ge=>{H.error("Failed to load item player component:",ge)})});let ri=!1;vt(()=>{if(!p(K)||!p(z)||p(Ue).length===0||p(ye).items)return;const ge=p(Ue).length,fr=setTimeout(()=>{ri||te.active().items||(ri=!0,console.warn(`[pie-section-player] The section has ${ge} item(s) and no <pie-section-player-items-pane> inside <${V()}>, so no item renders and pie-loading-complete does not fire. Reported once per section player.`))},0);return()=>clearTimeout(fr)}),vt(()=>{p(Je),c(),Dr(()=>{be(Q,lY(p(Q)),!0),be(K,!1)})}),vt(()=>{Y(),p(Je),c(),p(De),p(At),p(Ue).length,p(K),p(Ae),p(ce),p(_),p(tr).readiness.mode,Dr(()=>{if(!Y())return;fe.attachHost({host:Y(),sourceCe:V()});const ge=ck({sectionId:p(Je),attemptId:c()}),fr=p(Ue).length;if(_d(W,ge)?ge!==null&&fe.dispatchInput({kind:"update-runtime",effectiveRuntime:p(De),effectiveToolsConfig:p(At)}):(ge&&(W===null?fe.dispatchInput({kind:"initialize",cohort:ge,effectiveRuntime:p(De),effectiveToolsConfig:p(At),itemCount:fr}):fe.dispatchInput({kind:"cohort-change",cohort:ge,effectiveRuntime:p(De),effectiveToolsConfig:p(At),itemCount:fr})),W=ge,fn()),W!==null){const Nn={sectionReady:p(K),interactionReady:p(Ae),allLoadingComplete:p(Ae),runtimeError:p(_)||p(ce)};fe.dispatchInput({kind:"update-readiness-signals",signals:Nn,itemCount:fr,mode:p(tr).readiness.mode})}})}),vt(()=>{if(Y())return YU({host:Y(),getOnStageChange:()=>p(De)?.onStageChange,getOnLoadingComplete:()=>p(De)?.onLoadingComplete,onError:(ge,fr)=>{H.error(`${ge} handler threw`,fr)}})}),vt(()=>()=>{Dr(()=>{fe.dispose(),te.dispose()})});var ko={getSnapshot:Fe,navigateTo:Ve,navigateNext:Ft,navigatePrevious:Pr,getSectionController:en,waitForSectionController:En,get runtime(){return r()},set runtime(ge=null){r(ge),N()},get ndsIcons(){return n()},set ndsIcons(ge=void 0){n(ge),N()},get locale(){return i()},set locale(ge=""){i(ge),N()},get section(){return o()},set section(ge=null){o(ge),N()},get session(){return s()},set session(ge=null){s(ge),N()},get assessment(){return a()},set assessment(ge=null){a(ge),N()},get sectionId(){return l()},set sectionId(ge=""){l(ge),N()},get attemptId(){return c()},set attemptId(ge=""){c(ge),N()},get iifeBundleHost(){return u()},set iifeBundleHost(ge){u(ge),N()},get showToolbar(){return d()},set showToolbar(ge="false"){d(ge),N()},get toolbarPosition(){return f()},set toolbarPosition(ge="right"){f(ge),N()},get toolConfigStrictness(){return h()},set toolConfigStrictness(ge="error"){h(ge),N()},get toolRegistry(){return g()},set toolRegistry(ge=null){g(ge),N()},get sectionHostButtons(){return m()},set sectionHostButtons(ge=[]){m(ge),N()},get itemHostButtons(){return v()},set itemHostButtons(ge=[]){v(ge),N()},get passageHostButtons(){return b()},set passageHostButtons(ge=[]){b(ge),N()},get debug(){return I()},set debug(ge=void 0){I(ge),N()},get baseHeadingLevel(){return C()},set baseHeadingLevel(ge=void 0){C(ge),N()},get playerActionConfig(){return x()},set playerActionConfig(ge={stateKey:"__sectionPlayerAppliedParams",includeSessionRefInState:!1}){x(ge),N()},get policies(){return $()},set policies(ge=sb){$(ge),N()},get hooks(){return P()},set hooks(ge=void 0){P(ge),N()},get onElementPreloadRetry(){return L()},set onElementPreloadRetry(ge=void 0){L(ge),N()},get onElementPreloadError(){return J()},set onElementPreloadError(ge=void 0){J(ge),N()},get sourceCe(){return V()},set sourceCe(ge="pie-section-player"){V(ge),N()},get host(){return Y()},set host(ge=null){Y(ge),N()}};return $r(CA(e,{get runtime(){return p(De)},get ndsIcons(){return n()},get locale(){return i()},get toolConfigStrictness(){return h()},get section(){return o()},get session(){return s()},get assessment(){return a()},get sectionId(){return l()},get attemptId(){return c()},onCompositionChanged:dr,onSectionReady:yr,onFrameworkErrorEvent:j,onToolkitReady:or,get showToolbar(){return p(Nt)},get toolbarPosition(){return f()},get enabledTools(){return p(Ze)},get toolRegistry(){return p(Et)},get sectionHostButtons(){return m()},get cardRenderContext(){return p(me)},get layoutContext(){return p(vr)},children:(ge,fr)=>{var Nn=Ys(),_r=bn(Nn);_u(_r,t,"default",{get layoutModel(){return{passages:p(_e),paneElementsLoaded:p(Ne)}}},null),ht(ge,Nn)},$$slots:{default:!0}}),ge=>be(A,ge,!0),()=>p(A)),mn(ko)}Tn(Gf,{runtime:{},ndsIcons:{},locale:{},section:{},session:{},assessment:{},sectionId:{},attemptId:{},iifeBundleHost:{},showToolbar:{},toolbarPosition:{},toolConfigStrictness:{},toolRegistry:{},sectionHostButtons:{},itemHostButtons:{},passageHostButtons:{},debug:{},baseHeadingLevel:{},playerActionConfig:{},policies:{},hooks:{},onElementPreloadRetry:{},onElementPreloadError:{},sourceCe:{},host:{}},["default"],["getSnapshot","navigateTo","navigateNext","navigatePrevious","getSectionController","waitForSectionController"],{mode:"open"});var xA={composition:{itemsCount:0,passagesCount:0},navigation:{currentIndex:0,totalItems:0,canNext:!1,canPrevious:!1}};function cg(e){return t=>{const r=(n,i)=>{const o=Reflect.get(t.prototype,i,n);return typeof o=="function"?o:null};return class extends t{getSnapshot(){const n=r(this,"getSnapshot");return n?n():e}navigateTo(n){return r(this,"navigateTo")?.(n)===!0}navigateNext(){return r(this,"navigateNext")?.()===!0}navigatePrevious(){return r(this,"navigatePrevious")?.()===!0}getSectionController(){return r(this,"getSectionController")?.()??null}get session(){const n=this.getSectionController()?.getSession?.();return n||(Reflect.get(t.prototype,"session",this)??null)}set session(n){Reflect.set(t.prototype,"session",n,this)}async waitForSectionController(n=5e3){const i=Date.now()+n;await Promise.resolve();const o=this.getSectionController();if(o)return o;const s=i-Date.now();return s<=0?null:EA(this,()=>this.getSectionController(),s)}}}}var dY=Wt('<div class="pie-section-player-tabs svelte-311cih" role="tablist"><button type="button" role="tab" data-pie-purpose="passage-label"> </button> <button type="button" role="tab" data-pie-purpose="item-label"> </button></div>'),fY=Wt('<div class="pie-section-player-tab-panel pie-section-player-tab-panel--passages svelte-311cih" role="tabpanel"><pie-section-player-passages-pane></pie-section-player-passages-pane></div>',2),hY=Wt('<div class="pie-section-player-tabbed-frame svelte-311cih"><div class="pie-section-player-tabbed-content svelte-311cih"><!> <!> <div class="pie-section-player-tab-panel pie-section-player-tab-panel--items svelte-311cih" role="tabpanel"><pie-section-player-items-pane></pie-section-player-items-pane></div></div></div>',2),pY={hash:"svelte-311cih",code:`.pie-section-player-tabbed-frame.svelte-311cih {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-tabbed-content.svelte-311cih {height:100%;max-height:100%;min-height:0;min-width:0;display:flex;flex-direction:column;gap:var(--pie-section-player-tab-gap, 0.5rem);padding:0.5rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);overflow:hidden;}.pie-section-player-tabs.svelte-311cih {display:flex;gap:6px;background:var(--pie-background, #ffffff);border-radius:var(--pie-section-player-tab-track-radius, 9999px);
1664
+ /*
1665
+ * \`--pie-border-gray\` clears the 3:1 non-text minimum in every scheme and
1666
+ * is stepped to it under the DaisyUI provider. The literal only applies to
1667
+ * a host that mounts the player with no theme at all, where #D9DADA left
1668
+ * the track at 1.2:1 against the frame -- the same grey the button border
1669
+ * defaults to holds there instead.
1670
+ */border:1px solid var(--pie-border-gray, #767676);padding:var(--pie-section-player-tab-track-padding, 0.25rem);width:fit-content;align-self:center;}.pie-section-player-tab.svelte-311cih {position:relative;border:none;border-radius:24px;background:var(--pie-section-player-tab-background, transparent);
1671
+ /*
1672
+ * The unselected tab is transparent, so its ink has to hold against the
1673
+ * track's own \`--pie-background\`. Resolving the hook through \`--pie-text\`
1674
+ * is what keeps it on the certified ordinary-text pair; a literal here
1675
+ * stays near-black under every scheme and disappears on the dark ones.
1676
+ */color:var(--pie-section-player-tab-color, var(--pie-text, #111827));padding:var(--pie-section-player-tab-padding-block, 0.35rem) 12px;font:inherit;
1677
+ /* Was a hard \`12px\`, the only pixel type size in the content path: it
1678
+ ignored the font accommodation and the reader's own browser font size
1679
+ alike, leaving 12px tab labels beside body text at 175%. \`0.75rem\` is
1680
+ the same 12px at a default root, so this only diverges for a host that
1681
+ moves the root size — which is the point of using rem. */font-size:calc(0.75rem * var(--pie-font-scale, 1));font-weight:600;cursor:pointer;transition:background 0.15s ease, color 0.15s ease;white-space:nowrap;}.pie-section-player-tab.svelte-311cih::after {display:none;}.pie-section-player-tab--active.svelte-311cih {
1682
+ /*
1683
+ * The selected pill carries a fixed brand hue, so it behaves like any other
1684
+ * fixed encoding: pinned while no scheme is asking for a palette, folded
1685
+ * into that palette when one is. #1D7375 does not follow a scheme at all,
1686
+ * and as the selection indicator it measured 1.42:1 against the track under
1687
+ * Yellow on Navy, 2.26:1 under Light Gray on Dark Gray and 2.80:1 under
1688
+ * Black on Violet, where 1.4.11 asks for 3:1.
1689
+ *
1690
+ * At 100% collapse the fill becomes --pie-primary and the ink the page
1691
+ * colour, which is the one pairing that holds on every scheme: 5.44:1 or
1692
+ * better for the text, and the same ratio separating the pill from the
1693
+ * track it sits on, since the track paints --pie-background. Mixing rather
1694
+ * than substituting is what keeps the ink out of the light Base Theme's
1695
+ * transparent --pie-background, where it would render invisible: that end
1696
+ * of the mix is the pinned white, exact at 0%.
1697
+ */background:var(
1698
+ --pie-section-player-tab-active-background,
1699
+ color-mix(in srgb, var(--pie-primary, #1D7375) var(--pie-fixed-hue-collapse, 0%), #1D7375)
1700
+ );color:var(
1701
+ --pie-section-player-tab-active-color,
1702
+ color-mix(in srgb, var(--pie-background, #ffffff) var(--pie-fixed-hue-collapse, 0%), #ffffff)
1703
+ );}.pie-section-player-tab.svelte-311cih:focus-visible {outline:2px solid var(--pie-focus-outline, #1d4ed8);outline-offset:2px;}.pie-section-player-tab-panel.svelte-311cih {min-height:0;min-width:0;height:100%;max-height:100%;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-tab-panel[hidden].svelte-311cih {display:none;}.pie-section-player-tab-panel.svelte-311cih .pie-section-player-passages-pane,
1704
+ .pie-section-player-tab-panel.svelte-311cih .pie-section-player-items-pane {height:100%;}`};function ww(e,t){pn(t,!0),Ln(e,pY);let r=D(t,"layoutModel",7),n=D(t,"contentMaxWidthNoPassagePx",7,void 0),i=D(t,"contentMaxWidthWithPassagePx",7,void 0),o=D(t,"idBase",7,"pie-section-player-tabbed"),s=Be(null);const a=Hf(()=>p(s));let l=Be("passage"),c=Be(null),u=Be(null);vt(()=>{o(),Dr(()=>{be(l,"passage")})});const d=q(()=>r().passages.length>0),f=q(()=>p(d)?i():n()),h=q(()=>`${o()}-tab-passage`),g=q(()=>`${o()}-tab-items`),m=q(()=>`${o()}-panel-passage`),v=q(()=>`${o()}-panel-items`),b=q(()=>p(d)?p(l):"items");function I(H){H==="passage"&&!p(d)||be(l,H,!0)}function C(H){if(H==="passage"){p(c)?.focus();return}p(u)?.focus()}function x(H,ne){if(p(d))switch(H.key){case"ArrowRight":case"ArrowLeft":{H.preventDefault();const ae=ne==="passage"?"items":"passage";I(ae),C(ae);break}case"Home":H.preventDefault(),I("passage"),C("passage");break;case"End":H.preventDefault(),I("items"),C("items")}}var $={get layoutModel(){return r()},set layoutModel(H){r(H),N()},get contentMaxWidthNoPassagePx(){return n()},set contentMaxWidthNoPassagePx(H=void 0){n(H),N()},get contentMaxWidthWithPassagePx(){return i()},set contentMaxWidthWithPassagePx(H=void 0){i(H),N()},get idBase(){return o()},set idBase(H="pie-section-player-tabbed"){o(H),N()}},P=hY(),L=Er(P),J=Er(L),V=H=>{var ne=dY(),ae=Er(ne),ye=La(ae,!0);$r(ae,A=>be(c,A),()=>p(c));var te=mr(ae,2),z=La(te,!0);$r(te,A=>be(u,A),()=>p(u)),Tr(ne),ve((A,K,Q)=>{at(ne,"aria-label",A),at(ae,"id",p(h)),yn(ae,1,`pie-section-player-tab ${p(b)==="passage"?"pie-section-player-tab--active":""}`,"svelte-311cih"),at(ae,"aria-controls",p(m)),at(ae,"aria-selected",p(b)==="passage"),at(ae,"tabindex",p(b)==="passage"?0:-1),ks(ye,K),at(te,"id",p(g)),yn(te,1,`pie-section-player-tab ${p(b)==="items"?"pie-section-player-tab--active":""}`,"svelte-311cih"),at(te,"aria-controls",p(v)),at(te,"aria-selected",p(b)==="items"),at(te,"tabindex",p(b)==="items"?0:-1),ks(z,Q)},[()=>a.t("player.sectionTabsA11y"),()=>a.t("player.passage"),()=>a.t("player.questions")]),fo("click",ae,()=>I("passage")),fo("keydown",ae,A=>x(A,"passage")),fo("click",te,()=>I("items")),fo("keydown",te,A=>x(A,"items")),ht(H,ne)};cn(J,H=>{p(d)&&H(V)});var Y=mr(J,2),Pe=H=>{var ne=fY();ve(()=>{at(ne,"id",p(m)),at(ne,"aria-labelledby",p(h)),at(ne,"hidden",p(b)!=="passage")}),ht(H,ne)};cn(Y,H=>{p(d)&&H(Pe)});var M=mr(Y,2);return Tr(L),Tr(P),$r(P,H=>be(s,H),()=>p(s)),ve(()=>{Xl(P,`--pie-section-player-layout-max-width: ${p(f)!==void 0?`${p(f)}px`:"none"};`),at(M,"id",p(v)),at(M,"aria-labelledby",p(d)?p(g):void 0),at(M,"hidden",p(d)&&p(b)!=="items")}),ht(e,P),mn($)}Pu(["click","keydown"]);Tn(ww,{layoutModel:{},contentMaxWidthNoPassagePx:{},contentMaxWidthWithPassagePx:{},idBase:{}},[],[],{mode:"open"});var mY=Wt('<section class="pie-section-player-passages-section svelte-1q3epdx"><pie-section-player-passages-pane></pie-section-player-passages-pane></section>',2),gY=Wt('<div class="pie-section-player-vertical-frame svelte-1q3epdx"><div class="pie-section-player-vertical-content svelte-1q3epdx"><!> <section class="pie-section-player-items-section svelte-1q3epdx"><pie-section-player-items-pane></pie-section-player-items-pane></section></div></div>',2),vY={hash:"svelte-1q3epdx",code:`.pie-section-player-vertical-frame.svelte-1q3epdx {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-vertical-content.svelte-1q3epdx {height:100%;max-height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;display:flex;flex-direction:column;gap:1rem;padding:0.5rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-passages-section.svelte-1q3epdx,
1705
+ .pie-section-player-items-section.svelte-1q3epdx {min-height:0;
1706
+ /* Prevent flexbox from compressing content sections.
1707
+ Let the vertical container own scrolling instead. */flex:0 0 auto;}.pie-section-player-passages-section.svelte-1q3epdx {width:100%;}`};function Sw(e,t){pn(t,!0),Ln(e,vY);let r=D(t,"layoutModel",7),n=D(t,"contentMaxWidthNoPassagePx",7,void 0),i=D(t,"contentMaxWidthWithPassagePx",7,void 0),o=Be(null);const s=Hf(()=>p(o)),a=q(()=>r().passages.length>0?i():n());var l={get layoutModel(){return r()},set layoutModel(g){r(g),N()},get contentMaxWidthNoPassagePx(){return n()},set contentMaxWidthNoPassagePx(g=void 0){n(g),N()},get contentMaxWidthWithPassagePx(){return i()},set contentMaxWidthWithPassagePx(g=void 0){i(g),N()}},c=gY(),u=Er(c),d=Er(u),f=g=>{var m=mY();ve(v=>at(m,"aria-label",v),[()=>s.t("player.passagesRegionA11y")]),ht(g,m)};cn(d,g=>{r().passages.length>0&&r().paneElementsLoaded&&g(f)});var h=mr(d,2);return Tr(u),Tr(c),$r(c,g=>be(o,g),()=>p(o)),ve(g=>{Xl(c,`--pie-section-player-layout-max-width: ${p(a)!==void 0?`${p(a)}px`:"none"};`),at(h,"aria-label",g)},[()=>s.t("player.itemsRegionA11y")]),ht(e,c),mn(l)}Tn(Sw,{layoutModel:{},contentMaxWidthNoPassagePx:{},contentMaxWidthWithPassagePx:{}},[],[],{mode:"open"});var yY=Wt('<div role="separator" aria-orientation="vertical"><span class="pie-section-player-split-divider-handle svelte-mpm4s6"></span></div>'),bY={hash:"svelte-mpm4s6",code:`.pie-section-player-split-divider.svelte-mpm4s6 {border:none;padding:0;margin:0;font:inherit;align-self:stretch;height:100%;min-height:0;position:relative;cursor:col-resize;background:var(--pie-secondary-background, #f3f4f6);display:flex;align-items:center;justify-content:center;user-select:none;touch-action:none;transition:background 0.2s ease;}.pie-section-player-split-divider.svelte-mpm4s6:hover {background:var(--pie-border-light, #e5e7eb);}.pie-section-player-split-divider.svelte-mpm4s6:focus {outline:none;}.pie-section-player-split-divider.svelte-mpm4s6:focus-visible {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:-2px;border-radius:999px;}.pie-section-player-split-divider-handle.svelte-mpm4s6 {position:absolute;inset:0;margin:auto;width:6px;height:60px;background:var(--pie-blue-grey-600, #9ca3af);border-radius:3px;transition:all 0.2s ease;pointer-events:none;}.pie-section-player-split-divider-handle.svelte-mpm4s6::before {content:"";position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);width:2px;height:20px;background:var(--pie-white, white);border-radius:1px;opacity:0.8;}.pie-section-player-split-divider.svelte-mpm4s6:hover .pie-section-player-split-divider-handle:where(.svelte-mpm4s6),
1708
+ .pie-section-player-split-divider.svelte-mpm4s6:focus-visible .pie-section-player-split-divider-handle:where(.svelte-mpm4s6),
1709
+ .pie-section-player-split-divider--dragging.svelte-mpm4s6 .pie-section-player-split-divider-handle:where(.svelte-mpm4s6) {background:var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));height:80px;box-shadow:0 2px 8px color-mix(in srgb, var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3)) 30%, transparent);}.pie-section-player-split-divider--dragging.svelte-mpm4s6 {background:var(--pie-primary-light, #dbeafe);}`};function RA(e,t){pn(t,!0),Ln(e,bY);let r=D(t,"value",7,50),n=D(t,"min",7,20),i=D(t,"max",7,80),o=D(t,"step",7,5),s=D(t,"disabled",7,!1),a=D(t,"ariaLabel",7,"Resize panels"),l=D(t,"ariaControls",7,""),c=D(t,"ariaValueText",7,""),u=D(t,"onResize",7),d=Be(!1),f=0,h=0;function g($){return Math.max(n(),Math.min(i(),$))}function m($){s()||($.preventDefault(),be(d,!0),f=$.clientX,h=r())}function v($){if(!p(d))return;const P=$.clientX-f,L=g(h+P*.1);u()?.(L)}function b(){p(d)&&be(d,!1)}function I($){if(s()||$.key!=="ArrowLeft"&&$.key!=="ArrowRight"&&$.key!=="Escape"&&$.key!=="Home"&&$.key!=="End"||($.preventDefault(),$.key==="Escape"))return;let P=r();if($.key==="Home")P=n();else if($.key==="End")P=i();else{const L=$.key==="ArrowLeft"?-o():o();P=g(r()+L)}u()?.(P)}vt(()=>{if(p(d))return window.addEventListener("mousemove",v),window.addEventListener("mouseup",b),()=>{window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",b)}});var C={get value(){return r()},set value($=50){r($),N()},get min(){return n()},set min($=20){n($),N()},get max(){return i()},set max($=80){i($),N()},get step(){return o()},set step($=5){o($),N()},get disabled(){return s()},set disabled($=!1){s($),N()},get ariaLabel(){return a()},set ariaLabel($="Resize panels"){a($),N()},get ariaControls(){return l()},set ariaControls($=""){l($),N()},get ariaValueText(){return c()},set ariaValueText($=""){c($),N()},get onResize(){return u()},set onResize($){u($),N()}},x=yY();return ve($=>{yn(x,1,`pie-section-player-split-divider ${p(d)?"pie-section-player-split-divider--dragging":""}`,"svelte-mpm4s6"),at(x,"aria-label",a()),at(x,"aria-controls",l()||void 0),at(x,"aria-valuemin",n()),at(x,"aria-valuemax",i()),at(x,"aria-valuenow",$),at(x,"aria-valuetext",c()||void 0),at(x,"aria-disabled",s()?"true":void 0),at(x,"tabindex",s()?void 0:0)},[()=>Math.round(r())]),fo("mousedown",x,m),fo("keydown",x,I),ht(e,x),mn(C)}Pu(["mousedown","keydown"]);Tn(RA,{value:{},min:{},max:{},step:{},disabled:{},ariaLabel:{},ariaControls:{},ariaValueText:{},onResize:{}},[],[],{mode:"open"});var wY=1100,SY=400,IY=2e3,kT=320,TT=2200;function Tb(e,t,r){if(e==null||e==="")return;const n=typeof e=="number"?e:Number(e);if(Number.isFinite(n))return Math.max(t,Math.min(r,n))}function Iw(e){const t=typeof e=="number"?e:Number(e);return Math.max(SY,Math.min(IY,Number.isFinite(t)?t:wY))}function kw(e,t){const r=Tb(e,kT,TT),n=Tb(t,kT,TT);return n===void 0?{noPassagePx:r,withPassagePx:void 0}:{noPassagePx:r,withPassagePx:r===void 0?n:Math.max(r,n)}}function Tw(e){let t=Be(!1);return vt(()=>{const r=e();if(typeof window>"u")return;const n=window.matchMedia(`(max-width: ${r}px)`),i=()=>{be(t,n.matches,!0)};return i(),n.addEventListener("change",i),()=>n.removeEventListener("change",i)}),{get isNarrow(){return p(t)}}}var kY=Wt('<aside class="pie-section-player-passages-pane svelte-qeub3g"><pie-section-player-passages-pane></pie-section-player-passages-pane></aside> <!>',3),TY=Wt('<div class="pie-section-player-split-frame svelte-qeub3g"><div><!> <main class="pie-section-player-items-pane svelte-qeub3g"><pie-section-player-items-pane></pie-section-player-items-pane></main></div></div>',2),EY=Wt('<div class="pie-section-player-observability-anchor svelte-qeub3g" aria-hidden="true"></div> <!>',1),CY={hash:"svelte-qeub3g",code:`:host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-split-frame.svelte-qeub3g {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-split-content.svelte-qeub3g {display:grid;gap:0;min-height:0;width:100%;height:100%;overflow:hidden;}.pie-section-player-passages-pane.svelte-qeub3g,
1710
+ .pie-section-player-items-pane.svelte-qeub3g {height:100%;max-height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;
1711
+ /* Margin (not padding) so the gutter sits outside the scrollable
1712
+ region. Padding lives inside the scroll box, letting any child
1713
+ that uses position:sticky bleed into it as content scrolls past.
1714
+ Kept as margin so this pane composes cleanly with arbitrary
1715
+ descendant content (sticky headers, floating toolbars, etc.). */margin:0.5rem;box-sizing:border-box;
1716
+ /* Backdrop for the scroll surround behind the cards. Deliberately the
1717
+ canonical surface token and not --pie-passage-header-background: that
1718
+ is a passage header hook, and this rule also covers the items pane,
1719
+ which holds no passage header, so a host coloring its hosted
1720
+ passage-player's header used to repaint both pane backdrops. There is
1721
+ no pane-specific hook on purpose — the backdrop is meant to stay with
1722
+ the theme, which is what tracks dark themes and color schemes.
1723
+ --pie-background-dark resolves to #ecedf1 in the default light theme. */background:var(--pie-background-dark, #ecedf1);scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-items-pane.svelte-qeub3g .pie-section-player-scroll-hint {bottom:-0.5rem;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar,
1724
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-track,
1725
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-thumb,
1726
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-thumb:hover,
1727
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-observability-anchor.svelte-qeub3g {display:none;}`};function xY(e,t){pn(t,!0),Ln(e,CY);const r=160,n=1200,i=.5,o=20,s=80;function a(me,Nt){return Math.max(Nt.min,Math.min(Nt.max,me))}function l(me){if(me==null||me==="")return;const Nt=typeof me=="number"?me:Number(me);if(Number.isFinite(Nt))return Math.max(o,Math.min(s,Nt))}function c(me){const Nt=Number.parseFloat(getComputedStyle(me).fontSize||"16");return(Number.isFinite(Nt)&&Nt>0?Nt:16)*i}function u(me){const Nt=me.querySelector(".pie-section-player-passages-pane, .pie-section-player-items-pane");if(!Nt)return 0;const tr=getComputedStyle(Nt),mt=Number.parseFloat(tr.marginLeft||"0"),vr=Number.parseFloat(tr.marginRight||"0"),dr=(Number.isFinite(mt)?mt:0)+(Number.isFinite(vr)?vr:0);return dr>0?dr:0}function d(me,Nt){const tr=me.clientWidth;if(!Number.isFinite(tr)||tr<=0)return{min:o,max:s};const mt=c(me),vr=Math.max(0,tr-mt);if(vr<=0)return{min:50,max:50};const dr=(Nt+u(me))/vr*100;if(!Number.isFinite(dr)||dr>=50)return{min:50,max:50};const Ir=Math.max(o,dr);return{min:Ir,max:Math.min(s,Math.max(Ir,100-Ir))}}let f=D(t,"runtime",7,null),h=D(t,"ndsIcons",7,void 0),g=D(t,"locale",7,""),m=D(t,"section",7,null),v=D(t,"session",7,null),b=D(t,"assessment",7,null),I=D(t,"sectionId",7,""),C=D(t,"attemptId",7,""),x=D(t,"iifeBundleHost",7),$=D(t,"debug",7,void 0),P=D(t,"baseHeadingLevel",7,void 0),L=D(t,"showToolbar",7,"false"),J=D(t,"toolbarPosition",7,"right"),V=D(t,"toolRegistry",7,null),Y=D(t,"sectionHostButtons",23,()=>[]),Pe=D(t,"itemHostButtons",23,()=>[]),M=D(t,"passageHostButtons",23,()=>[]),H=D(t,"policies",7,void 0),ne=D(t,"hooks",7,void 0),ae=D(t,"toolConfigStrictness",7,void 0),ye=D(t,"narrowLayoutBreakpoint",7,void 0),te=D(t,"contentMaxWidthNoPassage",7,void 0),z=D(t,"contentMaxWidthWithPassage",7,void 0),A=D(t,"splitPaneMinRegionWidth",7,void 0),K=D(t,"splitPaneInitialPassageWidth",7,void 0),Q=D(t,"splitPaneCollapseStrategy",7,"tabbed");const _=Dr(()=>l(K())??50);let B=Be(ui(Dr(()=>l(K()))));const U=q(()=>Iw(ye())),fe=Tw(()=>p(U));let W=Be(ui(_)),se=Be(ui({min:20,max:80})),_e=Be(null);const Ue=Hf(()=>p(_e));let it=Be(null),le=Be(null);const de=q(()=>`pie-section-player-splitpane-${(I()||C()||"default").replace(/[^a-zA-Z0-9_-]/g,"-")}`),Ne=q(()=>`${p(de)}-passages`),Ae=q(()=>`${p(de)}-items`),ce=q(()=>`${Math.round(p(W))}% passages width`),ie=q(()=>kw(te(),z())),De=q(()=>p(ie).noPassagePx),Je=q(()=>p(ie).withPassagePx),At=q(()=>Tb(A(),r,n)),pt=q(()=>Q()==="tabbed"?"tabbed":"vertical"),Et=q(()=>Au({runtimePlayer:f()?.player,component:"pie-section-player-splitpane"})),Re=q(()=>oa(p(it)));vt(()=>{const me=p(_e),Nt=p(At);if(typeof window>"u"||!me||typeof ResizeObserver>"u")return;if(Nt===void 0){const vr={min:o,max:s};be(se,vr,!0),be(W,a(p(W),vr),!0);return}const tr=()=>{const vr=d(me,Nt);be(se,vr,!0),be(W,a(p(W),vr),!0)};tr();const mt=new ResizeObserver(()=>tr());return mt.observe(me),()=>mt.disconnect()}),vt(()=>{const me=l(K());Dr(()=>{me!==p(B)&&(be(B,me,!0),me!==void 0&&be(W,a(me,p(se)),!0))})});const Ze=t.$$host,Ye=me=>Ze.dispatchEvent(new CustomEvent("element-preload-retry",{detail:me})),yt=me=>Ze.dispatchEvent(new CustomEvent("element-preload-error",{detail:me}));function re(me){p(_e)&&(Number.isNaN(me)||be(W,a(me,p(se)),!0))}function Qe(){return p(le)?.getSnapshot?.()??null}function lt(me){return p(le)?.navigateTo?.(me)===!0}function zt(){return p(le)?.navigateNext?.()===!0}function Vt(){return p(le)?.navigatePrevious?.()===!0}function ur(){return p(le)?.getSectionController?.()||null}vt(()=>{if(!p(Re)||!qf(H()).telemetry.enabled)return;const me=p(Re);return wf({host:me,instrumentationProvider:p(Et),component:"pie-section-player-splitpane",eventMap:$m,staticAttributes:{instrumentationLayer:"section",assessmentId:f()?.assessmentId,sectionId:ju({sectionId:I(),section:m(),assessmentId:f()?.assessmentId}),attemptId:C()||void 0},shouldTrackEvent:Nt=>tg(Nt,me),dedupeWindowMs:100})});var st={getSnapshot:Qe,navigateTo:lt,navigateNext:zt,navigatePrevious:Vt,getSectionController:ur,get runtime(){return f()},set runtime(me=null){f(me),N()},get ndsIcons(){return h()},set ndsIcons(me=void 0){h(me),N()},get locale(){return g()},set locale(me=""){g(me),N()},get section(){return m()},set section(me=null){m(me),N()},get session(){return v()},set session(me=null){v(me),N()},get assessment(){return b()},set assessment(me=null){b(me),N()},get sectionId(){return I()},set sectionId(me=""){I(me),N()},get attemptId(){return C()},set attemptId(me=""){C(me),N()},get iifeBundleHost(){return x()},set iifeBundleHost(me){x(me),N()},get debug(){return $()},set debug(me=void 0){$(me),N()},get baseHeadingLevel(){return P()},set baseHeadingLevel(me=void 0){P(me),N()},get showToolbar(){return L()},set showToolbar(me="false"){L(me),N()},get toolbarPosition(){return J()},set toolbarPosition(me="right"){J(me),N()},get toolRegistry(){return V()},set toolRegistry(me=null){V(me),N()},get sectionHostButtons(){return Y()},set sectionHostButtons(me=[]){Y(me),N()},get itemHostButtons(){return Pe()},set itemHostButtons(me=[]){Pe(me),N()},get passageHostButtons(){return M()},set passageHostButtons(me=[]){M(me),N()},get policies(){return H()},set policies(me=void 0){H(me),N()},get hooks(){return ne()},set hooks(me=void 0){ne(me),N()},get toolConfigStrictness(){return ae()},set toolConfigStrictness(me=void 0){ae(me),N()},get narrowLayoutBreakpoint(){return ye()},set narrowLayoutBreakpoint(me=void 0){ye(me),N()},get contentMaxWidthNoPassage(){return te()},set contentMaxWidthNoPassage(me=void 0){te(me),N()},get contentMaxWidthWithPassage(){return z()},set contentMaxWidthWithPassage(me=void 0){z(me),N()},get splitPaneMinRegionWidth(){return A()},set splitPaneMinRegionWidth(me=void 0){A(me),N()},get splitPaneInitialPassageWidth(){return K()},set splitPaneInitialPassageWidth(me=void 0){K(me),N()},get splitPaneCollapseStrategy(){return Q()},set splitPaneCollapseStrategy(me="tabbed"){Q(me),N()}},Rt=EY(),bt=bn(Rt);$r(bt,me=>be(it,me),()=>p(it));var ft=mr(bt,2);{let me=q(()=>fe.isNarrow?"top":J());$r(Gf(ft,{get runtime(){return f()},get ndsIcons(){return h()},get locale(){return g()},get section(){return m()},get session(){return v()},get assessment(){return b()},get sectionId(){return I()},get attemptId(){return C()},get iifeBundleHost(){return x()},get debug(){return $()},get baseHeadingLevel(){return P()},get showToolbar(){return L()},get toolbarPosition(){return p(me)},get toolRegistry(){return V()},get sectionHostButtons(){return Y()},get itemHostButtons(){return Pe()},get passageHostButtons(){return M()},get policies(){return H()},get hooks(){return ne()},get toolConfigStrictness(){return ae()},onElementPreloadRetry:Ye,onElementPreloadError:yt,sourceCe:"pie-section-player-splitpane",get host(){return p(Re)},playerActionConfig:{stateKey:"__splitPaneAppliedParams",includeSessionRefInState:!0},children:Mb,$$slots:{default:(Nt,tr)=>{const mt=q(()=>tr.layoutModel);var vr=Ys(),dr=bn(vr),Ir=Nr=>{var on=Ys(),Or=bn(on),yr=or=>{{let j=q(()=>`${p(de)}-tabbed`);ww(or,{get layoutModel(){return p(mt)},get contentMaxWidthNoPassagePx(){return p(De)},get contentMaxWidthWithPassagePx(){return p(Je)},get idBase(){return p(j)}})}},fn=or=>{Sw(or,{get layoutModel(){return p(mt)},get contentMaxWidthNoPassagePx(){return p(De)},get contentMaxWidthWithPassagePx(){return p(Je)}})};cn(Or,or=>{p(pt)==="tabbed"?or(yr):or(fn,-1)}),ht(Nr,on)},Qt=Nr=>{var on=TY(),Or=Er(on),yr=Er(Or),fn=j=>{var ke=kY(),Fe=bn(ke),Ve=mr(Fe,2);{let Ft=q(()=>Ue.t("player.resizePassagesAndItemsA11y"));RA(Ve,{get value(){return p(W)},get min(){return p(se).min},get max(){return p(se).max},get ariaLabel(){return p(Ft)},get ariaControls(){return p(Ne)},get ariaValueText(){return p(ce)},onResize:re})}ve(Ft=>{at(Fe,"id",p(Ne)),at(Fe,"aria-label",Ft)},[()=>Ue.t("player.passagesRegionA11y")]),ht(j,ke)};cn(yr,j=>{p(mt).passages.length>0&&j(fn)});var or=mr(yr,2);Tr(Or),$r(Or,j=>be(_e,j),()=>p(_e)),Tr(on),ve(j=>{Xl(on,`--pie-section-player-layout-max-width: ${p(mt).passages.length===0?p(De)!==void 0?`${p(De)}px`:"none":p(Je)!==void 0?`${p(Je)}px`:"none"};`),yn(Or,1,`pie-section-player-split-content ${p(mt).passages.length===0?"pie-section-player-split-content--no-passages":""}`,"svelte-qeub3g"),Xl(Or,p(mt).passages.length===0?"grid-template-columns: 1fr":`grid-template-columns: minmax(0, calc((100% - 0.5rem) * ${p(W)/100})) 0.5rem minmax(0, calc((100% - 0.5rem) * ${(100-p(W))/100}))`),at(or,"id",p(Ae)),at(or,"aria-label",j)},[()=>Ue.t("player.itemsRegionA11y")]),ht(Nr,on)};cn(dr,Nr=>{fe.isNarrow?Nr(Ir):Nr(Qt,-1)}),ht(Nt,vr)}}}),Nt=>be(le,Nt,!0),()=>p(le))}return ht(e,Rt),mn(st)}RY("pie-section-player-splitpane",Tn(xY,{runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},session:{type:"Object"},assessment:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"},splitPaneMinRegionWidth:{attribute:"split-pane-min-region-width",type:"Number"},splitPaneInitialPassageWidth:{attribute:"split-pane-initial-passage-width",type:"Number"},splitPaneCollapseStrategy:{attribute:"split-pane-collapse-strategy",type:"String"}},[],["getSnapshot","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>ja(cg(null)(e))));function RY(e,t){customElements.get(e)||customElements.define(e,t)}var PY=Wt('<div class="pie-section-player-observability-anchor svelte-e5eey4" aria-hidden="true"></div> <!>',1),_Y={hash:"svelte-e5eey4",code:":host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-observability-anchor.svelte-e5eey4 {display:none;}"};function AY(e,t){pn(t,!0),Ln(e,_Y);let r=D(t,"runtime",7,null),n=D(t,"ndsIcons",7,void 0),i=D(t,"locale",7,""),o=D(t,"section",7,null),s=D(t,"session",7,null),a=D(t,"assessment",7,null),l=D(t,"sectionId",7,""),c=D(t,"attemptId",7,""),u=D(t,"iifeBundleHost",7),d=D(t,"debug",7,void 0),f=D(t,"baseHeadingLevel",7,void 0),h=D(t,"showToolbar",7,"false"),g=D(t,"toolbarPosition",7,"right"),m=D(t,"toolRegistry",7,null),v=D(t,"sectionHostButtons",23,()=>[]),b=D(t,"itemHostButtons",23,()=>[]),I=D(t,"passageHostButtons",23,()=>[]),C=D(t,"policies",7,void 0),x=D(t,"hooks",7,void 0),$=D(t,"toolConfigStrictness",7,void 0),P=D(t,"narrowLayoutBreakpoint",7,void 0),L=D(t,"contentMaxWidthNoPassage",7,void 0),J=D(t,"contentMaxWidthWithPassage",7,void 0),V=Be(null),Y=Be(null);const Pe=q(()=>Au({runtimePlayer:r()?.player,component:"pie-section-player-vertical"})),M=q(()=>oa(p(V))),H=q(()=>Iw(P())),ne=Tw(()=>p(H)),ae=q(()=>ne.isNarrow?"top":g()),ye=q(()=>kw(L(),J())),te=q(()=>p(ye).noPassagePx),z=q(()=>p(ye).withPassagePx),A=t.$$host,K=le=>A.dispatchEvent(new CustomEvent("element-preload-retry",{detail:le})),Q=le=>A.dispatchEvent(new CustomEvent("element-preload-error",{detail:le}));function _(){return p(Y)?.getSnapshot?.()??null}function B(le){return p(Y)?.navigateTo?.(le)===!0}function U(){return p(Y)?.navigateNext?.()===!0}function fe(){return p(Y)?.navigatePrevious?.()===!0}function W(){return p(Y)?.getSectionController?.()||null}vt(()=>{if(!p(M)||!qf(C()).telemetry.enabled)return;const le=p(M);return wf({host:le,instrumentationProvider:p(Pe),component:"pie-section-player-vertical",eventMap:$m,staticAttributes:{instrumentationLayer:"section",assessmentId:r()?.assessmentId,sectionId:ju({sectionId:l(),section:o(),assessmentId:r()?.assessmentId}),attemptId:c()||void 0},shouldTrackEvent:de=>tg(de,le),dedupeWindowMs:100})});var se={getSnapshot:_,navigateTo:B,navigateNext:U,navigatePrevious:fe,getSectionController:W,get runtime(){return r()},set runtime(le=null){r(le),N()},get ndsIcons(){return n()},set ndsIcons(le=void 0){n(le),N()},get locale(){return i()},set locale(le=""){i(le),N()},get section(){return o()},set section(le=null){o(le),N()},get session(){return s()},set session(le=null){s(le),N()},get assessment(){return a()},set assessment(le=null){a(le),N()},get sectionId(){return l()},set sectionId(le=""){l(le),N()},get attemptId(){return c()},set attemptId(le=""){c(le),N()},get iifeBundleHost(){return u()},set iifeBundleHost(le){u(le),N()},get debug(){return d()},set debug(le=void 0){d(le),N()},get baseHeadingLevel(){return f()},set baseHeadingLevel(le=void 0){f(le),N()},get showToolbar(){return h()},set showToolbar(le="false"){h(le),N()},get toolbarPosition(){return g()},set toolbarPosition(le="right"){g(le),N()},get toolRegistry(){return m()},set toolRegistry(le=null){m(le),N()},get sectionHostButtons(){return v()},set sectionHostButtons(le=[]){v(le),N()},get itemHostButtons(){return b()},set itemHostButtons(le=[]){b(le),N()},get passageHostButtons(){return I()},set passageHostButtons(le=[]){I(le),N()},get policies(){return C()},set policies(le=void 0){C(le),N()},get hooks(){return x()},set hooks(le=void 0){x(le),N()},get toolConfigStrictness(){return $()},set toolConfigStrictness(le=void 0){$(le),N()},get narrowLayoutBreakpoint(){return P()},set narrowLayoutBreakpoint(le=void 0){P(le),N()},get contentMaxWidthNoPassage(){return L()},set contentMaxWidthNoPassage(le=void 0){L(le),N()},get contentMaxWidthWithPassage(){return J()},set contentMaxWidthWithPassage(le=void 0){J(le),N()}},_e=PY(),Ue=bn(_e);$r(Ue,le=>be(V,le),()=>p(V));var it=mr(Ue,2);return $r(Gf(it,{get runtime(){return r()},get ndsIcons(){return n()},get locale(){return i()},get section(){return o()},get session(){return s()},get assessment(){return a()},get sectionId(){return l()},get attemptId(){return c()},get iifeBundleHost(){return u()},get debug(){return d()},get baseHeadingLevel(){return f()},get showToolbar(){return h()},get toolbarPosition(){return p(ae)},get toolRegistry(){return m()},get sectionHostButtons(){return v()},get itemHostButtons(){return b()},get passageHostButtons(){return I()},get policies(){return C()},get hooks(){return x()},get toolConfigStrictness(){return $()},onElementPreloadRetry:K,onElementPreloadError:Q,sourceCe:"pie-section-player-vertical",get host(){return p(M)},playerActionConfig:{stateKey:"__verticalAppliedParams",includeSessionRefInState:!1},children:Mb,$$slots:{default:(le,de)=>{const Ne=q(()=>de.layoutModel);Sw(le,{get layoutModel(){return p(Ne)},get contentMaxWidthNoPassagePx(){return p(te)},get contentMaxWidthWithPassagePx(){return p(z)}})}}}),le=>be(Y,le,!0),()=>p(Y)),ht(e,_e),mn(se)}$Y("pie-section-player-vertical",Tn(AY,{runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},session:{type:"Object"},assessment:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"}},[],["getSnapshot","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>ja(cg(null)(e))));function $Y(e,t){customElements.get(e)||customElements.define(e,t)}var MY=Wt('<div class="pie-section-player-observability-anchor svelte-w6yo40" aria-hidden="true"></div> <!>',1),OY={hash:"svelte-w6yo40",code:":host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-observability-anchor.svelte-w6yo40 {display:none;}"};function LY(e,t){pn(t,!0),Ln(e,OY);let r=D(t,"runtime",7,null),n=D(t,"ndsIcons",7,void 0),i=D(t,"locale",7,""),o=D(t,"section",7,null),s=D(t,"session",7,null),a=D(t,"assessment",7,null),l=D(t,"sectionId",7,""),c=D(t,"attemptId",7,""),u=D(t,"iifeBundleHost",7),d=D(t,"debug",7,void 0),f=D(t,"baseHeadingLevel",7,void 0),h=D(t,"showToolbar",7,"false"),g=D(t,"toolbarPosition",7,"right"),m=D(t,"toolRegistry",7,null),v=D(t,"sectionHostButtons",23,()=>[]),b=D(t,"itemHostButtons",23,()=>[]),I=D(t,"passageHostButtons",23,()=>[]),C=D(t,"policies",7,void 0),x=D(t,"hooks",7,void 0),$=D(t,"toolConfigStrictness",7,void 0),P=D(t,"narrowLayoutBreakpoint",7,void 0),L=D(t,"contentMaxWidthNoPassage",7,void 0),J=D(t,"contentMaxWidthWithPassage",7,void 0),V=Be(null),Y=Be(null);const Pe=q(()=>`pie-section-player-tabbed-${(l()||c()||"default").replace(/[^a-zA-Z0-9_-]/g,"-")}`),M=q(()=>Au({runtimePlayer:r()?.player,component:"pie-section-player-tabbed"})),H=q(()=>oa(p(V))),ne=q(()=>Iw(P())),ae=Tw(()=>p(ne)),ye=q(()=>ae.isNarrow?"top":g()),te=q(()=>kw(L(),J())),z=q(()=>p(te).noPassagePx),A=q(()=>p(te).withPassagePx),K=t.$$host,Q=de=>K.dispatchEvent(new CustomEvent("element-preload-retry",{detail:de})),_=de=>K.dispatchEvent(new CustomEvent("element-preload-error",{detail:de}));function B(){return p(Y)?.getSnapshot?.()??null}function U(de){return p(Y)?.navigateTo?.(de)===!0}function fe(){return p(Y)?.navigateNext?.()===!0}function W(){return p(Y)?.navigatePrevious?.()===!0}function se(){return p(Y)?.getSectionController?.()||null}vt(()=>{if(!p(H)||!qf(C()).telemetry.enabled)return;const de=p(H);return wf({host:de,instrumentationProvider:p(M),component:"pie-section-player-tabbed",eventMap:$m,staticAttributes:{instrumentationLayer:"section",assessmentId:r()?.assessmentId,sectionId:ju({sectionId:l(),section:o(),assessmentId:r()?.assessmentId}),attemptId:c()||void 0},shouldTrackEvent:Ne=>tg(Ne,de),dedupeWindowMs:100})});var _e={getSnapshot:B,navigateTo:U,navigateNext:fe,navigatePrevious:W,getSectionController:se,get runtime(){return r()},set runtime(de=null){r(de),N()},get ndsIcons(){return n()},set ndsIcons(de=void 0){n(de),N()},get locale(){return i()},set locale(de=""){i(de),N()},get section(){return o()},set section(de=null){o(de),N()},get session(){return s()},set session(de=null){s(de),N()},get assessment(){return a()},set assessment(de=null){a(de),N()},get sectionId(){return l()},set sectionId(de=""){l(de),N()},get attemptId(){return c()},set attemptId(de=""){c(de),N()},get iifeBundleHost(){return u()},set iifeBundleHost(de){u(de),N()},get debug(){return d()},set debug(de=void 0){d(de),N()},get baseHeadingLevel(){return f()},set baseHeadingLevel(de=void 0){f(de),N()},get showToolbar(){return h()},set showToolbar(de="false"){h(de),N()},get toolbarPosition(){return g()},set toolbarPosition(de="right"){g(de),N()},get toolRegistry(){return m()},set toolRegistry(de=null){m(de),N()},get sectionHostButtons(){return v()},set sectionHostButtons(de=[]){v(de),N()},get itemHostButtons(){return b()},set itemHostButtons(de=[]){b(de),N()},get passageHostButtons(){return I()},set passageHostButtons(de=[]){I(de),N()},get policies(){return C()},set policies(de=void 0){C(de),N()},get hooks(){return x()},set hooks(de=void 0){x(de),N()},get toolConfigStrictness(){return $()},set toolConfigStrictness(de=void 0){$(de),N()},get narrowLayoutBreakpoint(){return P()},set narrowLayoutBreakpoint(de=void 0){P(de),N()},get contentMaxWidthNoPassage(){return L()},set contentMaxWidthNoPassage(de=void 0){L(de),N()},get contentMaxWidthWithPassage(){return J()},set contentMaxWidthWithPassage(de=void 0){J(de),N()}},Ue=MY(),it=bn(Ue);$r(it,de=>be(V,de),()=>p(V));var le=mr(it,2);return $r(Gf(le,{get runtime(){return r()},get ndsIcons(){return n()},get locale(){return i()},get section(){return o()},get session(){return s()},get assessment(){return a()},get sectionId(){return l()},get attemptId(){return c()},get iifeBundleHost(){return u()},get debug(){return d()},get baseHeadingLevel(){return f()},get showToolbar(){return h()},get toolbarPosition(){return p(ye)},get toolRegistry(){return m()},get sectionHostButtons(){return v()},get itemHostButtons(){return b()},get passageHostButtons(){return I()},get policies(){return C()},get hooks(){return x()},get toolConfigStrictness(){return $()},onElementPreloadRetry:Q,onElementPreloadError:_,sourceCe:"pie-section-player-tabbed",get host(){return p(H)},playerActionConfig:{stateKey:"__tabbedAppliedParams",includeSessionRefInState:!1},children:Mb,$$slots:{default:(de,Ne)=>{const Ae=q(()=>Ne.layoutModel);ww(de,{get layoutModel(){return p(Ae)},get contentMaxWidthNoPassagePx(){return p(z)},get contentMaxWidthWithPassagePx(){return p(A)},get idBase(){return p(Pe)}})}}}),de=>be(Y,de,!0),()=>p(Y)),ht(e,Ue),mn(_e)}NY("pie-section-player-tabbed",Tn(LY,{runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},session:{type:"Object"},assessment:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"}},[],["getSnapshot","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>ja(cg(null)(e))));function NY(e,t){customElements.get(e)||customElements.define(e,t)}var DY=Wt("<pie-section-player-passages-pane></pie-section-player-passages-pane>",2),jY=Wt('<div class="pie-section-player-kernel-host-content svelte-1qqam9j"><!> <pie-section-player-items-pane></pie-section-player-items-pane></div>',2),zY={hash:"svelte-1qqam9j",code:".pie-section-player-kernel-host-content.svelte-1qqam9j {display:flex;flex-direction:column;gap:1rem;min-height:0;height:100%;padding:0.5rem;box-sizing:border-box;}pie-section-player-items-pane.svelte-1qqam9j .pie-section-player-scroll-hint {bottom:-0.5rem;}"};function PA(e,t){pn(t,!0),Ln(e,zY);let r=Be(null),n=Be(!1);vt(()=>{if(p(r))return dw(p(r),l=>{be(n,l.passages.length>0)})});var i=jY(),o=Er(i),s=l=>{var c=DY();ht(l,c)};cn(o,l=>{p(n)&&l(s)});var a=mr(o,2);yn(a,1,"svelte-1qqam9j"),Tr(i),$r(i,l=>be(r,l),()=>p(r)),ht(e,i),mn()}Tn(PA,{},[],[],{mode:"open"});function BY(e,t){let r=null,n=new Set;const i=()=>Array.from(e.children).some(a=>!n.has(a)),o=()=>{const a=!i();if(a&&!r){const l=new Set(e.childNodes);r=t(e),n=new Set(Array.from(e.childNodes).filter(c=>!l.has(c)));return}if(!a&&r){const l=r;r=null,n=new Set,l()}};o();const s=new MutationObserver(o);return s.observe(e,{childList:!0}),()=>{s.disconnect();const a=r;r=null,n=new Set,a?.()}}var FY=Wt('<div class="pie-section-player-observability-anchor svelte-1y3fqx7" aria-hidden="true"></div> <!>',1),HY={hash:"svelte-1y3fqx7",code:".pie-section-player-observability-anchor.svelte-1y3fqx7 {display:none;}"};function UY(e,t){pn(t,!0),Ln(e,HY);let r=D(t,"runtime",7,null),n=D(t,"ndsIcons",7,void 0),i=D(t,"locale",7,""),o=D(t,"section",7,null),s=D(t,"session",7,null),a=D(t,"assessment",7,null),l=D(t,"sectionId",7,""),c=D(t,"attemptId",7,""),u=D(t,"iifeBundleHost",7),d=D(t,"debug",7,void 0),f=D(t,"baseHeadingLevel",7,void 0),h=D(t,"showToolbar",7,"false"),g=D(t,"toolbarPosition",7,"right"),m=D(t,"toolRegistry",7,null),v=D(t,"sectionHostButtons",23,()=>[]),b=D(t,"itemHostButtons",23,()=>[]),I=D(t,"passageHostButtons",23,()=>[]),C=D(t,"policies",7,void 0),x=D(t,"hooks",7,void 0),$=D(t,"toolConfigStrictness",7,void 0),P=Be(null),L=Be(null);const J=q(()=>Au({runtimePlayer:r()?.player,component:"pie-section-player-kernel-host"})),V=q(()=>oa(p(P)));function Y(){return p(L)?.getSnapshot?.()||xA}function Pe(_){return p(L)?.navigateTo?.(_)===!0}function M(){return p(L)?.navigateNext?.()===!0}function H(){return p(L)?.navigatePrevious?.()===!0}function ne(){return p(L)?.getSectionController?.()||null}const ae=t.$$host,ye=_=>ae.dispatchEvent(new CustomEvent("element-preload-retry",{detail:_})),te=_=>ae.dispatchEvent(new CustomEvent("element-preload-error",{detail:_}));vt(()=>{if(p(V))return BY(p(V),_=>{const B=qb(PA,{target:_});return()=>{$E(B)}})}),vt(()=>{if(!p(V)||!qf(C()).telemetry.enabled)return;const _=p(V);return wf({host:_,instrumentationProvider:p(J),component:"pie-section-player-kernel-host",eventMap:$m,staticAttributes:{instrumentationLayer:"section",assessmentId:r()?.assessmentId,sectionId:ju({sectionId:l(),section:o(),assessmentId:r()?.assessmentId}),attemptId:c()||void 0},shouldTrackEvent:B=>tg(B,_),dedupeWindowMs:100})});var z={getSnapshot:Y,navigateTo:Pe,navigateNext:M,navigatePrevious:H,getSectionController:ne,get runtime(){return r()},set runtime(_=null){r(_),N()},get ndsIcons(){return n()},set ndsIcons(_=void 0){n(_),N()},get locale(){return i()},set locale(_=""){i(_),N()},get section(){return o()},set section(_=null){o(_),N()},get session(){return s()},set session(_=null){s(_),N()},get assessment(){return a()},set assessment(_=null){a(_),N()},get sectionId(){return l()},set sectionId(_=""){l(_),N()},get attemptId(){return c()},set attemptId(_=""){c(_),N()},get iifeBundleHost(){return u()},set iifeBundleHost(_){u(_),N()},get debug(){return d()},set debug(_=void 0){d(_),N()},get baseHeadingLevel(){return f()},set baseHeadingLevel(_=void 0){f(_),N()},get showToolbar(){return h()},set showToolbar(_="false"){h(_),N()},get toolbarPosition(){return g()},set toolbarPosition(_="right"){g(_),N()},get toolRegistry(){return m()},set toolRegistry(_=null){m(_),N()},get sectionHostButtons(){return v()},set sectionHostButtons(_=[]){v(_),N()},get itemHostButtons(){return b()},set itemHostButtons(_=[]){b(_),N()},get passageHostButtons(){return I()},set passageHostButtons(_=[]){I(_),N()},get policies(){return C()},set policies(_=void 0){C(_),N()},get hooks(){return x()},set hooks(_=void 0){x(_),N()},get toolConfigStrictness(){return $()},set toolConfigStrictness(_=void 0){$(_),N()}},A=FY(),K=bn(A);$r(K,_=>be(P,_),()=>p(P));var Q=mr(K,2);return $r(Gf(Q,{get runtime(){return r()},get ndsIcons(){return n()},get locale(){return i()},get section(){return o()},get session(){return s()},get assessment(){return a()},get sectionId(){return l()},get attemptId(){return c()},get iifeBundleHost(){return u()},get debug(){return d()},get baseHeadingLevel(){return f()},get showToolbar(){return h()},get toolbarPosition(){return g()},get toolRegistry(){return m()},get sectionHostButtons(){return v()},get itemHostButtons(){return b()},get passageHostButtons(){return I()},get policies(){return C()},get hooks(){return x()},get toolConfigStrictness(){return $()},sourceCe:"pie-section-player-kernel-host",get host(){return p(V)},onElementPreloadRetry:ye,onElementPreloadError:te,children:(_,B)=>{var U=Ys(),fe=bn(U);_u(fe,t,"default",{},null),ht(_,U)},$$slots:{default:!0}}),_=>be(L,_,!0),()=>p(L)),ht(e,A),mn(z)}qY("pie-section-player-kernel-host",Tn(UY,{runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},session:{type:"Object"},assessment:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"}},["default"],["getSnapshot","navigateTo","navigateNext","navigatePrevious","getSectionController"],{mode:"open"},e=>ja(cg(xA)(e))));function qY(e,t){customElements.get(e)||customElements.define(e,t)}function WY(e){return!!e.pie}function VY(e){const t={...e.pie};e.instructorResources!==void 0&&t.instructorResources===void 0&&(t.instructorResources=e.instructorResources),e.defaultExtraModels!==void 0&&t.defaultExtraModels===void 0&&(t.defaultExtraModels=e.defaultExtraModels);const r={id:e.id,config:t};return e.passage&&(r.passage={id:e.passage.id,config:e.passage}),r}function SK(e,t={}){const r=WY(e)?VY(e):{id:e.id,config:e},n={identifier:e.id,item:r};return t.itemVId!==void 0&&(n.itemVId=t.itemVId),{section:{identifier:t.sectionId??e.id,assessmentItemRefs:[n]},session:t.session==null?null:{currentItemIndex:0,itemSessions:{[e.id]:t.session}}}}export{sb as DEFAULT_SECTION_PLAYER_POLICIES,S_ as DEFAULT_TOOL_MODULE_LOADERS,I_ as createPackagedToolRegistry,SK as sectionFromItem};