@readium/speech 0.10.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +5 -5
- package/build/index.js +1160 -1117
- package/package.json +2 -2
package/build/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=n=>{if(!n)return["",void 0];const e=n.replace(/_/g,"-");try{const t=new Intl.Locale(e);return[t.language.toLowerCase(),t.region?.toUpperCase()]}catch{const t=e.split("-");return[t[0].toLowerCase(),t[1]?.toUpperCase()]}},G={ar:{defaultRegion:"SA",availableRegions:["001","AE","AS","BH","DZ","EG","IQ","JO","KW","LB","LY","MA","OM","QA","SA","SY","TN","YE"],testUtterance:"مرحبًا، اسمي {name} وأنا صوت عربي."},bg:{defaultRegion:"BG",availableRegions:["BG"],testUtterance:"Здравейте, казвам се {name} и съм български глас."},bho:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, हमार नाम {name} ह आ हम भोजपुरी आवाज हईं"},bn:{defaultRegion:"IN",availableRegions:["BD","IN"],testUtterance:"হ্যালো, আমার নাম {name} এবং আমি একজন বাংলা ভয়েস।"},ca:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Hola, em dic {name} i sóc una veu catalana"},cmn:{defaultRegion:"CN",availableRegions:["CN","CTW","TW"],testUtterance:"你好,我的名字是 {name},我是普通话配音。"},cs:{defaultRegion:"CZ",availableRegions:["CZ"],testUtterance:"Dobrý den, jmenuji se {name} a jsem český hlas."},da:{defaultRegion:"DK",availableRegions:["DK"],testUtterance:"Hej, mit navn er {name} og jeg er en dansk stemme."},de:{defaultRegion:"DE",availableRegions:["AT","CH","DE"],testUtterance:"Hallo, mein Name ist {name} und ich bin eine deutsche Stimme."},el:{defaultRegion:"GR",availableRegions:["GR"],testUtterance:"Γεια σας, με λένε {name} και είμαι ελληνική φωνή."},en:{defaultRegion:"US",availableRegions:["AU","CA","GB","HK","IE","IN","KE","NG","NZ","PH","SG","TZ","US","ZA"],testUtterance:"Hello, my name is {name} and I am an English voice."},es:{defaultRegion:"ES",availableRegions:["AR","BO","CL","CO","CR","CU","DO","EC","ES","GQ","GT","HN","MX","NI","PA","PE","PR","PY","SV","US","UY","VE"],testUtterance:"Hola, mi nombre es {name} y soy una voz española."},eu:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Kaixo, nire izena {name} da eta euskal ahotsa naiz."},fa:{defaultRegion:"IR",availableRegions:["IR"],testUtterance:"سلام اسم من {name} و صدای فارسی هستم"},fi:{defaultRegion:"FI",availableRegions:["FI"],testUtterance:"Hei, nimeni on {name} ja olen suomalainen ääni."},fr:{defaultRegion:"FR",availableRegions:["BE","CA","CH","FR"],testUtterance:"Bonjour, mon nom est {name} et je suis une voix française."},gl:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Ola, chámome {name} e son unha voz galega."},he:{defaultRegion:"IL",availableRegions:["IL"],testUtterance:"שלום, שמי {name} ואני קול עברי."},hi:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, मेरा नाम {name} है और मैं एक हिंदी आवाज़ हूँ।"},hr:{defaultRegion:"HR",availableRegions:["HR"],testUtterance:"Pozdrav, ja sam {name} i hrvatski sam glas."},hu:{defaultRegion:"HU",availableRegions:["HU"],testUtterance:"Helló, a nevem {name} és magyar hangú vagyok."},id:{defaultRegion:"ID",availableRegions:["ID"],testUtterance:"Halo, nama saya {name} dan saya suara Indonesia."},it:{defaultRegion:"IT",availableRegions:["IT"],testUtterance:"Ciao, mi chiamo {name} e sono una voce italiana."},ja:{defaultRegion:"JP",availableRegions:["JP"],testUtterance:"こんにちは。私の名前は{name}で、日本語の声を担当しています。"},kk:{defaultRegion:"KZ",availableRegions:["KZ"],testUtterance:"Sälemetsiz be, meniñ atım {name} jäne men qazaq dawısımın."},kn:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"ಹಲೋ, ನನ್ನ ಹೆಸರು {name} ಮತ್ತು ನಾನು ಕನ್ನಡ ಧ್ವನಿ."},ko:{defaultRegion:"KR",availableRegions:["KR"],testUtterance:"안녕하세요, 저는 {name}이고 한국어 음성입니다."},mr:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, माझे नाव {name} आहे आणि मी एक मराठी आवाज आहे."},ms:{defaultRegion:"MY",availableRegions:["MY"],testUtterance:"Hello, nama saya {name} dan saya suara Melayu."},nb:{defaultRegion:"NO",availableRegions:["NO"],testUtterance:"Hei, jeg heter {name} og er en norsk stemme."},nl:{defaultRegion:"NL",availableRegions:["BE","NL"],testUtterance:"Hallo, mijn naam is {name} en ik ben een Nederlandse stem."},pl:{defaultRegion:"PL",availableRegions:["PL"],testUtterance:"Cześć, nazywam się {name} i mam polski głos."},pt:{defaultRegion:"BR",availableRegions:["BR","PT"],testUtterance:"Olá, o meu nome é {name} e sou uma voz portuguesa."},ro:{defaultRegion:"RO",availableRegions:["RO"],testUtterance:"Buna ziua, ma numesc {name} si sunt o voce romaneasca."},ru:{defaultRegion:"RU",availableRegions:["RU"],testUtterance:"Здравствуйте, меня зовут {name} и я русский голос."},sk:{defaultRegion:"SK",availableRegions:["SK"],testUtterance:"Dobrý deň, volám sa {name} a som slovenský hlas."},sl:{defaultRegion:"SI",availableRegions:["SI"],testUtterance:"Pozdravljeni, moje ime je {name} in sem slovenski glas."},sv:{defaultRegion:"SE",availableRegions:["SE"],testUtterance:"Hej, jag heter {name} och jag är en svensk röst."},ta:{defaultRegion:"IN",availableRegions:["IN","LK","MY","SG"],testUtterance:"வணக்கம், என் பெயர் {name} மற்றும் நான் ஒரு தமிழ் குரல்"},te:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"హలో, నా పేరు {name} మరియు నేను తెలుగు వాణిని."},th:{defaultRegion:"TH",availableRegions:["TH"],testUtterance:"สวัสดีค่ะ ฉันชื่อ {name} และฉันเป็นคนมีเสียงภาษาไทย"},tr:{defaultRegion:"TR",availableRegions:["TR"],testUtterance:"Merhaba, adım {name} ve Türk sesiyim."},uk:{defaultRegion:"UA",availableRegions:["UA"],testUtterance:"Здравствуйте, меня зовут {name} и я украинский голос."},vi:{defaultRegion:"VN",availableRegions:["VN"],testUtterance:"Xin chào, tôi tên là {name} và tôi là giọng nói tiếng Việt."},wuu:{defaultRegion:"CN",availableRegions:["CN"],testUtterance:"你好,我的名字是 {name},我是吴语配音。"},yue:{defaultRegion:"HK",availableRegions:["HK"],testUtterance:"你好,我叫 {name},係越中文聲。"}},Vt=new Map,zo=Object.assign({"../../json/ar.json":()=>Promise.resolve().then(()=>require("./ar-BYWkyZgW.cjs")),"../../json/bg.json":()=>Promise.resolve().then(()=>require("./bg-D7xe9YTl.cjs")),"../../json/bho.json":()=>Promise.resolve().then(()=>require("./bho-UB6aO8oz.cjs")),"../../json/bn.json":()=>Promise.resolve().then(()=>require("./bn-boRZ2pl5.cjs")),"../../json/ca.json":()=>Promise.resolve().then(()=>require("./ca-DkC8kSJ8.cjs")),"../../json/cmn.json":()=>Promise.resolve().then(()=>require("./cmn-BsNLjyA4.cjs")),"../../json/cs.json":()=>Promise.resolve().then(()=>require("./cs-p05r08p7.cjs")),"../../json/da.json":()=>Promise.resolve().then(()=>require("./da-crefCup9.cjs")),"../../json/de.json":()=>Promise.resolve().then(()=>require("./de-xoW-RuhZ.cjs")),"../../json/el.json":()=>Promise.resolve().then(()=>require("./el-C025sTug.cjs")),"../../json/en.json":()=>Promise.resolve().then(()=>require("./en-CbfmLXbR.cjs")),"../../json/es.json":()=>Promise.resolve().then(()=>require("./es-DW7IPf8I.cjs")),"../../json/eu.json":()=>Promise.resolve().then(()=>require("./eu-uq15ZgwW.cjs")),"../../json/fa.json":()=>Promise.resolve().then(()=>require("./fa-CHOnwiFr.cjs")),"../../json/fi.json":()=>Promise.resolve().then(()=>require("./fi-Bxlno6Zi.cjs")),"../../json/fr.json":()=>Promise.resolve().then(()=>require("./fr-yAth5-FC.cjs")),"../../json/gl.json":()=>Promise.resolve().then(()=>require("./gl-BEgzCAO0.cjs")),"../../json/he.json":()=>Promise.resolve().then(()=>require("./he-B-CTHJPL.cjs")),"../../json/hi.json":()=>Promise.resolve().then(()=>require("./hi-C0yUjV1-.cjs")),"../../json/hr.json":()=>Promise.resolve().then(()=>require("./hr-CZvFOcdo.cjs")),"../../json/hu.json":()=>Promise.resolve().then(()=>require("./hu-_2PInItj.cjs")),"../../json/id.json":()=>Promise.resolve().then(()=>require("./id-BROcb7-t.cjs")),"../../json/it.json":()=>Promise.resolve().then(()=>require("./it-Bmc8Ycff.cjs")),"../../json/ja.json":()=>Promise.resolve().then(()=>require("./ja-B8t6WOeg.cjs")),"../../json/kk.json":()=>Promise.resolve().then(()=>require("./kk-DskO1CW8.cjs")),"../../json/kn.json":()=>Promise.resolve().then(()=>require("./kn-Cy3NH6na.cjs")),"../../json/ko.json":()=>Promise.resolve().then(()=>require("./ko-CZdQzppZ.cjs")),"../../json/mr.json":()=>Promise.resolve().then(()=>require("./mr-9hGqBYlV.cjs")),"../../json/ms.json":()=>Promise.resolve().then(()=>require("./ms-DzpBxNFZ.cjs")),"../../json/nb.json":()=>Promise.resolve().then(()=>require("./nb-BQfw9EEH.cjs")),"../../json/nl.json":()=>Promise.resolve().then(()=>require("./nl-CyM0R4Gr.cjs")),"../../json/pl.json":()=>Promise.resolve().then(()=>require("./pl-Da8XOMa1.cjs")),"../../json/pt.json":()=>Promise.resolve().then(()=>require("./pt-tubyvYaM.cjs")),"../../json/ro.json":()=>Promise.resolve().then(()=>require("./ro-C-rXDfuM.cjs")),"../../json/ru.json":()=>Promise.resolve().then(()=>require("./ru-DJocRaDd.cjs")),"../../json/sk.json":()=>Promise.resolve().then(()=>require("./sk-BvpojIXp.cjs")),"../../json/sl.json":()=>Promise.resolve().then(()=>require("./sl-D0X3JKvQ.cjs")),"../../json/sv.json":()=>Promise.resolve().then(()=>require("./sv-4lEgrHda.cjs")),"../../json/ta.json":()=>Promise.resolve().then(()=>require("./ta-CyeVPdIs.cjs")),"../../json/te.json":()=>Promise.resolve().then(()=>require("./te-DqWIZZxL.cjs")),"../../json/th.json":()=>Promise.resolve().then(()=>require("./th-BcoSVZAp.cjs")),"../../json/tr.json":()=>Promise.resolve().then(()=>require("./tr-BuafNhfw.cjs")),"../../json/uk.json":()=>Promise.resolve().then(()=>require("./uk-DkXNxnD9.cjs")),"../../json/vi.json":()=>Promise.resolve().then(()=>require("./vi-Ct2avSE6.cjs")),"../../json/wuu.json":()=>Promise.resolve().then(()=>require("./wuu-DnwGQ6c-.cjs")),"../../json/yue.json":()=>Promise.resolve().then(()=>require("./yue-j9Y48sR-.cjs"))});async function Vo(n){try{const e=n.split("-")[0],t=zo[`../../json/${e}.json`];if(!t)throw new Error(`No voice data found for language: ${n}`);const s=(await t()).default;return{...s,voices:s.voices.map(qo)}}catch(e){return console.warn(`Failed to load voice data for ${n}:`,e),{language:n,defaultRegion:"",testUtterance:"",voices:[]}}}function ai(n){return Vt.has(n)||Vt.set(n,Vo(n)),Vt.get(n)}const jo=["veryLow","low","normal","high","veryHigh"],Ho=["android","apple"],qo=n=>({...n,quality:n.quality?.filter(e=>jo.includes(e)),localizedName:n.localizedName&&Ho.includes(n.localizedName)?n.localizedName:void 0}),xe={cmn:"cmn","cmn-CN":"cmn-CN","cmn-TW":"cmn-TW",zh:"cmn","zh-CN":"cmn-CN","zh-TW":"cmn-TW",yue:"yue","yue-HK":"yue-HK","zh-HK":"yue-HK",wuu:"wuu","wuu-CN":"wuu-CN"},U=n=>{if(!n)return"";let e=n.toLowerCase().replace(/_/g,"-");if(/\w{2,3}-\w{2,3}/.test(e)){const[t,i]=e.split("-");e=`${t.toLowerCase()}-${i.toUpperCase()}`}return xe[e]||e},tn=async n=>{if(!n)return[];try{const e=U(n);try{const i=await ai(e);if(i?.voices?.length)return i.voices}catch(i){console.warn(`Failed to load voices for ${e}:`,i)}const[t]=F(e);if(t!==e)try{const i=await ai(t);if(i?.voices?.length)return i.voices}catch(i){console.warn(`Failed to load voices for base language ${t}:`,i)}return[]}catch(e){return console.error(`Error in getVoices for ${n}:`,e),[]}},nn=(n,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(n)||n.toUpperCase()}catch{return n.toUpperCase()}},li=n=>{if(!n)return"";try{const e=U(n),t=G[e];if(t?.testUtterance)return t.testUtterance;if(e in xe){const s=xe[e];if(s&&G[s]?.testUtterance)return G[s].testUtterance}const[i]=F(e);return i!==e&&G[i]?.testUtterance?G[i].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${n}:`,e),""}},Pt=n=>{if(!n)return"";try{const e=U(n),t=G[e];if(t?.defaultRegion)return`${e}-${t.defaultRegion}`;if(e in xe){const s=xe[e];if(s){const r=G[s];if(r?.defaultRegion)return`${s}-${r.defaultRegion}`}}const[i]=F(e);if(i!==e){const s=G[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${n}:`,e),""}},Ft=n=>{if(!n?.length)return[];const e=new Set,t=new Map,i=new Map;for(const[s,r]of n.entries()){if(!r)continue;const o=U(r),[a,l]=F(o);l&&(e.add(l),i.has(l)||i.set(l,s)),t.has(a)||t.set(a,new Set),l&&t.get(a).add(l)}return Array.from(t.entries()).map(([s,r])=>{const o=new Set(G[s]?.availableRegions||[]),a=Array.from(r),l=Array.from(e).filter(u=>o.has(u)&&!a.includes(u)),c=Array.from(new Set([...a,...l])).sort((u,h)=>{const d=i.get(u)??Number.MAX_SAFE_INTEGER,f=i.get(h)??Number.MAX_SAFE_INTEGER;return d-f});if(c.length===0){const u=Pt(s),[,h]=F(u);h&&c.push(h)}return{baseLang:s,regions:c}})},Ee=async n=>{const e=new Map;for(const i of n){if(i.source!=="json")continue;const[s]=F(i.language);e.has(s)||e.set(s,[]),e.get(s).push(i)}const t=new Map;for(const[i,s]of e.entries()){const r=new Map,o=await tn(i),a=new Map;o.forEach((l,c)=>{a.set(l.name.toLowerCase(),c),l.altNames?.forEach(u=>{a.set(u.toLowerCase(),c)})});for(const l of s){const c=l.name.toLowerCase(),u=a.get(c);u!==void 0&&r.set(l.name,u)}r.size>0&&t.set(i,r)}return t},Wo={veryLow:1,low:2,normal:3,high:4,veryHigh:5},mt=n=>n?Wo[n]??0:0,oe=(n,e,t,i)=>{const s=mt(n.quality),r=mt(e.quality);if(t&&i&&n.source==="json"&&e.source==="json"){const o=t.get(i);if(o){const a=o.get(n.name),l=o.get(e.name);if(a!==void 0&&l!==void 0)return a-l}}return r!==s?r-s:n.name.localeCompare(e.name)},It=(n,e)=>{const t=new Map(e.map(r=>[r.baseLang,r])),i=new Map,s=[];for(const r of n){const[o]=F(r.language);t.get(o)?(i.has(o)||i.set(o,[]),i.get(o).push(r)):s.push(r)}return{voicesByLang:i,otherLangVoices:s}},As=(n,e,t,i)=>{const[,s]=F(n.language),[,r]=F(e.language),o=s&&t.regions.includes(s),a=r&&t.regions.includes(r);if(o&&a){const d=t.regions.indexOf(s),f=t.regions.indexOf(r);return d===f?oe(n,e,i,t.baseLang):d-f}if(o)return-1;if(a)return 1;const l=Pt(t.baseLang),[,c]=F(l),u=!!c&&s===c,h=!!c&&r===c;if(u&&!h)return-1;if(!u&&h)return 1;if(s&&r){const d=s.localeCompare(r);return d!==0?d:oe(n,e,i,t.baseLang)}return s?-1:r?1:oe(n,e,i,t.baseLang)},Ko=async(n,e,t)=>{const i=t??await Ee(n);n.sort((s,r)=>As(s,r,e,i))},Os=(n,e,t)=>{const[i]=F(n.language),[s]=F(e.language),r=nn(i).toLowerCase(),o=nn(s).toLowerCase(),a=r.localeCompare(o);if(a!==0)return a;if(i===s){const l=Pt(i),[,c]=F(n.language),[,u]=F(e.language),h=l&&c===l.split("-")[1],d=l&&u===l.split("-")[1];if(h&&!d)return-1;if(!h&&d)return 1;if(c&&u){const f=c.localeCompare(u);if(f!==0)return f}return c&&!u?-1:!c&&u?1:oe(n,e,t,i)}return oe(n,e,t,i)},sn=async(n,e)=>{const t=e??await Ee(n);n.sort((i,s)=>Os(i,s,t))},Go=async(n,e)=>{if(!e?.length)return[];const t=Ft(n||[]),{voicesByLang:i,otherLangVoices:s}=It(e,t),r=await Ee(e),o=[];for(const a of t){const l=i.get(a.baseLang);l&&(await Ko(l,a,r),o.push(...l))}return await sn(s,r),o.push(...s),o},Xo=async(n,e)=>{if(!e.length)return null;const[t]=Ft([n]),{voicesByLang:i,otherLangVoices:s}=It(e,[t]),r=i.get(t.baseLang),o=r?.length?r:s,a=await Ee(e),l=r?.length?(c,u)=>As(c,u,t,a):(c,u)=>Os(c,u,a);return o.reduce((c,u)=>l(u,c)<0?u:c)},Jo=[{name:"Albert",nativeID:["com.apple.speech.synthesis.voice.Albert"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bad News",nativeID:["com.apple.speech.synthesis.voice.BadNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Mauvaises nouvelles","Malas noticias","Brutte notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bahh",nativeID:["com.apple.speech.synthesis.voice.Bahh"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bells",nativeID:["com.apple.speech.synthesis.voice.Bells"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Cloches","Campanas","Campane"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Boing",nativeID:["com.apple.speech.synthesis.voice.Boing"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bubbles",nativeID:["com.apple.speech.synthesis.voice.Bubbles"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bulles","Burbujas","Bollicine"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Cellos",nativeID:["com.apple.speech.synthesis.voice.Cellos"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Violoncelles","Violonchelos","Violoncelli"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Good News",nativeID:["com.apple.speech.synthesis.voice.GoodNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bonnes nouvelles","Buenas noticias","Buone notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jester",nativeID:["com.apple.speech.synthesis.voice.Hysterical"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bouffon","Bufón","Giullare"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Organ",nativeID:["com.apple.speech.synthesis.voice.Organ"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Orgue","Órgano","Organo"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Superstar",nativeID:["com.apple.speech.synthesis.voice.Princess"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Superestrella"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Trinoids",nativeID:["com.apple.speech.synthesis.voice.Trinoids"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Trinoïdes"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Whisper",nativeID:["com.apple.speech.synthesis.voice.Whisper"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Murmure","Susurro","Sussurro"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Wobble",nativeID:["com.apple.speech.synthesis.voice.Deranged"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Zarvox",nativeID:["com.apple.speech.synthesis.voice.Zarvox"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0}],Yo={voices:Jo},Qo=[{name:"Eddy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Flo",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandma",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandpa",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jacques",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Reed",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Rocko",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Sandy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Shelley",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Fred",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Junior",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Kathy",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Ralph",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"eSpeak Arabic",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ar",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bulgarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bg",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bengali",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Catalan",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ca",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Chinese (Mandarin, latin as English)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cmn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Czech",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cs",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Danish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"da",os:["ChromeOS"],preloaded:!0},{name:"eSpeak German",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"de",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Greek",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"el",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Spanish (Spain)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"es",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Estonian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"et",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Finnish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"fi",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Gujarati",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"gu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Croatian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Hungarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Indonesian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"id",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Italian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"it",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Kannada",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"kn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Korean",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ko",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Lithuanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lt",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Latvian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malayalm",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ml",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Marathi",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"mr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malay",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ms",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Norwegian Bokmål",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"nb",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Polish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Portuguese (Brazil)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pt-br",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Romanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ro",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Russian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ru",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovak",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sk",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovenian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Serbian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swedish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swahili",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sw",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Tamil",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ta",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Telugu",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"te",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Turkish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"tr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Vietnamese (Northern)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"vi",os:["ChromeOS"],preloaded:!0}],Zo={voices:Qo},ea=Yo,ta=Zo,rn=(n,e)=>ea.voices.some(t=>n.includes(t.name)||e&&t.nativeID?.some(i=>e.includes(i))||t.altNames?.some(i=>n.includes(i))),on=(n,e)=>ta.voices.some(t=>n.includes(t.name))||e==="veryLow",ci=n=>n?.length?n.filter(e=>!(e.isNovelty||rn(e.name,e.voiceURI))):[],ui=n=>n?.length?n.filter(e=>!on(e.name,e.quality)):[],na={ar:{normal:"محسن",high:"استثنائي"},ca:{normal:"millorada",high:"prèmium"},"cmn-CN":{normal:"优化音质",high:"高音质"},"cmn-TW":{normal:"增強音質",high:"高音質"},cs:{normal:"vylepšená verze",high:"prémiový"},da:{normal:"forbedret",high:"høj kvalitet"},de:{normal:"erweitert",high:"premium"},el:{normal:"βελτιωμένη",high:"υψηλής ποιότητας"},en:{normal:"Enhanced",high:"Premium"},es:{normal:"mejorada",high:"premium"},fi:{normal:"parannettu",high:"korkealaatuinen"},fr:{normal:"premium",high:"de qualité"},he:{normal:"משופר",high:"פרימיום"},hi:{normal:"बेहतर",high:"प्रीमियम"},hr:{normal:"poboljšani",high:"vrhunski"},hu:{normal:"továbbfejlesztett",high:"prémium"},id:{normal:"Ditingkatkan",high:"Premium"},it:{normal:"ottimizzata",high:"premium"},ja:{normal:"拡張",high:"プレミアム"},ko:{normal:"고품질",high:"프리미엄"},ms:{normal:"Dipertingkat",high:"Premium"},nb:{normal:"forbedret",high:"premium"},nl:{normal:"verbeterd",high:"premium"},pl:{normal:"rozszerzony",high:"premium"},pt:{normal:"melhorada",high:"premium"},ro:{normal:"îmbunătățită",high:"premium"},ru:{normal:"улучшенный",high:"высшее качество"},sk:{normal:"vylepšený",high:"prémiový"},sl:{normal:"izboljšano",high:"prvovrsten"},sv:{normal:"förbättrad",high:"premium"},th:{normal:"คุณภาพสูง",high:"คุณภาพสูง"},tr:{normal:"Geliştirilmiş",high:"Yüksek Kaliteli"},uk:{normal:"вдосконалений",high:"високої якості"},vi:{normal:"Nâng cao",high:"Cao cấp"}},ia={quality:na},an={apple:ia.quality},sa=(n,e,t)=>{if(!n)return;const i=Array.isArray(t)?t:t?[t]:[];for(const s of i)if(s&&an[s]){const r=an[s],o=F(e)[0],a=r[e]||r[o];if(a){const l=n.toLowerCase(),{normal:c,high:u}=a;if(u&&l.includes(u.toLowerCase()))return"high";if(c&&l.includes(c.toLowerCase()))return"normal"}}},ra=(n,e)=>{const t=an[e];if(t)for(const[i,{high:s,normal:r}]of Object.entries(t)){const o=s&&n.some(l=>l.includes(s)),a=r&&n.some(l=>l.includes(r));if(o&&a)return i}},oa={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},hi=n=>{if(!n)return;const t=n.toLowerCase().split(/[._-]/);for(const i of Object.values(oa))if(i.values.some(s=>t.includes(s)))return i.quality};function aa(n,e){if(n.name===n.originalName)return n;if(e.name===e.originalName)return e;const t=[n.originalName,...n.altNames||[]],i=[e.originalName,...e.altNames||[]],s=t.findIndex(o=>i.includes(o)),r=i.findIndex(o=>t.includes(o));return s===-1&&r===-1||s!==-1&&(r===-1||s<=r)?n:e}function la(n,e){if(!n.altNames&&!e.altNames)return!1;const t=n.originalName,i=e.originalName,s=n.altNames||[],r=e.altNames||[];return r.includes(t)||s.includes(i)?!0:s.filter(a=>r.includes(a)).length>0}class T{static instance;static initializationPromise=null;systemLocale;voices=[];browserVoices=[];isInitialized=!1;scopedLanguages=null;broadenPromises=new Map;constructor(){if(typeof window>"u"||!window.speechSynthesis)throw new Error("Web Speech API is not available in this environment");this.systemLocale=navigator.languages?.[0]?.split("-")[0]||"en"}static async initialize(e){if(T.instance?.isInitialized){const t=T.instance;return e?.languages&&e.languages.length>0&&await t.broadenLanguages(e.languages),t}return T.initializationPromise||(T.initializationPromise=(async()=>{try{const t=new T;T.instance=t,t.browserVoices=await t.getBrowserVoices(e?.maxTimeout,e?.interval),t.updateSystemLocale(t.browserVoices);let i=t.browserVoices;return e?.languages&&e.languages.length>0?(i=t.filterBrowserVoicesByLanguages(t.browserVoices,e.languages),t.scopedLanguages=T.toBaseLangSet(e.languages)):t.scopedLanguages=null,t.voices=await t.parseToReadiumSpeechVoices(i),t.isInitialized=!0,t}catch(t){throw T.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",t),t}})()),T.initializationPromise}filterBrowserVoicesByLanguages(e,t){if(!t?.length)return e;const i=T.toBaseLangSet(t);return e.filter(s=>{if(!s?.lang)return!1;const r=U(s.lang),[o]=T.extractLangRegionFromBCP47(r);return i.has(o)})}static toBaseLangSet(e){return new Set(e.map(t=>{const i=U(t),[s]=T.extractLangRegionFromBCP47(i);return s}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const i=[...T.toBaseLangSet(e)].filter(a=>!this.scopedLanguages.has(a));if(i.length===0)return;const s=i.filter(a=>this.broadenPromises.has(a)),r=i.filter(a=>!this.broadenPromises.has(a));let o;r.length>0&&(o=(async()=>{const a=this.filterBrowserVoicesByLanguages(this.browserVoices,r),l=await this.parseToReadiumSpeechVoices(a);this.voices=[...this.voices,...l],r.forEach(c=>this.scopedLanguages.add(c)),r.forEach(c=>this.broadenPromises.delete(c))})(),r.forEach(a=>this.broadenPromises.set(a,o))),await Promise.all([...o?[o]:[],...s.map(a=>this.broadenPromises.get(a))])}static extractLangRegionFromBCP47(e){return F(e)}cleanVoiceName(e){return e?e.replace(/\s*\([^)]*\)/g,"").replace(/[^\p{L}\p{N}\s-]/gu,"").replace(/\s+/g," ").trim():""}normalizeVoiceName(e){return this.cleanVoiceName(e.toLowerCase())}countVoiceDuplicates(e){const t=new Map;for(const i of e){if(!i?.name||!i?.lang)continue;const s=`${i.lang.toLowerCase()}_${this.normalizeVoiceName(i.name)}`;t.set(s,(t.get(s)||0)+1)}return t}updateSystemLocale(e){if(!e?.length)return;const t=e.map(s=>s.name),i=ra(t,"apple");i&&(this.systemLocale=i)}inferVoiceQuality(e,t,i){const s=e.voiceURI?hi(e.voiceURI):void 0;if(s)return s;if(t?.nativeID&&Array.isArray(t.nativeID))for(const r of t.nativeID){const o=hi(r);if(o)return o}if(t?.localizedName&&e.voiceURI&&e.lang){const r=sa(e.voiceURI,this.systemLocale,t.localizedName);if(r)return r}if(t?.quality&&t.quality.length>0){const r=Math.min(i-1,t.quality.length-1),o=t.quality[r];if(o)return o}return null}findMatchingJsonVoice(e,t){return e.find(i=>this.normalizeVoiceName(i.name)===t||i.altNames?.some(s=>this.normalizeVoiceName(s)===t))}removeDuplicates(e){const t=new Map;for(const i of e){const s=`${i.language.toLowerCase()}_${this.normalizeVoiceName(i.name)}`,r=t.get(s);if(!r)t.set(s,i);else if(la(i,r)){const o=aa(i,r);t.set(s,o)}else{const o=mt(r.quality);mt(i.quality)>=o&&t.set(s,i)}}return Array.from(t.values())}getTestUtterance(e){if(!e)return"";const t=li(e);if(t)return t;const[i]=T.extractLangRegionFromBCP47(e);if(i&&i!==e){const s=li(i);if(s)return s}return""}getVoices(e={}){if(!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");return this.filterVoices(e,[...this.voices])}getLanguages(e,t,i){if(!i&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const s=i??this.voices,r=t?this.filterVoices(t,s):s,o=[],a=new Set;for(const l of r){const u=U(l.language).split("-")[0];if(!a.has(u)){const h=nn(u,e),d=r.filter(f=>U(f.language).split("-")[0]===u).length;o.push({code:u,label:h,count:d}),a.add(u)}}return i?o:o.sort((l,c)=>l.label.localeCompare(c.label))}getRegions(e,t,i){if(!i&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const s=i??this.voices,r=t?this.filterVoices(t,s):s,o=[],a=new Set,l=new Map;for(const c of r){const[,u]=T.extractLangRegionFromBCP47(c.language);u&&l.set(u,(l.get(u)||0)+1)}for(const c of r){const[,u]=T.extractLangRegionFromBCP47(c.language);if(u&&!a.has(u)){let h=c.language;try{const d=e||navigator.language;h=new Intl.DisplayNames([d],{type:"region"}).of(u)||c.language}catch(d){console.warn(`Failed to get display name for region ${u}`,d)}o.push({code:u,label:h,count:l.get(u)||0}),a.add(u)}}return i?o:o.sort((c,u)=>c.label.localeCompare(u.label))}async getDefaultVoice(e,t){if(!e)return null;const i=Array.isArray(e)?e:[e];let s=t||this.getVoices({languages:i});return s.length?(s=await this.sortVoicesByRegions(i,s),s[0]):null}getBrowserVoices(e=1e4,t=10){const i=()=>window.speechSynthesis?.getVoices()||[];if(!window.speechSynthesis)return Promise.resolve([]);const s=i();return Array.isArray(s)&&s.length?Promise.resolve(s):new Promise((r,o)=>{let a=Math.floor(e/t),l=!1;const c=()=>{if(l)return;l=!0;const u=()=>{if(a<1)return r([]);--a;const h=i();if(Array.isArray(h)&&h.length)return r(h);setTimeout(u,t)};setTimeout(u,t)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const u=i();Array.isArray(u)&&u.length?r(u):c()}:c(),setTimeout(()=>r([]),e)})}async parseToReadiumSpeechVoices(e){const t=this.countVoiceDuplicates(e);return await Promise.all(e.filter(s=>s?.name&&s?.lang).map(async s=>{const r=U(s.lang),[o]=T.extractLangRegionFromBCP47(r),a=this.normalizeVoiceName(s.name),l=`${s.lang.toLowerCase()}_${a}`,c=t.get(l)||1;let u=await tn(r);(!u||u.length===0)&&(u=await tn(o));const h=this.findMatchingJsonVoice(u,a),d=this.inferVoiceQuality(s,h,c);return h?{...h,label:h.label??this.cleanVoiceName(s.name),source:"json",originalName:s.name,language:h.language??r,voiceURI:s.voiceURI,quality:d,isDefault:s.default||!1,offlineAvailability:s.localService||!1,isNovelty:rn(s.name,s.voiceURI),isLowQuality:on(s.name,d)}:{source:"browser",label:this.cleanVoiceName(s.name),name:s.name,originalName:s.name,language:r,voiceURI:s.voiceURI,quality:d,isDefault:s.default||!1,offlineAvailability:s.localService||!1,isNovelty:rn(s.name,s.voiceURI),isLowQuality:on(s.name,d)}}))}convertToSpeechSynthesisVoice(e){if(e)return this.browserVoices.find(t=>t.voiceURI===e.voiceURI||t.name===e.originalName||this.normalizeVoiceName(t.name)===this.normalizeVoiceName(e.name))}filterVoices(e,t){let i=t?[...t]:[...this.voices];const s={excludeNovelty:!0,excludeVeryLowQuality:!0,removeDuplicates:!0,...e};if(s.languages){const r=Array.isArray(s.languages)?s.languages:[s.languages];i=i.filter(o=>r.some(a=>{const l=a.toLowerCase(),c=o.language?.toLowerCase(),u=o.altLanguage?.toLowerCase();if(c===l||u===l)return!0;const[h]=l.split("-");return c&&c.startsWith(h)||u&&u.startsWith(h)}))}if(s.source&&(i=i.filter(r=>r.source===s.source)),s.gender&&(i=i.filter(r=>r.gender===s.gender)),s.quality){const r=Array.isArray(s.quality)?s.quality:[s.quality];i=i.filter(o=>o.quality&&r.includes(o.quality))}return s.offlineOnly&&(i=i.filter(r=>r.offlineAvailability===!0)),s.provider&&(i=i.filter(r=>r.provider?.toLowerCase()===s.provider?.toLowerCase())),s.excludeNovelty&&(i=ci(i)),s.excludeVeryLowQuality&&(i=ui(i)),s.removeDuplicates&&(i=this.removeDuplicates(i)),i}filterOutNoveltyVoices(e){const t=e??this.voices;return ci(t)}filterOutVeryLowQualityVoices(e){const t=e??this.voices;return ui(t)}async sortVoicesByQuality(e){const t=e||this.voices;if(!t?.length)return[];const i=await Ee(t);return[...t].sort((s,r)=>oe(s,r,i))}static async sortByDefaultRegion(e,t){const i=await Ee(e),s=Pt(t);e.sort((r,o)=>{const[,a]=T.extractLangRegionFromBCP47(r.language),[,l]=T.extractLangRegionFromBCP47(o.language),c=s&&a===s.split("-")[1],u=s&&l===s.split("-")[1];return c&&!u?-1:!c&&u?1:oe(r,o,i,t)})}async sortVoicesByLanguages(e,t){const i=t||this.voices;if(!i?.length)return[];if(!e?.length){const l=[...i];return await sn(l),l}const s=Ft(e),{voicesByLang:r,otherLangVoices:o}=It(i,s),a=[];for(const l of s){const c=r.get(l.baseLang);c&&(await T.sortByDefaultRegion(c,l.baseLang),a.push(...c))}return await sn(o),a.push(...o),a}async sortVoicesByRegions(e,t){return Go(e,t||this.voices)}groupVoices(e,t){const i={},s=t||this.voices;for(const r of s){let o="Unknown";switch(e){case"languages":o=T.extractLangRegionFromBCP47(r.language)[0];break;case"gender":o=r.gender||"unknown";break;case"quality":o=r.quality||"unknown";break;case"region":const[,a]=T.extractLangRegionFromBCP47(r.language);o=a||"unknown";break}i[o]||(i[o]=[]),i[o].push(r)}return i}}const ca=["webKit","moz","ms","o"],ua=["boundary","end","error","mark","pause","resume","start"],ha=n=>`${n.charAt(0).toUpperCase()}${n.slice(1)}`,Ie=(n={},e)=>Object.hasOwnProperty.call(n,e)||e in n||!!n[e],da=n=>typeof window<"u"&&n in window,fa=n=>{const e=ha(n),t=ca.map(s=>`${s}${e}`),i=[n,e].concat(t).find(da);return i&&typeof window<"u"?window[i]:void 0},ga=()=>{const n={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(t=>{n[t]=fa(t)}),n.onvoiceschanged=Ie(n.speechSynthesis,"onvoiceschanged"),n.speechSynthesisSpeaking=Ie(n.speechSynthesis,"speaking"),n.speechSynthesisPaused=Ie(n.speechSynthesis,"paused");const e=n.speechSynthesisUtterance?Ie(n.speechSynthesisUtterance,"prototype"):!1;return ua.forEach(t=>{const i=`on${t}`;n[i]=e&&n.speechSynthesisUtterance?Ie(n.speechSynthesisUtterance.prototype,i):!1}),n},pa=()=>{const e=typeof window<"u"&&(window.navigator||{}).userAgent||"",t=()=>/android/i.test(e),i=()=>/kaios/i.test(e),s=()=>typeof window.InstallTrigger<"u"?!0:/firefox/i.test(e),r=()=>typeof window.GestureEvent<"u"||/safari/i.test(e);return{isAndroid:t(),isFirefox:s()||i(),isSafari:r(),isKaiOS:i()}};let Lt=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>{const i=this.listeners.get(e);if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1)}}}emit(e,t){const i=this.listeners.get(e);i&&[...i].forEach(s=>{try{s(t)}catch(r){console.error(`Error in "${String(e)}" listener:`,r)}})}clear(){this.listeners.clear()}};const dt=(n,e)=>Math.min(Math.max(n,0),Math.max(e-1,0));function ae(n,e,t,i){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):i}const ye="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",ln="\\p{Ps}\\p{Pi}¿¡",ma=new RegExp(`^[${ye}]`,"u"),Sa=new RegExp(`^[${ln}]`,"u"),va=new RegExp("^\\p{P}$","u");function Oe(n){return ma.test(n)}function ya(n){return Sa.test(n)}function ba(n){return va.test(n)}function Ts(n){return n.replace(/[<>]/g,"")}function wa(n){return n.replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>String.fromCodePoint(parseInt(t,16)))}function Je(n){return n.plain===""&&n.ssml===""&&n.language===""}function xa(n){if(!n||Je(n))return;if(n.ssml===""&&n.language==="")return n.plain;const e={language:n.language};return n.plain!==""&&(e.plain=n.plain),n.ssml!==""&&(e.ssml=n.ssml),e}function Ea(n,e){if(n.lang!==e.lang||n.tag!==e.tag)return!1;const t=Object.entries(n.attrs??{}),i=Object.entries(e.attrs??{});return t.length!==i.length?!1:t.every(([s,r])=>e.attrs?.[s]===r)}const X=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),jt=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ca=/[\u00A0\u2007\u202F]/;function ka(n){return Ca.test(n)}function Ce(n,e){let t="",i=!1,s=!1;for(const r of n)if(ka(r))t+=r,i=!1,s=!0;else if(/\s/.test(r)){if(e&&!s||i)continue;t+=" ",i=!0}else r!==""&&r!==""&&(t+=r,i=!1,s=!0);return t}const Ra=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function Aa(n){return n.replace(Ra,(t,i,s)=>{const r=s.slice(i+t.length);return r.length===0||Oe(r)?"":" "}).replace(/ {2,}/g," ").trim()}function Oa(n){return n.includes("<")}function Pn(n){if(n===void 0)return;if(typeof n=="string")return{plain:n};const e={language:n.language};if(n.ssml){const t=Aa(n.ssml);Oa(t)&&(e.ssml=t)}return n.plain&&(e.plain=n.plain),e.plain||e.ssml?e:void 0}function le(n){return Ns(n).plain}function Ns(n){let e="";const t=[];let i=!1,s=0;for(;s<n.length;){const a=n[s];if(a==="<"){const c=n.indexOf(">",s),u=c===-1?"":n.slice(c+1);s=c===-1?n.length:c+1,!i&&e.length>0&&u.length>0&&!Oe(u)&&(e+=" ",t.push(s),i=!0);continue}const l=n.startsWith("<",s)?"<":n.startsWith(">",s)?">":n.startsWith("&",s)?"&":void 0;if(l){e+=l,t.push(s),s+=l==="&"?5:4,i=!1;continue}if(a===" "){i||(e+=a,t.push(s),i=!0),s++;continue}e+=a,t.push(s),i=!1,s++}let r=0;for(;r<e.length&&/\s/.test(e[r]);)r++;let o=e.length;for(;o>r&&/\s/.test(e[o-1]);)o--;return{plain:e.slice(r,o),map:t.slice(r,o)}}function di(n,e){let t=0,i=n.length;for(;t<i;){const s=t+i>>1;n[s]<e?t=s+1:i=s}return t}const fi=new WeakMap;function Ta(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Na(n){const e=Ta(n),t=/\w/.test(n[0])?"(?<!\\w)":"",i=/\w/.test(n[n.length-1])?"(?!\\w)":"";return`${t}${e}${i}`}function Da(n,e){if(typeof e=="string")return{regex:new RegExp(Na(n),"g"),replace:e};const t=e.pattern.flags.includes("g")?e.pattern.flags:`${e.pattern.flags}g`;return{regex:new RegExp(e.pattern.source,t),replace:e.replace}}function Pa(n){let e=fi.get(n);return e||(e=Object.entries(n).map(([t,i])=>Da(t,i)),fi.set(n,e)),e}function Ds(n,e){const t=[];for(const r of Pa(e))for(const o of n.matchAll(r.regex)){const a=o.index,l=typeof r.replace=="string"?r.replace:r.replace(...o);t.push({start:a,end:a+o[0].length,replacement:l})}t.sort((r,o)=>r.start-o.start);const i=[];let s=0;for(const r of t)r.start<s||(i.push(r),s=r.end);return i}function Fa(n,e){let t="";const i=[];let s=0;for(const r of Ds(n,e)){for(;s<r.start;)t+=n[s],i.push(s),s++;for(let o=0;o<r.replacement.length;o++)t+=r.replacement[o],i.push(r.start);s=r.end}for(;s<n.length;)t+=n[s],i.push(s),s++;return{text:t,map:i}}function gi(n,e){return n.length?e<=0?n[0]:e>=n.length?n[n.length-1]+1:n[e]:e}const Ia=/<([a-zA-Z][\w-]*)([^>]*)>([\s\S]*?)<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function pi(n){return n.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Ps(n){const e=[];for(const t of n.matchAll(Ia))t[1]!==void 0?e.push({kind:"paired",raw:t[0],tag:t[1],attrs:t[2],innerText:pi(t[3])}):t[0][0]==="<"?e.push({kind:"selfClosing",raw:t[0]}):e.push({kind:"text",raw:t[0],text:pi(t[0])});return e}function La(n,e){const t=Ps(n);let i="",s=!1;const r=[],o=t.map(()=>[]);t.forEach((b,C)=>{if(b.kind==="selfClosing")return;const R=b.kind==="paired"?b.innerText:b.text;if(!s&&i.length>0&&R.length>0&&!Oe(R)&&!/^\s/.test(R)){const N=i.length;i+=" ",o[C].push(r.length),r.push({start:N,end:N+1,atomIndex:-1}),s=!0}const A=i.length;i+=R,o[C].push(r.length),r.push({start:A,end:i.length,atomIndex:C}),R.length>0&&(s=/\s$/.test(R))});const a=Ds(i,e);let l="",c="";const u=[];let h=-2,d="",f=0;const g=()=>{if(h>=0){const b=t[h];l+=b.kind==="paired"?`<${b.tag}${b.attrs}>${d}</${b.tag}>`:d}d="",h=-2};for(let b=0;b<t.length;b++){const C=t[b];if(C.kind==="selfClosing"){g(),l+=C.raw;continue}for(const R of o[b]){const A=r[R];let N=A.start;for(;N<A.end;){const O=f<a.length?a[f]:void 0;if(O&&O.start<=N&&O.end>N){const P=O.start===N,$=O.end>A.end;if(P){c+=O.replacement;for(let De=0;De<O.replacement.length;De++)u.push(O.start);A.atomIndex===-1||$?(g(),l+=X(O.replacement)):(h!==A.atomIndex&&(g(),h=A.atomIndex),d+=X(O.replacement))}N=Math.min(O.end,A.end),O.end<=A.end&&f++;continue}const tt=O?Math.min(O.start,A.end):A.end,he=i.slice(N,tt);c+=he;for(let P=0;P<he.length;P++)u.push(N+P);A.atomIndex===-1?(g(),l+=X(he)):(h!==A.atomIndex&&(g(),h=A.atomIndex),d+=X(he)),N=tt}}}g();let p=0;for(;p<i.length&&/\s/.test(i[p]);)p++;let m=i.length;for(;m>p&&/\s/.test(i[m-1]);)m--;let y=0;for(;y<c.length&&/\s/.test(c[y]);)y++;let w=c.length;for(;w>y&&/\s/.test(c[w-1]);)w--;const S=i.slice(p,m),v=u.slice(y,w).map(b=>Math.min(Math.max(b-p,0),Math.max(S.length-1,0)));return{ssml:l,plain:S,map:v}}const Fs=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function Is(n){return new RegExp(Fs).test(n)}function mi(n){return n.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const $a=new RegExp(`\\s+|[${ln}]+|[${ye}]+|[^\\s${ln}${ye}]+`,"gu");function Ht(n){const e=[];for(const[t]of n.matchAll($a))/^\s/.test(t)?e.push({kind:"space"}):ya(t)?e.push({kind:"open",text:t}):Oe(t)?e.push({kind:"close",text:t}):e.push({kind:"word",text:t});return e}function Ma(n){let e="",t=!1;for(const i of n){if(i.kind==="space"){e&&(t=!0);continue}t&&(e+=" "),e+=i.text,t=!1}return e}function _a(n){let e=n.length;for(;e>0&&(n[e-1].kind==="space"||n[e-1].kind==="open");)e--;return n.slice(e).some(t=>t.kind==="open")?n.splice(e):[]}function Ba(n){let e=0;for(;e<n.length&&(n[e].kind==="space"||n[e].kind==="close");)e++;return n.slice(0,e).some(t=>t.kind==="close")?n.splice(0,e):[]}function Ls(n,e){const t=[];let i=0;for(const o of n.matchAll(Fs))t.push({tokens:Ht(mi(n.slice(i,o.index))),language:e,tagged:!1}),t.push({tokens:Ht(le(o[2])),language:o[1],tagged:!0}),i=o.index+o[0].length;t.push({tokens:Ht(mi(n.slice(i))),language:e,tagged:!1});for(let o=0;o<t.length-1;o++)!t[o].tagged&&t[o+1].tagged?t[o+1].tokens.unshift(..._a(t[o].tokens)):t[o].tagged&&!t[o+1].tagged&&t[o].tokens.push(...Ba(t[o+1].tokens));const s=[];let r=0;for(const o of t){const a=Ma(o.tokens);a&&(s.push({plain:a,language:o.language,start:r,end:r+a.length}),r+=a.length)}return s}const $s=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function Ua(n){return new RegExp($s).test(n)}function za(n){const e=[];let t=0;for(const s of n.matchAll($s)){const r=n.slice(t,s.index).trim();r&&e.push({ssml:r}),e.push({placeholderId:s[1]}),t=s.index+s[0].length}const i=n.slice(t).trim();return i&&e.push({ssml:i}),e}class cn{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Lt;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;restartPending=!1;isPausedInternal=!1;isAndroidPaused=!1;pausedAtUtteranceIndex=null;initialized=!1;maxLengthExceeded="warn";utterancesBeingCancelled=!1;rate=1;pitch=1;volume=1;features;patches;constructor(){if(this.features=ga(),this.patches=pa(),!this.features.speechSynthesis||!this.features.speechSynthesisUtterance)throw new Error("Web Speech API is not available in this environment");this.speechSynthesis=this.features.speechSynthesis,this.speechSynthesisUtterance=this.features.speechSynthesisUtterance}shouldUseResumeInfinity(){const e=this.currentVoice,t=!!(e?.name&&typeof e.name=="string"&&e.name.toLocaleLowerCase().includes("(natural)"));return this.patches.isAndroid!==!0&&!this.patches.isFirefox&&!this.patches.isSafari&&!t}createUtterance(e){return new this.speechSynthesisUtterance(e)}async initialize(e={}){const{languages:t,maxTimeout:i,interval:s,maxLengthExceeded:r="warn"}=e;if(this.initialized)return!1;this.maxLengthExceeded=r;try{this.voiceManager=await T.initialize({languages:t,maxTimeout:i,interval:s}),this.voices=this.voiceManager.getVoices();const o=t||[...navigator.languages||["en"]];return this.defaultVoice=await this.voiceManager.getDefaultVoice(o,this.voices),this.initialized=!0,!0}catch(o){return console.error("Failed to initialize WebSpeechEngine:",o),this.initialized=!1,!1}}validateText(e){if(new TextEncoder().encode(e).length>4096){const i="Text exceeds max length of 4096 bytes, which may not work with some voices.";switch(this.maxLengthExceeded){case"none":break;case"error":throw new Error(`WebSpeechEngine: ${i}`);default:console.warn(`WebSpeechEngine: ${i}`)}}}getCurrentVoiceForUtterance(e){return e&&typeof e=="object"?e:typeof e=="string"?this.voices.find(t=>t.name===e||t.language===e)||null:this.currentVoice||this.defaultVoice}voiceMatchesLanguage(e,t){const[i,s]=F(t),[r,o]=F(e.language);return r===i&&(!s||o===s)}voiceForUtteranceSync(e){const t=this.getCurrentVoiceForUtterance(this.currentVoice);if(!this.speakInContentLanguage||!e.language)return t;const i=U(e.language);if(t&&this.voiceMatchesLanguage(t,i))return t;if(this.languageVoiceCache.has(i))return this.languageVoiceCache.get(i)??t}async voiceForUtterance(e){const t=this.voiceForUtteranceSync(e);return t!==void 0?t:(await this.warmLanguageVoiceCache([e]),this.voiceForUtteranceSync(e)??this.getCurrentVoiceForUtterance(this.currentVoice))}async warmLanguageVoiceCache(e){if(!this.speakInContentLanguage||!this.voiceManager)return;const t=new Set(e.map(o=>o.language).filter(o=>!!o).map(o=>U(o)).filter(o=>!this.languageVoiceCache.has(o))),i=[...t].filter(o=>this.warmingLanguages.has(o)),r=[...t].filter(o=>!this.warmingLanguages.has(o)).map(o=>{const a=(async()=>{await T.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const l=this.voices.filter(h=>this.voiceMatchesLanguage(h,o)),u=(await this.voiceManager.sortVoicesByQuality(l))[0]??null;this.languageVoiceCache.set(o,u),u||this.emitEvent({type:"languagefallback",detail:{language:o,reason:"no-matching-voice"}})})();return this.warmingLanguages.set(o,a.finally(()=>this.warmingLanguages.delete(o))),this.warmingLanguages.get(o)});await Promise.all([...r,...i.map(o=>this.warmingLanguages.get(o))])}getCurrentVoice(){return this.currentVoice}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,e&&this.warmLanguageVoiceCache(this.currentUtterances)}getSpeakInContentLanguage(){return this.speakInContentLanguage}toPlainText(e){return e.map(t=>({...t,plain:t.plain??(t.ssml?le(wa(t.ssml)):"")}))}loadUtterances(e,t){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=dt(t??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="ready",this.emitEvent({type:"ready"})}async setVoice(e){const t=this.currentVoice;if(typeof e=="string"){const i=this.voices.find(s=>s.name===e||s.language===e);i?(this.currentVoice=i,t&&t.name!==i.name&&(this.currentUtteranceIndex=0)):console.warn(`Voice "${e}" not found`)}else this.currentVoice=e,t&&t.name!==e.name&&(this.currentUtteranceIndex=0);this.voiceManager&&this.defaultVoice&&this.currentVoice&&this.currentVoice.language!==this.defaultVoice.language&&(this.defaultVoice=await this.voiceManager.getDefaultVoice([this.currentVoice.language],this.voices))}async getAvailableVoices(){if(this.voices.length>0)return this.voices;try{return await this.initialize(),this.voices}catch{return[]}}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.cancelCurrentSpeech();const t=++this.speakGeneration;this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length&&(this.currentUtteranceIndex=0),this.speakCurrentUtterance(t)}cancelCurrentSpeech(){this.patches.isFirefox&&this.speechSynthesis.speaking&&(this.utterancesBeingCancelled=!0,setTimeout(()=>{this.utterancesBeingCancelled=!1},100)),this.speechSynthesis.cancel()}async speakCurrentUtterance(e){if(this.currentUtteranceIndex>=this.currentUtterances.length){this.setState("idle"),this.emitEvent({type:"end"});return}const t=this.currentUtterances[this.currentUtteranceIndex],i=t.plain??"";this.validateText(i);const s=this.createUtterance(Ts(i)),r=await this.voiceForUtterance(t);if(e===this.speakGeneration){if(r&&this.voiceManager){const o=this.voiceManager.convertToSpeechSynthesisVoice(r);o&&(s.voice=o,s.lang=o.lang)}t.language&&(s.lang=t.language),s.rate=this.rate,s.pitch=this.pitch,s.volume=this.volume,s.onstart=()=>{this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.patches.isAndroid&&this.isAndroidPaused&&(this.isAndroidPaused=!1),this.shouldUseResumeInfinity()&&this.startResumeInfinity(s)},s.onend=()=>{if(this.utterancesBeingCancelled){this.utterancesBeingCancelled=!1;return}this.playbackState!=="idle"&&(this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))},s.onerror=o=>{if(o.error==="interrupted"&&this.patches.isAndroid&&this.isAndroidPaused)return;this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.setState("idle"),["synthesis-unavailable","audio-hardware","voice-unavailable"].includes(o.error)&&(console.log("[ENGINE] fatal error detected, resetting index to 0"),this.currentUtteranceIndex=0),o.error==="interrupted"||o.error==="canceled"?this.emitEvent({type:"stop"}):this.emitEvent({type:"error",detail:{error:o.error,message:`Speech synthesis error: ${o.error}`}})},s.onpause=()=>{this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.emitEvent({type:"pause"})},s.onresume=()=>{this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.emitEvent({type:"resume"})},s.onboundary=o=>{e===this.speakGeneration&&this.emitEvent({type:"boundary",detail:{charIndex:o.charIndex,charLength:o.charLength,elapsedTime:o.elapsedTime,name:o.name}})},s.onmark=o=>{this.emitEvent({type:"mark",detail:{name:o.name}})},this.speechSynthesis.speak(s)}}startResumeInfinity(e){this.shouldUseResumeInfinity()&&(this.resumeInfinityTimer=window.setTimeout(()=>{if(e){const{paused:i,speaking:s}=this.speechSynthesis,r=s||this.isSpeakingInternal,o=i||this.isPausedInternal;r&&!o&&(this.speechSynthesis.pause(),this.speechSynthesis.resume())}this.startResumeInfinity(e)},5e3))}stopResumeInfinity(){this.resumeInfinityTimer&&(clearTimeout(this.resumeInfinityTimer),this.resumeInfinityTimer=void 0)}pause(){this.playbackState==="playing"&&(this.pausedAtUtteranceIndex=this.currentUtteranceIndex,this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.setState("paused"),this.patches.isAndroid?(this.isAndroidPaused=!0,this.speechSynthesis.cancel(),this.emitEvent({type:"pause"})):this.speechSynthesis.pause())}resume(){this.playbackState==="paused"&&this.currentUtteranceIndex<this.currentUtterances.length&&(this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.setState("playing"),this.patches.isAndroid||this.pausedAtUtteranceIndex!==this.currentUtteranceIndex?(this.emitEvent({type:"resume"}),this.speak(this.currentUtteranceIndex)):this.speechSynthesis.resume(),this.pausedAtUtteranceIndex=null)}stop(){this.cancelCurrentSpeech(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const t=ae(e,.1,10,this.rate);t!==this.rate&&(this.rate=t,this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const t=ae(e,0,2,this.pitch);t!==this.pitch&&(this.pitch=t,this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const t=ae(e,0,1,this.volume);t!==this.volume&&(this.volume=t,this.scheduleRestartIfSpeaking())}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,t){if(e<0||e>=this.currentUtterances.length){t?.(!1);return}e!==this.currentUtteranceIndex&&(!this.isPausedInternal&&this.isSpeakingInternal&&this.cancelCurrentSpeech(),this.currentUtteranceIndex=e,t?.(!0))}getUtteranceCount(){return this.currentUtterances.length}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const t=this.playbackState;if(this.playbackState=e,t!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),this.stopResumeInfinity(),this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class Va{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new cn,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const t=new cn;return await t.initialize(),e&&await t.setVoice(e),t}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}function Ms(n,e){const t=[];let i=-1,s=-1;const r=()=>{i!==-1&&(t.push({text:ja(n,i,s),offset:n[i].offset}),i=-1,s=-1)};for(let o=0;o<n.length;o++){const a=n[o];if(a.text.length>e){r(),t.push({text:a.text,offset:a.offset});continue}const l=a.offset+a.text.length,c=i===-1?a.text.length:l-n[i].offset;i!==-1&&c>e&&r(),i===-1&&(i=o),s=o}return r(),t}function ja(n,e,t){const i=n[e],s=n[t];return i===s?i.text:n.slice(e,t+1).map(r=>r.text).join("")}const _s=new RegExp(`[^${ye}]*[${ye}]+\\s*|[^${ye}]+$`,"gu"),Ha=/\S+\s*|\s+/g;function Fn(n,e,t){const i=[];for(const s of n.matchAll(t))s[0].length!==0&&i.push({text:s[0],offset:e+s.index,atomic:!1});return i}function In(n,e){if(n.text.length<=e||n.atomic)return[n];const t=Fn(n.text,n.offset,Ha);if(t.length>1)return t.flatMap(o=>In(o,e));const i=[];let s=n.offset,r="";for(const o of n.text)r.length>0&&r.length+o.length>e&&(i.push({text:r,offset:s,atomic:!1}),s+=r.length,r=""),r+=o;return r.length>0&&i.push({text:r,offset:s,atomic:!1}),i}function Bs(n,e){if(n.length<=e)return[{text:n,offset:0}];const i=Fn(n,0,_s).flatMap(s=>In(s,e));return Ms(i,e)}const qa=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Us(n,e){if(n.length<=e)return[{text:n,offset:0}];const t=[];for(const s of n.matchAll(qa))s[0][0]==="<"?t.push({text:s[0],offset:s.index,atomic:!0}):t.push(...Fn(s[0],s.index,_s));const i=t.flatMap(s=>In(s,e));return Ms(i,e)}const Wa={wav:"audio/wav",mp3:"audio/mpeg",opus:"audio/ogg",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",m4a:"audio/mp4"};function zs(n){return Wa[n]??`audio/${n}`}const Ka=["flac","wav","opus","aac","ogg","webm","mp3"],Ga=["opus","aac","webm","ogg","mp3","wav","flac"];function Vs(n,e,t){const i=a=>t(zs(a))!=="",s=n.formats.filter(i);if(e.preferredFormat&&s.includes(e.preferredFormat))return e.preferredFormat;const r=e.strategy==="bandwidth"?Ga:Ka,o=[...r,...s.filter(a=>!r.includes(a))];for(const a of o)if(s.includes(a))return a;return n.default}const Xa=new Set(["wav","flac"]),Ja={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function js(n,e,t){return Xa.has(n)||!e||!t?void 0:t.saveData===!0||/2g/.test(t.effectiveType??"")?Ja[n]:void 0}function Ln(n,e){return{source:"server",label:n.name,name:n.name,originalName:n.originalName,language:n.language,otherLanguages:n.otherLanguages,gender:n.gender??void 0,quality:n.quality,provider:n.provider,identifier:n.identifier,controls:e}}class ke extends Error{status;type;title;instance;constructor(e,t){super(e),this.name="SpeechServerError",this.status=t.status,this.type=t.type,this.title=t.title,this.instance=t.instance}}class $n extends ke{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class Mn extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class _n extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function be(n){if((n.headers.get("content-type")??"").includes("application/problem+json"))try{const t=await n.json();return new ke(t.detail||t.title||`Request failed with status ${n.status}`,{status:t.status??n.status,type:t.type,title:t.title,instance:t.instance})}catch{}return new ke(`Request failed with status ${n.status}`,{status:n.status})}const Ya=3,Qa=400;function Za(n){const e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t.buffer}function el(n){return ae(n,.25,4,1)}function it(n){return n?.plain??n?.ssml??void 0}function Si(n){return n instanceof $n?{message:n.message,status:n.status,type:n.type,title:n.title,instance:n.instance,recoverable:!0}:n instanceof ke?{message:n.message,status:n.status,type:n.type,title:n.title,instance:n.instance,recoverable:!1}:n instanceof Mn?{message:n.message,recoverable:!1}:n instanceof _n?{message:n.message,recoverable:!0}:n instanceof Error?{message:n.message,recoverable:!1}:{message:String(n),recoverable:!1}}class Hs{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Lt;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;timeoutMs;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();activeControllers=new Set;liveControllers=new Set;isSpeakingInternal=!1;restartPending=!1;audioContext=null;masterGain=null;scheduledChunks=[];boundaryRafHandle=null;rate=1;pitch=1;volume=1;constructor(e){this.endpoints=e.endpoints,this.fetchImpl=e.fetch??fetch.bind(globalThis),this.prefetchWindow=e.prefetchWindow??Ya,this.readyBufferChars=e.readyBufferChars??Qa,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?t=>new Audio().canPlayType(t):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,t){try{return await this.fetchImpl(e,t)}catch(i){throw i instanceof TypeError?new _n(i.message):i}}loadUtterances(e,t){this.abortLiveControllers(),this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=dt(t??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const t=dt(this.currentUtteranceIndex,this.currentUtterances.length),i=Math.min(this.indexCoveringChars(this.readyBufferChars,t),t+this.prefetchWindow),s=[];for(let r=t;r<=i;r++){this.queuePrefetch(r);const o=this.prefetchCache.get(r);o&&s.push(o.then(a=>a[0].promise))}try{await Promise.all(s)}catch{}e!==this.loadGeneration||this.playbackState!=="loading"||this.setState("ready")}indexCoveringChars(e,t){if(this.currentUtterances.length===0)return-1;const i=dt(t,this.currentUtterances.length);let s=0;for(let r=i;r<this.currentUtterances.length;r++)if(s+=(it(this.currentUtterances[r])??"").length,s>=e)return r;return this.currentUtterances.length-1}setVoice(e){if(typeof e=="string"){const t=this.voices.find(i=>i.identifier===e||i.name===e);t?this.currentVoice=t:(this.currentVoice={source:"server",label:e,name:e,originalName:e,language:"",identifier:e},this.getAvailableVoices().then(i=>{if(this.currentVoice?.identifier!==e)return;const s=i.find(r=>r.identifier===e||r.name===e);s&&(this.currentVoice=s)}).catch(()=>{}))}else this.currentVoice=e;this.abortLiveControllers(),this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,t]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await be(e);const i=await e.json(),s=new Map(t.providers.map(r=>[r.id,r.controls]));return this.voices=i.map(r=>Ln(r,s.get(r.provider))),this.voices}async getServiceInfo(){return this.serviceInfo?this.serviceInfo:(this.serviceInfoPromise||(this.serviceInfoPromise=this.fetchServiceInfo().catch(e=>{throw this.serviceInfoPromise=null,e})),this.serviceInfo=await this.serviceInfoPromise,this.serviceInfo)}async fetchServiceInfo(){const e=await this.fetchNetwork(this.endpoints.service);if(!e.ok)throw await be(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.abortLiveControllers(),this.clearPrefetchCache()}getSpeakInContentLanguage(){return this.speakInContentLanguage}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio(),this.abortLiveControllers();const t=++this.speakGeneration;this.isSpeakingInternal=!0,this.setState("loading"),this.synthesizeAndPlay(t)}async synthesizeAndPlay(e){const t=this.currentUtteranceIndex;try{const i=await this.resolveSynthesisStream(t);if(e!==this.speakGeneration)return;await this.scheduleChunksStreaming(i,e),this.fillPrefetchWindow(t)}catch(i){if(e!==this.speakGeneration)return;this.isSpeakingInternal=!1,this.setState("idle"),this.emitEvent({type:"error",detail:Si(i)})}}async resolveSynthesisStream(e){const t=this.prefetchCache.get(e);if(t){this.prefetchCache.delete(e);try{const i=await t;for(const{controller:s}of i)this.activeControllers.delete(s),this.liveControllers.add(s);return i}catch{}}return this.synthesizeStream(e,!1)}fillPrefetchWindow(e){const t=Math.min(e+this.prefetchWindow,this.currentUtterances.length-1);for(let i=e+1;i<=t;i++)this.queuePrefetch(i)}queuePrefetch(e){if(this.prefetchCache.has(e))return;const t=this.prefetchChainTail.then(()=>this.synthesizeStream(e,!0));this.prefetchCache.set(e,t),this.prefetchChainTail=t.then(i=>Promise.all(i.map(s=>s.promise))).then(()=>{},()=>{}),t.catch(()=>{}),t.then(i=>i.forEach(s=>s.promise.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear(),this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear()}abortLiveControllers(){this.liveControllers.forEach(e=>e.abort()),this.liveControllers.clear()}async synthesizeStream(e,t){const i=this.currentUtterances[e],s=!i.plain&&!!i.ssml,r=this.speakInContentLanguage?i.language:void 0,o=it(i)??"",a=s?Ns(o).map:void 0,l=it(this.currentUtterances[e-1]),c=it(this.currentUtterances[e+1]),u=await this.getServiceInfo(),h=Vs(u.output,this.formatOptions,this.canPlayType),d=navigator.connection,f=js(h,this.formatOptions.adaptBitrateToNetwork??!1,d);if(o.length<=u.limits.maxTextLength){const w=new AbortController;return(t?this.activeControllers:this.liveControllers).add(w),[{promise:this.synthesizeChunk({content:i,text:o,textOffset:0,useSSML:s,ssmlMap:a,language:r,prevText:l,nextText:c,format:h,bitrate:f,controller:w}),controller:w}]}if(this.overLengthText==="error")throw new ke(`Text exceeds this server's maximum length of ${u.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(u.limits.maxTextLength,this.readyBufferChars),p=s?Us(o,g):Bs(o,g),m=[];let y=Promise.resolve();for(let w=0;w<p.length;w++){const S=w===0?l:p[w-1].text,v=w===p.length-1?c:p[w+1].text,b=p[w],C=new AbortController;(t?this.activeControllers:this.liveControllers).add(C);const R=y.then(()=>this.synthesizeChunk({content:i,text:b.text,textOffset:b.offset,useSSML:s,ssmlMap:a,language:r,prevText:S,nextText:v,format:h,bitrate:f,controller:C}));m.push({promise:R,controller:C}),y=R}return m}async synthesizeChunk(e){const{content:t,text:i,textOffset:s,useSSML:r,ssmlMap:o,language:a,prevText:l,nextText:c,format:u,bitrate:h,controller:d}=e;try{const f=await this.fetchNetwork(this.endpoints.synthesize,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t.id,text:r?i:Ts(i),ssml:r,language:a,voice:this.currentVoice?.identifier??this.currentVoice?.name,prev_utterance:l,next_utterance:c,boundary:!0,output:{format:u,bitrate:h,speed:this.rate,pitch:this.pitch}}),signal:d.signal});if(!f.ok)throw await be(f);const g=await f.json(),p=Za(g.audio);let m;try{m=await this.ensureAudioContext().decodeAudioData(p)}catch{throw new Mn("Audio playback failed")}return{audioBuffer:m,format:g.format,boundaries:g.boundaries,textOffset:s,ssmlMap:o}}finally{this.activeControllers.delete(d),this.liveControllers.delete(d)}}ensureAudioContext(){return this.audioContext||(this.audioContext=new AudioContext,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this.volume,this.masterGain.connect(this.audioContext.destination)),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.audioContext}awaitWithStallDeadline(e,t,i){if(this.timeoutMs===void 0)return e;const s=i+this.timeoutMs;return new Promise((r,o)=>{const a=setTimeout(()=>{t.abort(),o(new $n(`No audio chunk arrived within ${s.toFixed(0)}ms of the playback buffer running dry`))},s);e.then(l=>{clearTimeout(a),r(l)},l=>{clearTimeout(a),o(l)})})}async scheduleChunksStreaming(e,t){const i=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(t!==this.speakGeneration)return;const s=this.ensureAudioContext(),r=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:el(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let l=s.currentTime,c=null;const u=h=>{const d=s.createBufferSource();d.buffer=h.audioBuffer,d.playbackRate.value=a,d.connect(r),d.start(l),c&&(c.onended=null),d.onended=()=>this.handleUtteranceEnded(t),c=d,this.scheduledChunks.push({chunk:h,startTime:l,node:d,nextBoundaryIndex:0,rate:a}),l+=h.audioBuffer.duration/a};u(i),this.startBoundaryPolling(t);for(let h=1;h<e.length;h++){let d;try{const f=Math.max(0,(l-s.currentTime)*1e3);d=await this.awaitWithStallDeadline(e[h].promise,e[h].controller,f)}catch(f){t===this.speakGeneration&&this.emitEvent({type:"error",detail:Si(f)});return}if(t!==this.speakGeneration)return;u(d)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))}startBoundaryPolling(e){const t=()=>{e===this.speakGeneration&&(this.checkBoundaries(),this.boundaryRafHandle=requestAnimationFrame(t))};this.boundaryRafHandle=requestAnimationFrame(t)}stopBoundaryPolling(){this.boundaryRafHandle!==null&&(cancelAnimationFrame(this.boundaryRafHandle),this.boundaryRafHandle=null)}checkBoundaries(){if(!this.audioContext)return;const e=this.audioContext.currentTime;for(const t of this.scheduledChunks){const i=t.chunk.boundaries??[];for(;t.nextBoundaryIndex<i.length&&e>=t.startTime+i[t.nextBoundaryIndex].elapsedTime/t.rate;){const s=i[t.nextBoundaryIndex],r=s.charIndex+t.chunk.textOffset;let o=r,a=s.charLength;if(t.chunk.ssmlMap){const l=t.chunk.ssmlMap;o=di(l,r),a=Math.max(0,di(l,r+s.charLength)-o)}this.emitEvent({type:"boundary",detail:{name:s.name,charIndex:o,charLength:a,elapsedTime:s.elapsedTime}}),t.nextBoundaryIndex++}}}stopAudio(){this.stopBoundaryPolling();for(const e of this.scheduledChunks){e.node.onended=null;try{e.node.stop()}catch{}e.node.disconnect()}this.scheduledChunks=[]}pause(){this.playbackState==="playing"&&this.audioContext&&(this.audioContext.suspend().catch(()=>{}),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.abortLiveControllers(),this.clearPrefetchCache(),this.isSpeakingInternal=!1,this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const t=ae(e,.1,10,this.rate);t!==this.rate&&(this.rate=t,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const t=ae(e,0,2,this.pitch);t!==this.pitch&&(this.pitch=t,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const t=ae(e,0,1,this.volume);t!==this.volume&&(this.volume=t,this.masterGain&&(this.masterGain.gain.value=this.volume))}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,t){if(e<0||e>=this.currentUtterances.length){t?.(!1);return}if(e===this.currentUtteranceIndex){t?.(!0);return}this.stopAudio(),this.currentUtteranceIndex=e,t?.(!0)}getUtteranceCount(){return this.currentUtterances.length}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const t=this.playbackState;if(this.playbackState=e,t!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),await this.audioContext?.close(),this.audioContext=null,this.masterGain=null,this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class tl{id="speech-server";name="Readium Speech Server";options;fetchImpl;voices=[];constructor(e){this.options=e,this.fetchImpl=e.fetch??fetch.bind(globalThis)}async getVoices(e){if(this.voices.length>0&&!e)return this.voices;const[t,i]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!t.ok)throw await be(t);if(!i.ok)throw await be(i);const s=await t.json(),r=await i.json(),o=new Map(r.providers.map(a=>[a.id,a.controls]));return this.voices=s.map(a=>Ln(a,o.get(a.provider))),this.voices}async createEngine(e){const t=new Hs(this.options);return this.voices.length>0&&t.setAvailableVoices(this.voices),e&&t.setVoice(e),t}async destroy(){this.voices=[]}}function qs(n){return n.detail?.recoverable===!0}const nl=3e4,il=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Ws{activeEngine;primaryProvider;fallbackProvider;onFailure;healthCheckIntervalMs;hasFallenBack=!1;healthCheckTimer=null;primaryReachable=!1;currentUtterances=[];lastVoiceRequest;desiredIndex=0;desiredPlaying=!1;engineStarted=!0;swapInFlight=!1;teardownEpoch=0;loadToken=0;events=new Lt;unbindActiveEngine=null;constructor(e){this.activeEngine=e.primaryEngine,this.primaryProvider=e.primaryProvider,this.fallbackProvider=e.fallbackProvider,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs??nl,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,t){this.loadToken++,this.currentUtterances=e,this.desiredIndex=t??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,t))}setVoice(e){this.lastVoiceRequest=e,this.activeEngine.setVoice(e)}getCurrentVoice(){return this.activeEngine.getCurrentVoice()}getAvailableVoices(){return this.activeEngine.getAvailableVoices()}setSpeakInContentLanguage(e){this.activeEngine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.activeEngine.getSpeakInContentLanguage()}speak(e){if(this.desiredIndex=e??this.desiredIndex,this.desiredPlaying=!0,!this.swapInFlight){if(this.hasFallenBack&&this.primaryReachable&&this.activeEngine.getState()!=="playing"){this.recoverToPrimary();return}this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex)}}pause(){this.desiredPlaying=!1,this.isEngineTrusted()&&this.activeEngine.pause()}resume(){if(this.desiredPlaying=!0,!this.swapInFlight){if(!this.engineStarted){this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex);return}this.activeEngine.resume()}}stop(){this.desiredPlaying=!1,this.desiredIndex=0,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.stop())}setRate(e){this.activeEngine.setRate(e)}getRate(){return this.activeEngine.getRate()}setPitch(e){this.activeEngine.setPitch(e)}getPitch(){return this.activeEngine.getPitch()}setVolume(e){this.activeEngine.setVolume(e)}getVolume(){return this.activeEngine.getVolume()}isEngineTrusted(){return!this.swapInFlight&&this.engineStarted}getState(){return this.isEngineTrusted()?this.activeEngine.getState():this.desiredPlaying?"loading":"paused"}getCurrentUtteranceIndex(){return this.isEngineTrusted()?this.activeEngine.getCurrentUtteranceIndex():this.desiredIndex}setCurrentUtteranceIndex(e,t){if(this.desiredIndex=e,!this.isEngineTrusted()){t?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,t)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,t=il.map(i=>e.on(i,s=>{this.emitEvent(s),this.maybeRecoverNow()}));t.push(e.on("error",i=>this.handleError(i))),this.unbindActiveEngine=()=>t.forEach(i=>i())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!qs(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,t){t.setRate(e.getRate()),t.setPitch(e.getPitch()),t.setVolume(e.getVolume()),t.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const t=this.loadToken,i=e.on("ready",()=>{i(),t===this.loadToken&&(this.desiredPlaying?(this.engineStarted=!0,e.speak(this.desiredIndex)):this.engineStarted=!1)})}startHealthCheck(){this.healthCheckTimer===null&&(this.healthCheckTimer=setTimeout(async()=>{this.healthCheckTimer=null;try{await this.primaryProvider.getVoices(!0),this.primaryReachable=!0,this.maybeRecoverNow()}catch{this.startHealthCheck()}},this.healthCheckIntervalMs))}maybeRecoverNow(){!this.hasFallenBack||!this.primaryReachable||this.swapInFlight||this.activeEngine.getState()!=="playing"&&this.recoverToPrimary()}async swapToFallback(e){let t=null;await this.performSwap(async()=>{const s=this.activeEngine.getCurrentVoice()??(typeof this.lastVoiceRequest=="object"?this.lastVoiceRequest:null),r=s?.language||this.currentUtterances[this.desiredIndex]?.language||(typeof navigator<"u"?navigator.language:"en");if(t=await this.pickBestFallbackVoice(r,s?.gender),!t)throw new Error("no offline-available fallback voice found");return this.fallbackProvider.createEngine(t)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:t}}),()=>{this.hasFallenBack=!0,this.emitEvent(e)})}async recoverToPrimary(){await this.performSwap(()=>this.primaryProvider.createEngine(this.lastVoiceRequest),e=>(this.hasFallenBack=!1,this.primaryReachable=!1,{type:"enginerecovered",detail:{voice:e.getCurrentVoice()}}),()=>{this.primaryReachable=!1,this.startHealthCheck()})}async performSwap(e,t,i){this.swapInFlight=!0;const s=this.teardownEpoch,r=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,i();return}if(s!==this.teardownEpoch){this.swapInFlight=!1,await o.destroy();return}this.copyPlaybackParameters(r,o),this.unbindActiveEngine?.(),this.activeEngine=o,this.engineStarted=!1,this.swapInFlight=!1,this.bindActiveEngine(),this.emitEvent(t(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await r.destroy()}async pickBestFallbackVoice(e,t){const i=await this.fallbackProvider.getVoices(),r=typeof navigator<"u"&&navigator.onLine===!0?i:i.filter(d=>d.offlineAvailability===!0);if(r.length===0)return null;const[o]=Ft([e]),{voicesByLang:a}=It(r,[o]),l=a.get(o.baseLang)??[],c=l.length>0?l:r,u=t?c.filter(d=>d.gender===t):[],h=u.length>0?u:c;return Xo(e,h)}async destroy(){this.teardownEpoch++,this.healthCheckTimer!==null&&(clearTimeout(this.healthCheckTimer),this.healthCheckTimer=null),this.unbindActiveEngine?.(),this.events.clear(),await this.activeEngine.destroy()}}class sl{id="fallback";name="Fallback";primary;fallback;onFailure;healthCheckIntervalMs;constructor(e){this.primary=e.primary,this.fallback=e.fallback,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs}async getVoices(e){try{return await this.primary.getVoices(e)}catch(t){if(this.onFailure==="error")throw t;return this.fallback.getVoices(e)}}async createEngine(e){let t;try{t=await this.primary.createEngine(e)}catch(i){if(this.onFailure==="error")throw i;return this.fallback.createEngine(e)}return new Ws({primaryEngine:t,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let rl=class{};function ol(n){return(n.getComputedStyle(n.document.documentElement).writingMode||n.getComputedStyle(n.document.body).writingMode)==="vertical-lr"}function al(n){const e=n.getComputedStyle(n.document.documentElement).writingMode||n.getComputedStyle(n.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function de(n){const e=al(n),t=e&&ol(n),i=n.innerWidth,s=n.innerHeight,r=n.document.scrollingElement,o=r.scrollLeft,a=r.scrollTop,l=parseInt(n.getComputedStyle(n.document.documentElement).getPropertyValue("column-count")),c=e&&!t?r.scrollWidth-i+o:o,u=a;return{isVertical:e,isVertLR:t,viewportInlineSize:e?s:i,viewportBlockSize:e?i:s,pageInlineSize:e?s:i/(l||1),xDocOffset:c,yDocOffset:u,inlineScrollOffset:e?u:c,blockScrollOffset:e?c:u,inlineStart:h=>e?h.top:h.left,blockStart:h=>e?h.left:h.top,inlineSize:h=>e?h.height:h.width,blockSize:h=>e?h.width:h.height,applyPosition(h,d,f,g,p,m){h.style.position="absolute",h.style.zIndex="2147483646",e?(h.style.top=`${d*m}px`,h.style.left=`${f*m}px`,h.style.height=`${g*m}px`,h.style.width=`${p*m}px`):(h.style.left=`${d*m}px`,h.style.top=`${f*m}px`,h.style.width=`${g*m}px`,h.style.height=`${p*m}px`)},toRect(h,d,f,g){return e?new DOMRect(d,h,g,f):new DOMRect(h,d,f,g)}}}function vi(n,e){return n.document.documentElement.style.getPropertyValue(e)}function ll(n){return n&&Array.isArray(n)?n:void 0}function cl(n){return n&&typeof n=="string"?[n]:ll(n)}function ft(n){return isNaN(n)?void 0:n}function qt(n){return ft(n)!==void 0&&Math.sign(n)>=0?n:void 0}let St=class Ks{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=qt(e.textNodeIndex);if(t===void 0)return;let i=qt(e.charOffset);return i===void 0&&(i=qt(e.offset)),new Ks({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:i})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}},Gs=class Xs{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=St.deserialize(e.start);if(t)return new Xs({start:t,end:St.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}},st=null,Wt=null,Le=0;const pe={r:255,g:255,b:255,a:1},fe=new Map,ul=()=>{if(!st)if(typeof OffscreenCanvas<"u")st=new OffscreenCanvas(5,5),Wt=st.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const n=document.createElement("canvas");n.width=5,n.height=5,st=n,Wt=n.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return Wt},hl=n=>{if(!n)return!0;const e=n.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(t=>e.includes(t))},rt=(n,e)=>{console.warn(`[Decorator] Could not parse color: "${n}". ${e} Falling back to ${JSON.stringify(pe)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},ce=(n,e=null)=>{const t=e?`${n}|${e}`:n,i=fe.get(t);if(i!==void 0)return i??pe;if(hl(n))return rt(n,"Unsupported color format or special value."),fe.set(t,null),pe;const s=ul();if(!s)return rt(n,"Could not get canvas context."),fe.set(t,null),pe;try{Le===0&&s.clearRect(0,0,5,5);const r=Le%5,o=Math.floor(Le/5);s.clearRect(r,o,1,1),e&&(s.fillStyle=e,s.fillRect(r,o,1,1)),s.fillStyle=n,s.fillRect(r,o,1,1);const a=s.getImageData(r,o,1,1);Le=(Le+1)%25;const[l,c,u,h]=a.data;if(h===0)return rt(n,"Fully transparent color."),fe.set(t,null),pe;const d={r:l,g:c,b:u,a:h/255};return fe.set(t,d),d}catch(r){return rt(n,`Error: ${r instanceof Error?r.message:String(r)}`),fe.set(t,null),pe}},Kt=n=>{const e=n/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},un=n=>{const e=Kt(n.r),t=Kt(n.g),i=Kt(n.b);return .2126*e+.7152*t+.0722*i},vt=(n,e)=>{const t=typeof n=="string"?ce(n):n,i=typeof e=="string"?ce(e):e,s=un(t),r=un(i),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)},Js=(n,e=null)=>{const t=ce(n,e),i=vt(t,{r:255,g:255,b:255,a:1}),s=vt(t,{r:0,g:0,b:0,a:1});return i>s},yi=(n,e=null)=>Js(n,e)?"white":"black",dl=n=>{const e=n.a!==void 0?n.a:1;return`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`},fl=(n,e)=>({r:Math.min(255,n.r+(255-n.r)*e),g:Math.min(255,n.g+(255-n.g)*e),b:Math.min(255,n.b+(255-n.b)*e),a:n.a??1}),gl=(n,e)=>({r:Math.max(0,n.r*(1-e)),g:Math.max(0,n.g*(1-e)),b:Math.max(0,n.b*(1-e)),a:n.a??1}),ge=(n,e=null,t=3)=>{const i=ce(n),s=e?ce(e):{r:255,g:255,b:255,a:1};let r=vt(i,s);if(r>=t)return n;const o=un(s)<.5;let a={...i,a:i.a??1};const l=20,c=.1;for(let u=0;u<l&&(o?a=fl(a,c):a=gl(a,c),r=vt(a,s),!(r>=t));u++);return dl(a)},Ys=()=>typeof navigator>"u"?"":navigator.userAgent||"",Qs=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let Zs=class{constructor(){const e=Qs(),t=Ys(),i=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(o=>parseInt(o)||0):[],s=(r="")=>{if(!r)return[];const o=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return o.test(t)?i(t.replace(o,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(r.iOS=s("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?r.iOS=r.iPadOS=s("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=s():r.macOS=s("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?r.Windows=(o=>o[0]!==6||!o[1]?o:o[1]===1?[7]:o[1]===2?[8]:[8,1])(s("Windows(?: NT)?")):/Android \d/.test(t)?r.Android=s("Android"):/CrOS/.test(t)?r.ChromeOS=s():/X11;/.test(t)&&(r.Linux=s()),r))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(o=>{const a=r.platform,l=r.platformVersion;if(!(!a||!l)){if(/^i(OS|P(hone|od touch))$/.test(a))o.iOS=i(l);else if(/^iPad(OS)?$/.test(a))o.iOS=o.iPadOS=i(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?o.iOS=o.iPadOS=i():o.macOS=i(l);else if(/^(Microsoft )?Windows$/.test(a))o.Windows=i(l);else if(/^(Google )?Android$/.test(a))o.Android=i(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))o.ChromeOS=i(l);else if(/^(Linux|Ubuntu|X11)$/.test(a))o.Linux=i(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,o)}})({})),this.UA=(r=>{let o=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});a["Google Chrome"]?(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Edge=a["Microsoft Edge"]):a.Opera&&(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Opera=a.Opera)}return o||(/ Gecko\/\d/.test(t)?(r.Gecko=s("rv"),/ Waterfox\/\d/.test(t)?r.Waterfox=s("Waterfox"):/ Firefox\/\d/.test(t)&&(r.Firefox=s("Firefox"))):/ Edge\/\d/.test(t)?(r.EdgeHTML=s("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(r.Blink=r.Chromium=(a=>a[0]?a:s("Chrome"))(s("Chromium")),/ EdgA?\/\d/.test(t)?r.Edge=(a=>a[0]?a:s("Edg"))(s("EdgA")):/ OPR\/\d/.test(t)?r.Opera=s("OPR"):/ Vivaldi\/\d/.test(t)?r.Vivaldi=s("Vivaldi"):/ Silk\/\d/.test(t)?r.Silk=s("Silk"):/ UCBrowser\/\d/.test(t)?r.UCBrowser=s("UCBrowser"):/ Phoebe\/\d/.test(t)?r.Phoebe=s("Phoebe"):r.Chrome=(a=>a[0]?a:r.Chromium)(s("Chrome"))):/ AppleWebKit\/\d/.test(t)?(r.WebKit=s("AppleWebKit"),/ CriOS \d/.test(t)?r.Chrome=s("CriOS"):/ FxiOS \d/.test(t)?r.Firefox=s("FxiOS"):/ EdgiOS\/\d/.test(t)?r.Edge=s("EdgiOS"):/ Version\/\d/.test(t)&&(r.Safari=s("Version"))):/ Trident\/\d/.test(t)&&(r.Trident=s("Trident"),r.InternetExplorer=(a=>a[0]?a:s("MSIE"))(s("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(r.Facebook=s("FBAV")),/ Line\/\d/.test(t)&&(r.LINE=s("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,o)=>{for(const a in o)o[a]&&r.push(a);return r},[])}}},pl=class extends Zs{get iOSRequest(){const e=Qs(),t=Ys();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(t)||e&&/^iPad(OS)?$/.test(e.platform)?"mobile":"desktop"}};const ml=new Zs;new pl;const bi=":~:text=";function Sl(n){if(!n)return;const e=n.indexOf(bi);if(e===-1)return;const t=n.slice(e+bi.length).split("&")[0];if(t)try{let i=t.split(",");const s={textStart:""};return i.length>1&&i[0].endsWith("-")&&(s.prefix=decodeURIComponent(i[0].slice(0,-1)),i=i.slice(1)),i.length>1&&i[i.length-1].startsWith("-")&&(s.suffix=decodeURIComponent(i[i.length-1].slice(1)),i=i.slice(0,-1)),i.length===0||i[0]===""?void 0:(s.textStart=decodeURIComponent(i[0]),i.length>1&&(s.textEnd=decodeURIComponent(i[1])),s)}catch{return}}const er=["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","BR","DETAILS","DIALOG","DD","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","LI","MAIN","NAV","OL","P","PRE","SECTION","TABLE","UL","TR","TH","TD","COLGROUP","COL","CAPTION","THEAD","TBODY","TFOOT"],Be=/[\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,vl=/[^\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,tr=(n,e,t)=>{const i=[],s=e.createRange();for(s.selectNodeContents(t??e);!s.collapsed&&i.length<2;){let r;if(n.prefix){const o=Ue(n.prefix,s);if(o==null)break;ot(s,o.startContainer,o.startOffset);const a=e.createRange();if(a.setStart(o.endContainer,o.endOffset),a.setEnd(s.endContainer,s.endOffset),nr(a),a.collapsed||(r=Ue(n.textStart,a),r==null))break;if(r.compareBoundaryPoints(Range.START_TO_START,a)!==0)continue}else{if(r=Ue(n.textStart,s),r==null)break;ot(s,r.startContainer,r.startOffset)}if(n.textEnd){const o=e.createRange();o.setStart(r.endContainer,r.endOffset),o.setEnd(s.endContainer,s.endOffset);let a=!1;for(;!o.collapsed&&i.length<2;){const l=Ue(n.textEnd,o);if(l==null)break;if(ot(o,l.startContainer,l.startOffset),r.setEnd(l.endContainer,l.endOffset),n.suffix){const c=wi(n.suffix,r,s,e);if(c===K.NO_SUFFIX_MATCH)break;if(c===K.SUFFIX_MATCH){a=!0,i.push(r.cloneRange());continue}else if(c===K.MISPLACED_SUFFIX)continue}else a=!0,i.push(r.cloneRange())}if(!a)break}else if(n.suffix){const o=wi(n.suffix,r,s,e);if(o===K.NO_SUFFIX_MATCH)break;if(o===K.SUFFIX_MATCH){i.push(r.cloneRange()),ot(s,s.startContainer,s.startOffset);continue}else if(o===K.MISPLACED_SUFFIX)continue}else i.push(r.cloneRange())}return i},K={NO_SUFFIX_MATCH:0,SUFFIX_MATCH:1,MISPLACED_SUFFIX:2},wi=(n,e,t,i)=>{const s=i.createRange();s.setStart(e.endContainer,e.endOffset),s.setEnd(t.endContainer,t.endOffset),nr(s);const r=Ue(n,s);return r==null?K.NO_SUFFIX_MATCH:r.compareBoundaryPoints(Range.START_TO_START,s)!==0?K.MISPLACED_SUFFIX:K.SUFFIX_MATCH},ot=(n,e,t)=>{try{n.setStart(e,t+1)}catch{n.setStartAfter(e)}},nr=n=>{const e=ir(n);let t=e.nextNode();for(;!n.collapsed&&t!=null;){if(t!==n.startContainer&&n.setStart(t,0),t.textContent.length>n.startOffset&&!t.textContent[n.startOffset].match(/\s/))return;try{n.setStart(t,n.startOffset+1)}catch{t=e.nextNode(),t==null?n.collapse():n.setStart(t,0)}}},ir=n=>(n.commonAncestorContainer.ownerDocument??n.commonAncestorContainer).createTreeWalker(n.commonAncestorContainer,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>bl(e,n)}),yl=n=>{if(n.hidden==="until-found")return!0;const e=n.attributes;return!!(e&&e.hidden&&e.hidden.value==="until-found")},Bn=n=>{let e=n;for(;e!=null&&!(e instanceof HTMLElement);)e=e.parentNode;const t=e?.ownerDocument?.defaultView;if(e!=null&&t!=null){if(yl(e))return!0;const i=t.getComputedStyle(e);if(i.visibility==="hidden"||i.display==="none"||parseInt(i.height,10)===0&&i.overflowY!="visible"||parseInt(i.width,10)===0&&i.overflowX!="visible"||parseInt(i.opacity,10)===0)return!1}return!0},sr=(n,e)=>e!=null&&!e.intersectsNode(n)?NodeFilter.FILTER_REJECT:Bn(n)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT,bl=(n,e)=>e!=null&&!e.intersectsNode(n)||!Bn(n)?NodeFilter.FILTER_REJECT:n.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,wl=(n,e)=>{const t=[];let i=[];const s=Array.from(El(n,r=>sr(r,e)));for(const r of s)r.nodeType===Node.TEXT_NODE?i.push(r):r instanceof HTMLElement&&er.includes(r.tagName.toUpperCase())&&i.length>0&&(t.push(i),i=[]);return i.length>0&&t.push(i),t},xl=(n,e,t)=>{let i="";return n.length===1?i=n[0].textContent.substring(e,t):i=n[0].textContent.substring(e)+n.slice(1,-1).reduce((s,r)=>s+r.textContent,"")+n.slice(-1)[0].textContent.substring(0,t),i.replace(/[\t\n\r ]+/g," ")};function*El(n,e){const t=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e}),i=new Set;for(;or(t,i)!==null;)yield t.currentNode}const Ue=(n,e)=>{const t=wl(e.commonAncestorContainer,e),i=rr(e.commonAncestorContainer.ownerDocument??void 0);for(const s of t){const r=Cl(n,e,s,i);if(r!==void 0)return r}},Cl=(n,e,t,i)=>{if(!n||!e||!(t||[]).length)return;const s=t[0]===e.startContainer?e.startOffset:0,r=Y(xl(t,s,void 0)),o=Y(n);let a=0,l,c;for(;a<r.length;){const u=r.indexOf(o,a);if(u===-1)return;if(kl(r,u,o.length,i)){const h=Y(t[0].data.slice(0,s)).length;l=xi(h+u,t,!1),c=xi(h+u+o.length,t,!0)}if(l!=null&&c!=null){const h=new Range;if(h.setStart(l.node,l.offset),h.setEnd(c.node,c.offset),e.compareBoundaryPoints(Range.START_TO_START,h)<=0&&e.compareBoundaryPoints(Range.END_TO_END,h)>=0)return h}a=u+1}},xi=(n,e,t)=>{let i=0,s;for(let r=0;r<e.length;r++){const o=e[r];s||(s=Y(o.data));let a=i+s.length;if(t&&(a+=1),a>n){const l=n-i;let c=Math.min(n-i,o.data.length);const u=t?s.substring(0,l):s.substring(l);let h=Y(t?o.data.substring(0,c):o.data.substring(c));const d=(t?-1:1)*(u.length>h.length?-1:1);for(;c>=0&&c<=o.data.length;){if(h.length===u.length)return{node:o,offset:c};c+=d,h=Y(t?o.data.substring(0,c):o.data.substring(c))}}if(i+=s.length,r+1<e.length){const l=Y(e[r+1].data);s.slice(-1)===" "&&l.slice(0,1)===" "&&(i-=1),s=l}}},kl=(n,e,t,i)=>{if(e<0||e>=n.length||t<=0||e+t>n.length)return!1;if(i){const s=i.segment(n),r=s.containing(e);if(!r||r.isWordLike&&r.index!=e)return!1;const o=e+t,a=s.containing(o);if(a&&a.isWordLike&&a.index!=o)return!1}else if(n[e].match(Be)&&(++e,--t,!t)||n[e+t-1].match(Be)&&(--t,!t)||e!==0&&!n[e-1].match(Be)||e+t!==n.length&&!n[e+t].match(Be))return!1;return!0},Y=n=>(n||"").normalize("NFKD").replace(/\s+/g," ").replace(/[\u0300-\u036f]/g,"").toLowerCase(),rr=n=>{if(Intl.Segmenter){const e=n?.documentElement?.lang||n?.defaultView?.navigator?.language||void 0;return new Intl.Segmenter(e,{granularity:"word"})}},or=(n,e)=>{if(!e.has(n.currentNode)){const s=n.firstChild();if(s!==null)return s}const t=n.nextSibling();if(t!==null)return t;const i=n.parentNode();return i!==null&&e.add(i),i},Rl=(n,e)=>{if(!e.has(n.currentNode)){const s=n.lastChild();if(s!==null)return s}const t=n.previousSibling();if(t!==null)return t;const i=n.parentNode();return i!==null&&e.add(i),i},k={BLOCK_ELEMENTS:er,BOUNDARY_CHARS:Be,NON_BOUNDARY_CHARS:vl,acceptNodeIfVisibleInRange:sr,normalizeString:Y,makeNewSegmenter:rr,forwardTraverse:or,backwardTraverse:Rl,makeTextNodeWalker:ir,isNodeVisible:Bn},Al=300,ar=20,Ol=1,Ei=3,Ci=1;let Tl=500,lr;class cr extends Error{constructor(){super(...arguments),this.isTimeout=!0}}const ie={SUCCESS:0,INVALID_SELECTION:1,AMBIGUOUS:2,TIMEOUT:3,EXECUTION_FAILED:4},Nl=(n,e=Date.now())=>{try{return Dl(n,e)}catch(t){return t instanceof cr?{status:ie.TIMEOUT}:{status:ie.EXECUTION_FAILED}}},Dl=(n,e)=>{Fl(e);const t=n.startContainer.ownerDocument,i=Pl(t);Ul(n),jl(n);const s=n.cloneRange();if(zl(n),n.collapsed)return{status:ie.INVALID_SELECTION};let r;if(Ll(n)){const h=k.normalizeString(n.toString()),d={textStart:h};if(h.length>=ar&&hr(d,t,i))return{status:ie.SUCCESS,fragment:d};r=new Gt(t,i).setExactTextMatch(h)}else{const h=ki(n),d=Ri(n);h&&d?r=new Gt(t,i).setStartAndEndSearchSpace(h,d):r=new Gt(t,i).setSharedSearchSpace(n.toString().trim())}const o=t.createRange();o.selectNodeContents(i);const a=o.cloneRange();o.setEnd(s.startContainer,s.startOffset),a.setStart(s.endContainer,s.endOffset);const l=Ri(o),c=ki(a);(l||c)&&r.setPrefixAndSuffixSearchSpace(l,c),r.useSegmenter(k.makeNewSegmenter(t));let u=!1;do{L(),u=r.embiggen();const h=r.tryToMakeUniqueFragment();if(h!=null)return{status:ie.SUCCESS,fragment:h}}while(u);return{status:ie.AMBIGUOUS}},Pl=n=>n.querySelector("body")??n.documentElement,L=()=>{const n=Date.now()-lr;if(n>Tl)throw new cr(`Fragment generation timed out after ${n} ms.`)},Fl=n=>{lr=n},ki=n=>{let e=Ye(n);const t=ue(e,n.endContainer);if(!t)return;const i=new Set;n.startContainer.nodeType===Node.ELEMENT_NODE&&n.startOffset===n.startContainer.childNodes.length&&i.add(n.startContainer);const s=e,r=new ur(n,!0),o=n.cloneRange();for(;!o.collapsed&&e!=null;){if(L(),e.contains?.(s)?o.setStartAfter(e):o.setStartBefore(e),r.appendNode(e),r.textInBlock!==null)return r.textInBlock;e=k.forwardTraverse(t,i)}},Ri=n=>{let e=$t(n);const t=ue(e,n.startContainer);if(!t)return;const i=new Set;n.endContainer.nodeType===Node.ELEMENT_NODE&&n.endOffset===0&&i.add(n.endContainer);const s=e,r=new ur(n,!1),o=n.cloneRange();for(;!o.collapsed&&e!=null;){if(L(),e.contains?.(s)?o.setEnd(e,0):o.setEndAfter(e),r.appendNode(e),r.textInBlock!==null)return r.textInBlock;e=k.backwardTraverse(t,i)}},Il={ALL_PARTS:1,SHARED_START_AND_END:2,CONTEXT_ONLY:3};let Gt=class{constructor(e,t){this.Mode=Il,this.startOffset=null,this.endOffset=null,this.prefixOffset=null,this.suffixOffset=null,this.prefixSearchSpace="",this.backwardsPrefixSearchSpace="",this.suffixSearchSpace="",this.numIterations=0,this.doc=e,this.root=t}tryToMakeUniqueFragment(){let e;if(this.mode===this.Mode.CONTEXT_ONLY?e={textStart:this.exactTextMatch}:e={textStart:this.getStartSearchSpace().substring(0,this.startOffset).trim(),textEnd:this.getEndSearchSpace().substring(this.endOffset).trim()},this.prefixOffset!=null){const t=this.getPrefixSearchSpace().substring(this.prefixOffset).trim();t&&(e.prefix=t)}if(this.suffixOffset!=null){const t=this.getSuffixSearchSpace().substring(0,this.suffixOffset).trim();t&&(e.suffix=t)}return hr(e,this.doc,this.root)?e:void 0}embiggen(){let e=!0;if(this.mode===this.Mode.SHARED_START_AND_END?this.startOffset>=this.endOffset&&(e=!1):this.mode===this.Mode.ALL_PARTS?this.startOffset===this.getStartSearchSpace().length&&this.backwardsEndOffset()===this.getEndSearchSpace().length&&(e=!1):this.mode===this.Mode.CONTEXT_ONLY&&(e=!1),e){const i=this.getNumberOfRangeWordsToAdd();if(this.startOffset<this.getStartSearchSpace().length){let s=0;if(this.getStartSegments()!=null)for(;s<i&&this.startOffset<this.getStartSearchSpace().length;)this.startOffset=this.getNextOffsetForwards(this.getStartSegments(),this.startOffset,this.getStartSearchSpace()),s++;else{let r=this.startOffset;do{L();const o=this.getStartSearchSpace().substring(this.startOffset+1).search(k.BOUNDARY_CHARS);o===-1?this.startOffset=this.getStartSearchSpace().length:this.startOffset=this.startOffset+1+o,this.getStartSearchSpace().substring(r,this.startOffset).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.startOffset,s++)}while(this.startOffset<this.getStartSearchSpace().length&&s<i)}this.mode===this.Mode.SHARED_START_AND_END&&(this.startOffset=Math.min(this.startOffset,this.endOffset))}if(this.backwardsEndOffset()<this.getEndSearchSpace().length){let s=0;if(this.getEndSegments()!=null)for(;s<i&&this.endOffset>0;)this.endOffset=this.getNextOffsetBackwards(this.getEndSegments(),this.endOffset),s++;else{let r=this.backwardsEndOffset();do{L();const o=this.getBackwardsEndSearchSpace().substring(this.backwardsEndOffset()+1).search(k.BOUNDARY_CHARS);o===-1?this.setBackwardsEndOffset(this.getEndSearchSpace().length):this.setBackwardsEndOffset(this.backwardsEndOffset()+1+o),this.getBackwardsEndSearchSpace().substring(r,this.backwardsEndOffset()).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.backwardsEndOffset(),s++)}while(this.backwardsEndOffset()<this.getEndSearchSpace().length&&s<i)}this.mode===this.Mode.SHARED_START_AND_END&&(this.endOffset=Math.max(this.startOffset,this.endOffset))}}let t=!1;if((!e||this.startOffset+this.backwardsEndOffset()<ar||this.numIterations>=Ol)&&(this.backwardsPrefixOffset()!=null&&this.backwardsPrefixOffset()!==this.getPrefixSearchSpace().length||this.suffixOffset!=null&&this.suffixOffset!==this.getSuffixSearchSpace().length)&&(t=!0),t){const i=this.getNumberOfContextWordsToAdd();if(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length){let s=0;if(this.getPrefixSegments()!=null)for(;s<i&&this.prefixOffset>0;)this.prefixOffset=this.getNextOffsetBackwards(this.getPrefixSegments(),this.prefixOffset),s++;else{let r=this.backwardsPrefixOffset();do{L();const o=this.getBackwardsPrefixSearchSpace().substring(this.backwardsPrefixOffset()+1).search(k.BOUNDARY_CHARS);o===-1?this.setBackwardsPrefixOffset(this.getBackwardsPrefixSearchSpace().length):this.setBackwardsPrefixOffset(this.backwardsPrefixOffset()+1+o),this.getBackwardsPrefixSearchSpace().substring(r,this.backwardsPrefixOffset()).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.backwardsPrefixOffset(),s++)}while(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length&&s<i)}}if(this.suffixOffset<this.getSuffixSearchSpace().length){let s=0;if(this.getSuffixSegments()!=null)for(;s<i&&this.suffixOffset<this.getSuffixSearchSpace().length;)this.suffixOffset=this.getNextOffsetForwards(this.getSuffixSegments(),this.suffixOffset,this.getSuffixSearchSpace()),s++;else{let r=this.suffixOffset;do{L();const o=this.getSuffixSearchSpace().substring(this.suffixOffset+1).search(k.BOUNDARY_CHARS);o===-1?this.suffixOffset=this.getSuffixSearchSpace().length:this.suffixOffset=this.suffixOffset+1+o,this.getSuffixSearchSpace().substring(r,this.suffixOffset).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.suffixOffset,s++)}while(this.suffixOffset<this.getSuffixSearchSpace().length&&s<i)}}}return this.numIterations++,e||t}setStartAndEndSearchSpace(e,t){return this.startSearchSpace=e,this.endSearchSpace=t,this.backwardsEndSearchSpace=gt(t),this.startOffset=0,this.endOffset=t.length,this.mode=this.Mode.ALL_PARTS,this}setSharedSearchSpace(e){return this.sharedSearchSpace=e,this.backwardsSharedSearchSpace=gt(e),this.startOffset=0,this.endOffset=e.length,this.mode=this.Mode.SHARED_START_AND_END,this}setExactTextMatch(e){return this.exactTextMatch=e,this.mode=this.Mode.CONTEXT_ONLY,this}setPrefixAndSuffixSearchSpace(e,t){return e&&(this.prefixSearchSpace=e,this.backwardsPrefixSearchSpace=gt(e),this.prefixOffset=e.length),t&&(this.suffixSearchSpace=t,this.suffixOffset=0),this}useSegmenter(e){return e==null?this:(this.mode===this.Mode.ALL_PARTS?(this.startSegments=e.segment(this.startSearchSpace),this.endSegments=e.segment(this.endSearchSpace)):this.mode===this.Mode.SHARED_START_AND_END&&(this.sharedSegments=e.segment(this.sharedSearchSpace)),this.prefixSearchSpace&&(this.prefixSegments=e.segment(this.prefixSearchSpace)),this.suffixSearchSpace&&(this.suffixSegments=e.segment(this.suffixSearchSpace)),this)}getNumberOfContextWordsToAdd(){return this.backwardsPrefixOffset()===0&&this.suffixOffset===0?Ei:Ci}getNumberOfRangeWordsToAdd(){return this.startOffset===0&&this.backwardsEndOffset()===0?Ei:Ci}getNextOffsetForwards(e,t,i){let s=e.containing(t);for(;s!=null;){L();const r=s.index+s.segment.length;if(s.isWordLike)return r;s=e.containing(r)}return i.length}getNextOffsetBackwards(e,t){let i=e.containing(t);for((!i||t==i.index)&&(i=e.containing(t-1));i!=null;){if(L(),i.isWordLike)return i.index;i=e.containing(i.index-1)}return 0}getStartSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.startSearchSpace}getStartSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.startSegments}getEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.endSearchSpace}getEndSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.endSegments}getBackwardsEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.backwardsSharedSearchSpace:this.backwardsEndSearchSpace}getPrefixSearchSpace(){return this.prefixSearchSpace}getPrefixSegments(){return this.prefixSegments}getBackwardsPrefixSearchSpace(){return this.backwardsPrefixSearchSpace}getSuffixSearchSpace(){return this.suffixSearchSpace}getSuffixSegments(){return this.suffixSegments}backwardsEndOffset(){return this.getEndSearchSpace().length-this.endOffset}setBackwardsEndOffset(e){this.endOffset=this.getEndSearchSpace().length-e}backwardsPrefixOffset(){return this.prefixOffset==null?null:this.getPrefixSearchSpace().length-this.prefixOffset}setBackwardsPrefixOffset(e){this.prefixOffset!=null&&(this.prefixOffset=this.getPrefixSearchSpace().length-e)}};class ur{constructor(e,t){this.textFound=!1,this.textNodes=[],this.textInBlock=null,this.searchRange=e,this.isForwardTraversal=t}appendNode(e){if(this.textInBlock!==null)return;if(Z(e)){this.textFound?(this.isForwardTraversal||this.textNodes.reverse(),this.textInBlock=this.textNodes.map(i=>i.textContent).join("").trim()):this.textNodes=[];return}if(!Un(e))return;const t=this.getNodeIntersectionWithRange(e);this.textFound=this.textFound||(t.textContent??"").trim()!=="",this.textNodes.push(t)}getNodeIntersectionWithRange(e){let t=null,i=null;const s=(e.textContent??"").length;return e===this.searchRange.startContainer&&this.searchRange.startOffset!==0&&(t=this.searchRange.startOffset),e===this.searchRange.endContainer&&this.searchRange.endOffset!==s&&(i=this.searchRange.endOffset),t!==null||i!==null?{textContent:(e.textContent??"").substring(t??0,i??s)}:e}}const hr=(n,e,t)=>tr(n,e,t).length===1,gt=n=>[...n||""].reverse().join(""),Ll=n=>n.toString().length>Al?!1:!_l(n),Ye=n=>{let e=n.startContainer;return e.nodeType==Node.ELEMENT_NODE&&n.startOffset<e.childNodes.length&&(e=e.childNodes[n.startOffset]),e},$t=n=>{let e=n.endContainer;return e.nodeType==Node.ELEMENT_NODE&&n.endOffset>0&&(e=e.childNodes[n.endOffset-1]),e},$l=n=>{const e=Ye(n);if(Un(e)&&k.isNodeVisible(e))return e;const t=k.makeTextNodeWalker(n);return t.currentNode=e,t.nextNode()},Ml=n=>{const e=$t(n);if(Un(e)&&k.isNodeVisible(e))return e;const t=k.makeTextNodeWalker(n);return t.currentNode=e,k.backwardTraverse(t,new Set)},_l=n=>{const e=n.cloneRange();let t=Ye(e);const i=ue(t);if(!i)return!1;const s=new Set;for(;!e.collapsed&&t!=null;){if(Z(t))return!0;t!=null&&e.setStartAfter(t),t=k.forwardTraverse(i,s),L()}return!1},Ai=(n,e)=>{if(n.nodeType!==Node.TEXT_NODE)return-1;const t=n,i=e??t.data.length;if(i<t.data.length&&k.BOUNDARY_CHARS.test(t.data[i]))return i;const s=t.data.substring(0,i),r=gt(s).search(k.BOUNDARY_CHARS);return r!==-1?i-r:-1},Bl=(n,e)=>{if(n.nodeType!==Node.TEXT_NODE)return-1;const t=n,i=e??0;if(i<t.data.length&&i>0&&k.BOUNDARY_CHARS.test(t.data[i-1]))return i;const s=t.data.substring(i).search(k.BOUNDARY_CHARS);return s!==-1?i+s:-1},ue=(n,e)=>{if(!n)return;let t=n;const i=e??n;for(;!t.contains?.(i)||!Z(t);)t.parentNode&&(t=t.parentNode);const s=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:r=>k.acceptNodeIfVisibleInRange(r)});return s.currentNode=n,s},Ul=n=>{const e=k.makeNewSegmenter(n.startContainer.ownerDocument??void 0);if(e){const t=Ye(n);t!==n.startContainer&&n.setStartBefore(t),dr(e,!1,n)}else{const t=Ai(n.startContainer,n.startOffset);if(t!==-1){n.setStart(n.startContainer,t);return}if(Z(n.startContainer)&&n.startOffset===0)return;const i=ue(n.startContainer);if(!i)return;const s=new Set;let r=k.backwardTraverse(i,s);for(;r!=null;){const o=Ai(r);if(o!==-1){n.setStart(r,o);return}if(Z(r)){r.contains?.(n.startContainer)?n.setStart(r,0):n.setStartAfter(r);return}r=k.backwardTraverse(i,s),n.collapse()}}},zl=n=>{const e=$l(n);if(e==null){n.collapse();return}Ye(n)!==e&&n.setStart(e,0);const t=$t(n),i=Ml(n);t!==i&&n.setEnd(i,(i.textContent??"").length)},dr=(n,e,t)=>{const i=e?{node:t.endContainer,offset:t.endOffset}:{node:t.startContainer,offset:t.startOffset},s=Vl(i.node);if(!s)return;const r=s.preNodes.reduce((g,p)=>g.concat(p.textContent??""),""),o=s.innerNodes.reduce((g,p)=>g.concat(p.textContent??""),"");let a=r.length;i.node.nodeType===Node.TEXT_NODE?a+=i.offset:e&&(a+=o.length);const l=s.postNodes.reduce((g,p)=>g.concat(p.textContent??""),""),c=[...s.preNodes,...s.innerNodes,...s.postNodes];if(c.length==0)return;const u=r.concat(o,l),h=n.segment(u).containing(a);if(!h){e?t.setEndAfter(c[c.length-1]):t.setEndBefore(c[0]);return}if(!h.isWordLike||a===h.index||a===h.index+h.segment.length)return;const d=e?h.index+h.segment.length:h.index;let f=0;for(const g of c){const p=(g.textContent??"").length;if(f<=d&&d<f+p){const m=d-f;e?m>=p?t.setEndAfter(g):t.setEnd(g,m):m>=p?t.setStartAfter(g):t.setStart(g,m);return}f+=p}e?t.setEndAfter(c[c.length-1]):t.setStartBefore(c[0])},Vl=n=>{const e=[],t=ue(n);if(!t)return;const i=new Set;let s=k.backwardTraverse(t,i);for(;s!=null&&!Z(s);)L(),s.nodeType===Node.TEXT_NODE&&e.push(s),s=k.backwardTraverse(t,i);e.reverse();const r=[];if(n.nodeType===Node.TEXT_NODE)r.push(n);else{const u=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>k.acceptNodeIfVisibleInRange(d)});u.currentNode=n;let h=u.nextNode();for(;h!=null;)L(),h.nodeType===Node.TEXT_NODE&&r.push(h),h=u.nextNode()}const o=[],a=ue(n);if(!a)return;const l=new Set([n]);let c=k.forwardTraverse(a,l);for(;c!=null&&!Z(c);)L(),c.nodeType===Node.TEXT_NODE&&o.push(c),c=k.forwardTraverse(a,l);return{preNodes:e,innerNodes:r,postNodes:o}},jl=n=>{const e=k.makeNewSegmenter(n.endContainer.ownerDocument??void 0);if(e){const t=$t(n);t!==n.endContainer&&n.setEndAfter(t),dr(e,!0,n)}else{let t=n.endOffset,i=n.endContainer;i.nodeType===Node.ELEMENT_NODE&&n.endOffset<i.childNodes.length&&(i=i.childNodes[n.endOffset]);const s=ue(i);if(!s)return;const r=new Set([i]);for(;i!=null;){L();const o=Bl(i,t);if(t=null,o!==-1){n.setEnd(i,o);return}if(Z(i)){i.contains?.(n.endContainer)?n.setEnd(i,i.childNodes.length):n.setEndBefore(i);return}i=k.forwardTraverse(s,r)}n.collapse()}},Z=n=>n.nodeType===Node.ELEMENT_NODE&&(k.BLOCK_ELEMENTS.includes(n.tagName.toUpperCase())||n.tagName.toUpperCase()==="HTML"||n.tagName.toUpperCase()==="BODY"),Un=n=>n.nodeType===Node.TEXT_NODE;function hn(n){return n.otherLocations?.get("cssSelector")}function Hl(n){return Gs.deserialize(n.otherLocations?.get("domRange"))}function ql(n){for(const e of n.fragments){const t=Sl(e);if(t)return t}}let te=class fr{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const t=ft(e.progression),i=ft(e.totalProgression),s=ft(e.position),r=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,l])=>{o.has(a)||r.set(a,l)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,l)=>r.set(l,a)),new fr({fragments:cl(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:s!==void 0&&s>0?s:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,i)=>e[i]=t),e}},zn=class gr{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new gr({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}},Vn=class dn{constructor(e){const t=e.href.indexOf("#"),i=t>=0?e.href.slice(t+1):void 0;this.href=t>=0?e.href.slice(0,t):e.href,this.type=e.type,this.title=e.title;const s=e.locations?.fragments,r=i&&(!s||s.length===0);this.locations=e.locations?r?new te({...e.locations,fragments:[i]}):e.locations:i?new te({fragments:[i]}):new te({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new dn({href:e.href,type:e.type,title:e.title,locations:te.deserialize(e.locations),text:zn.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new dn({href:this.href,type:this.type,title:this.title,text:this.text,locations:new te({...this.locations,...e})})}};function Oi(n){return n.split("").reverse().join("")}function Wl(n,e,t){const i=Oi(e);return t.map(s=>{const r=Math.max(0,s.end-e.length-s.errors),o=Oi(n.slice(r,s.end));return{start:pr(o,i,s.errors).reduce((a,l)=>s.end-l.end<a?s.end-l.end:a,s.end),end:s.end,errors:s.errors}})}function Xt(n){return(n|-n)>>31&1}function Ti(n,e,t,i){let s=n.P[t],r=n.M[t];const o=i>>>31,a=e[t]|o,l=a|r,c=(a&s)+s^s|a;let u=r|~(c|s),h=s&c;const d=Xt(u&n.lastRowMask[t])-Xt(h&n.lastRowMask[t]);return u<<=1,h<<=1,h|=o,u|=Xt(i)-o,s=h|~(l|u),r=u&l,n.P[t]=s,n.M[t]=r,d}function pr(n,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const i=[],s=32,r=Math.ceil(e.length/s)-1,o={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};o.lastRowMask.fill(1<<31),o.lastRowMask[r]=1<<(e.length-1)%s;const a=new Uint32Array(r+1),l=new Map,c=[];for(let d=0;d<256;d++)c.push(a);for(let d=0;d<e.length;d+=1){const f=e.charCodeAt(d);if(l.has(f))continue;const g=new Uint32Array(r+1);l.set(f,g),f<c.length&&(c[f]=g);for(let p=0;p<=r;p+=1){g[p]=0;for(let m=0;m<s;m+=1){const y=p*s+m;y>=e.length||e.charCodeAt(y)===f&&(g[p]|=1<<m)}}}let u=Math.max(0,Math.ceil(t/s)-1);const h=new Uint32Array(r+1);for(let d=0;d<=u;d+=1)h[d]=(d+1)*s;h[r]=e.length;for(let d=0;d<=u;d+=1)o.P[d]=-1,o.M[d]=0;for(let d=0;d<n.length;d+=1){const f=n.charCodeAt(d);let g;f<c.length?g=c[f]:(g=l.get(f),typeof g>"u"&&(g=a));let p=0;for(let m=0;m<=u;m+=1)p=Ti(o,g,m,p),h[m]+=p;if(h[u]-p<=t&&u<r&&(g[u+1]&1||p<0)){u+=1,o.P[u]=-1,o.M[u]=0;let m;if(u===r){const y=e.length%s;m=y===0?s:y}else m=s;h[u]=h[u-1]+m-p+Ti(o,g,u,p)}else for(;u>0&&h[u]>=t+s;)u-=1;u===r&&h[u]<=t&&(h[u]<t&&i.splice(0,i.length),i.push({start:-1,end:d+1,errors:h[u]}),t=h[u])}return i}function Kl(n,e,t){const i=pr(n,e,t);return Wl(n,e,i)}function mr(n,e,t){let i=0;const s=[];for(;i!==-1;)i=n.indexOf(e,i),i!==-1&&(s.push({start:i,end:i+e.length,errors:0}),i+=1);return s.length>0?s:Kl(n,e,t)}function Ni(n,e){return e.length===0||n.length===0?0:1-mr(n,e,e.length)[0].errors/e.length}function Gl(n,e,t={}){if(e.length===0)return null;const i=Math.min(256,e.length/2),s=mr(n,e,i);if(s.length===0)return null;const r=a=>{const l=1-a.errors/e.length,c=t.prefix?Ni(n.slice(Math.max(0,a.start-t.prefix.length),a.start),t.prefix):1,u=t.suffix?Ni(n.slice(a.end,a.end+t.suffix.length),t.suffix):1;let h=1;return typeof t.hint=="number"&&(h=1-Math.abs(a.start-t.hint)/n.length),(50*l+20*c+20*u+2*h)/92},o=s.map(a=>({start:a.start,end:a.end,score:r(a)}));return o.sort((a,l)=>l.score-a.score),o[0]}function fn(n,e,t){const i=t===1?e:e-1;if(n.charAt(i).trim()!=="")return e;let s,r;if(t===2?(s=n.substring(0,e),r=s.trimEnd()):(s=n.substring(e),r=s.trimStart()),!r.length)return-1;const o=s.length-r.length;return t===2?e-o:e+o}function Di(n,e){const t=n.commonAncestorContainer.ownerDocument.createNodeIterator(n.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=e===1?n.startContainer:n.endContainer,s=e===1?n.endContainer:n.startContainer;let r=t.nextNode();for(;r&&r!==i;)r=t.nextNode();e===2&&(r=t.previousNode());let o=-1;const a=()=>{if(r=e===1?t.nextNode():t.previousNode(),r){const l=r.textContent,c=e===1?0:l.length;o=fn(l,c,e)}};for(;r&&o===-1&&r!==s;)a();if(r&&o>=0)return{node:r,offset:o};throw new RangeError("No text nodes with non-whitespace text found in range")}function Xl(n){if(!n.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(n.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(n.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=n.cloneRange();let t=!1,i=!1;const s={start:fn(n.startContainer.textContent,n.startOffset,1),end:fn(n.endContainer.textContent,n.endOffset,2)};if(s.start>=0&&(e.setStart(n.startContainer,s.start),t=!0),s.end>0&&(e.setEnd(n.endContainer,s.end),i=!0),t&&i)return e;if(!t){const{node:r,offset:o}=Di(e,1);r&&o>=0&&e.setStart(r,o)}if(!i){const{node:r,offset:o}=Di(e,2);r&&o>0&&e.setEnd(r,o)}return e}function Sr(n){switch(n.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return n.textContent?.length??0;default:return 0}}function Pi(n){let e=n.previousSibling,t=0;for(;e;)t+=Sr(e),e=e.previousSibling;return t}function vr(n,...e){let t=e.shift();const i=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),s=[];let r=i.nextNode(),o,a=0;for(;t!==void 0&&r;)o=r,a+o.data.length>t?(s.push({node:o,offset:t-a}),t=e.shift()):(r=i.nextNode(),a+=o.data.length);for(;t!==void 0&&o&&a===t;)s.push({node:o,offset:o.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return s}let at=class me{constructor(e,t){if(t<0)throw new Error("Offset is invalid");this.element=e,this.offset=t}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let t=this.element,i=this.offset;for(;t!==e;)i+=Pi(t),t=t.parentElement;return new me(t,i)}resolve(e={}){try{return vr(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const s=e.direction===1,r=s?i.nextNode():i.previousNode();if(!r)throw t;return{node:r,offset:s?0:r.data.length}}else throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return me.fromPoint(e,t);case Node.ELEMENT_NODE:return new me(e,t);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,t){switch(e.nodeType){case Node.TEXT_NODE:{if(t<0||t>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent");const i=Pi(e)+t;return new me(e.parentElement,i)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let s=0;s<t;s++)i+=Sr(e.childNodes[s]);return new me(e,i)}default:throw new Error("Point is not in an element or text node")}}},gn=class ze{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new ze(this.start.relativeTo(e),this.end.relativeTo(e))}toRange(){let e,t;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[e,t]=vr(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const i=new Range;return i.setStart(e.node,e.offset),i.setEnd(t.node,t.offset),i}static fromRange(e){const t=at.fromPoint(e.startContainer,e.startOffset),i=at.fromPoint(e.endContainer,e.endOffset);return new ze(t,i)}static fromOffsets(e,t,i){return new ze(new at(e,t),new at(e,i))}static trimmedRange(e){return Xl(ze.fromRange(e).toRange())}},Jl=class pn{constructor(e,t,i){this.root=e,this.start=t,this.end=i}static fromRange(e,t){const i=gn.fromRange(t).relativeTo(e);return new pn(e,i.start.offset,i.end.offset)}static fromSelector(e,t){return new pn(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return gn.fromOffsets(this.root,this.start,this.end).toRange()}},Yl=class mn{constructor(e,t,i={}){this.root=e,this.exact=t,this.context=i}static fromRange(e,t){const i=e.textContent,s=gn.fromRange(t).relativeTo(e),r=s.start.offset,o=s.end.offset,a=32;return new mn(e,i.slice(r,o),{prefix:i.slice(Math.max(0,r-a),r),suffix:i.slice(o,Math.min(i.length,o+a))})}static fromSelector(e,t){const{prefix:i,suffix:s}=t;return new mn(e,t.exact,{prefix:i,suffix:s})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const t=this.root.textContent,i=Gl(t,this.exact,{...this.context,hint:e.hint});if(!i)throw new Error("Quote not found");return new Jl(this.root,i.start,i.end)}};function Ql(n){const e=n.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Fi(n,e){const t=e&&hn(e);let i=null;if(t)try{i=n.querySelector(t)}catch(s){console.warn(`Invalid cssSelector: ${t}`,s)}return i??n.body??n.documentElement}function Ii(n,e){let t;try{t=n.querySelector(e.cssSelector)}catch(s){return console.error(`Invalid domRange cssSelector: ${e.cssSelector}`,s),null}if(!t)return console.error(`Can't resolve domRange cssSelector: ${e.cssSelector}`),null;let i=0;for(const s of t.childNodes)if(s.nodeType===Node.TEXT_NODE){if(i===e.textNodeIndex)return{node:s,offset:e.charOffset};i++}return console.error(`Can't resolve domRange textNodeIndex ${e.textNodeIndex} for selector: ${e.cssSelector}`),null}function Zl(n,e){try{const t=e.locations,i=e.text;if(t){const s=Hl(t);if(s){const r=Ii(n,s.start),o=s.end?Ii(n,s.end):r;if(r&&o)try{const a=n.createRange();return r.offset!==void 0?a.setStart(r.node,r.offset):a.setStartBefore(r.node),o.offset!==void 0?a.setEnd(o.node,o.offset):a.setEndBefore(o.node),a}catch(a){console.warn("Invalid domRange, falling back:",a)}}}if(t){const s=ql(t);if(s){const r=Fi(n,t),o=tr(s,n,r);if(o.length>0)return o[0]}}if(i&&i.highlight){const s=Fi(n,t),r=new Yl(s,i.highlight,{prefix:i.before,suffix:i.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(t){let s=null;if(!s&&hn(t)&&(s=n.querySelector(hn(t))),!s&&t.fragments){for(const r of t.fragments)if(s=n.getElementById(r),s)break}if(s){const r=n.createRange();return s.childNodes.length===0||Ql(s)?(r.selectNode(s),r):(r.setStartBefore(s),r.setEndAfter(s),r)}}}catch(t){console.error(t)}return null}function ec(n,e){const t=e.map(l=>l.toUpperCase()),i=[],s=n.commonAncestorContainer,r=s.nodeType===Node.TEXT_NODE?s.parentNode:s,o=n.startContainer.ownerDocument.createTreeWalker(r,NodeFilter.SHOW_TEXT);let a=o.nextNode();for(;a;){if(n.intersectsNode(a)){let l=a.parentNode,c=!1;for(;l;){if(l.nodeType===Node.ELEMENT_NODE&&t.includes(l.tagName.toUpperCase())){c=!0;break}l=l.parentNode}if(!c){const u=n.cloneRange();u.selectNode(a),u.compareBoundaryPoints(Range.START_TO_START,n)<0&&u.setStart(n.startContainer,n.startOffset),u.compareBoundaryPoints(Range.END_TO_END,n)>0&&u.setEnd(n.endContainer,n.endOffset);for(const h of u.getClientRects())i.push({left:h.left,right:h.right,top:h.top,bottom:h.bottom,width:h.width,height:h.height})}}a=o.nextNode()}return i}function $e(n,e,t=!1,i=0){let s;if(Array.isArray(n))s=n;else{let c=n.getClientRects();c.length||n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(c=n.commonAncestorContainer.getClientRects()),s=[];for(const u of c)s.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.width})}if(i)for(const c of s)c.left-=i,c.top-=i,c.right+=i,c.bottom+=i,c.width+=i*2,c.height+=i*2;const r=yr(s,1,e,t),o=nc(r,1),a=br(o),l=4;for(let c=a.length-1;c>=0;c--){const u=a[c];if(!(u.width*u.height>l))if(a.length>1)a.splice(c,1);else break}return a}function yr(n,e,t,i=!1){for(let s=0;s<n.length;s++)for(let r=s+1;r<n.length;r++){const o=n[s],a=n[r];if(o===a)continue;const l=B(o.top,a.top,e)&&B(o.bottom,a.bottom,e),c=B(o.left,a.left,e)&&B(o.right,a.right,e);if((c&&!t&&!i||l&&!c)&&wr(o,a,e)){const u=n.filter(d=>d!==o&&d!==a),h=tc(o,a);return u.push(h),yr(u,e,t,i)}}return n}function tc(n,e){const t=Math.min(n.left,e.left),i=Math.max(n.right,e.right),s=Math.min(n.top,e.top),r=Math.max(n.bottom,e.bottom);return{bottom:r,height:r-s,left:t,right:i,top:s,width:i-t}}function nc(n,e){const t=new Set(n);for(const i of n){if(!(i.width>1&&i.height>1)){t.delete(i);continue}for(const s of n)if(i!==s&&t.has(s)&&ic(s,i,e)){t.delete(i);break}}return Array.from(t)}function ic(n,e,t){return Q(n,e.left,e.top,t)&&Q(n,e.right,e.top,t)&&Q(n,e.left,e.bottom,t)&&Q(n,e.right,e.bottom,t)}function Q(n,e,t,i){return(n.left<e||B(n.left,e,i))&&(n.right>e||B(n.right,e,i))&&(n.top<t||B(n.top,t,i))&&(n.bottom>t||B(n.bottom,t,i))}function br(n){for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){const i=n[e],s=n[t];if(i!==s&&wr(i,s,-1)){let r=[],o;const a=Li(i,s);if(a.length===1)r=a,o=i;else{const c=Li(s,i);a.length<c.length?(r=a,o=i):(r=c,o=s)}const l=n.filter(c=>c!==o);return Array.prototype.push.apply(l,r),br(l)}}return n}function Li(n,e){const t=sc(e,n);if(t.height===0||t.width===0)return[n];const i=[];{const s={bottom:n.bottom,height:0,left:n.left,right:t.left,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:t.top,height:0,left:t.left,right:t.right,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:n.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:n.bottom,height:0,left:t.right,right:n.right,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}return i}function sc(n,e){const t=Math.max(n.left,e.left),i=Math.min(n.right,e.right),s=Math.max(n.top,e.top),r=Math.min(n.bottom,e.bottom);return{bottom:r,height:Math.max(0,r-s),left:t,right:i,top:s,width:Math.max(0,i-t)}}function wr(n,e,t){return(n.left<e.right||t>=0&&B(n.left,e.right,t))&&(e.left<n.right||t>=0&&B(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&B(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&B(e.top,n.bottom,t))}function B(n,e,t){return Math.abs(n-e)<=t}const $i=["div","span","p","br","hr","b","i","em","strong","s","u","mark","small","sub","sup","abbr","cite","code","data","dfn","kbd","q","samp","time","var","blockquote","pre","svg","g","path","circle","ellipse","rect","line","polygon","polyline","text","tspan","defs","use"],rc=/^on/i,oc=new Set(["href","src","action","formaction","xlink:href"]),ac=/^\s*(javascript|data):/i;function lc(n,e){const t=n.document.createElement("div");if("Sanitizer"in n&&typeof t.setHTML=="function")try{const s=new n.Sanitizer({allowElements:$i});return t.setHTML(e,{sanitizer:s}),t.firstElementChild}catch{}const i=n.document.implementation.createHTMLDocument("");for(i.body.innerHTML=e,cc(i.body,new Set($i));i.body.firstChild;)t.appendChild(n.document.adoptNode(i.body.firstChild));return t.firstElementChild}function cc(n,e){const t=Array.from(n.querySelectorAll("*")).reverse();for(const i of t){if(!e.has(i.localName)){i.replaceWith(...Array.from(i.childNodes));continue}for(const{name:s,value:r}of Array.from(i.attributes))(rc.test(s)||oc.has(s)&&ac.test(r))&&i.removeAttribute(s)}}function Jt(n){switch(n){case E.Mask:return"rgba(255, 255, 255, 0.5)";case E.Highlight:case E.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const E={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var xr=(n=>(n.Wrap="wrap",n.Viewport="viewport",n.Bounds="bounds",n.Page="page",n))(xr||{}),Er=(n=>(n.Boxes="boxes",n.Bounds="bounds",n))(Er||{});const uc=()=>"Highlight"in window,Mi=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class hc{constructor(e,t,i,s){this.wnd=e,this.comms=t,this.id=i,this.name=s,this.items=[],this.lastItemId=0,this.container=void 0,this._activatable=!1,this._hoverable=!1,this.hoveredItem=void 0,this.experimentalHighlights=!1,this._tintSubKeys=new Map,this._subKeyCounter=0,this.maskSvg=void 0,this.shadowHost=void 0,this.shadowRoot=void 0,this.currentRender=0,uc()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map),this.activationHandler=this.handleActivation.bind(this),this.wnd.document.addEventListener("pointerup",this.activationHandler),this.hoverHandler=this.handleHover.bind(this),this.wnd.document.addEventListener("pointermove",this.hoverHandler)}get activatable(){return this._activatable}set activatable(e){this._activatable=e}get hoverable(){return this._hoverable}get hasOverlayItems(){return!this.experimentalHighlights||(this.notTextFlag?.size??0)>0}set hoverable(e){if(this._hoverable=e,!e&&this.hoveredItem){const t=this.hoveredItem.range.getBoundingClientRect(),i=this.wnd.devicePixelRatio;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:{top:t.top*i,left:t.left*i,width:t.width*i,height:t.height*i}}),this.hoveredItem=void 0}}add(e){const t=`${this.id}-${this.lastItemId++}`,i=Zl(this.wnd.document,e.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",e);return}const s=i.commonAncestorContainer;if(s.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(Mi.includes(s.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),i.cloneContents().querySelector(Mi.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(s.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0)),this.experimentalHighlights&&!this.notTextFlag?.has(t)){const o=a=>{for(;a&&a.nodeType===Node.ELEMENT_NODE;){if(a.namespaceURI?.includes("svg"))return!0;a=a.parentNode}return!1};(o(i.startContainer)||o(i.endContainer))&&this.notTextFlag?.set(t,!0)}if(this.experimentalHighlights){const{type:o}=e.style,{layout:a,width:l,expand:c}=e.style;o!==E.TextColor&&(o===E.Outline||o===E.Template||o===E.Mask||a!==void 0&&a!=="boxes"||l!==void 0&&l!=="wrap"||c)&&this.notTextFlag?.set(t,!0)}const r={decoration:e,id:t,range:i,hitRects:[],clickableElements:void 0,container:void 0};this.items.push(r),this.layout(r),r.hitRects=this.clientRectsToDocCoords($e(r.range,!1,!1,(r.decoration.style.expand??0)+this.hitGap())),this.renderLayout([r])}remove(e){const t=this.items.findIndex(r=>r.decoration.id===e);if(t<0)return;const i=this.items[t],s=i.decoration.style?.type===E.Mask;if(this.items.splice(t,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&i.highlightSubKey){const r=this.wnd.CSS.highlights;r.get(i.highlightSubKey)?.delete(i.range),this.items.some(a=>a.highlightSubKey===i.highlightSubKey)||r.delete(i.highlightSubKey);const o=this.wnd.document.getElementById(`${this.id}-style`);o&&this._rebuildHighlightStylesheet(o)}this.notTextFlag?.delete(i.id),this.hoveredItem===i&&(this.hoveredItem=void 0),s&&this.updateSharedMask()}update(e){this.remove(e.id),this.add(e)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear(),this.hoveredItem=void 0,this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&(this.shadowHost.remove(),this.shadowHost=void 0,this.shadowRoot=void 0)}destroy(){this.clear(),this.wnd.document.removeEventListener("pointerup",this.activationHandler),this.wnd.document.removeEventListener("pointermove",this.hoverHandler)}clientRectsToDocCoords(e,t=de(this.wnd)){const i=t.xDocOffset,s=t.yDocOffset;return i===0&&s===0?e:e.map(r=>({left:r.left+i,top:r.top+s,right:r.right+i,bottom:r.bottom+s,width:r.width,height:r.height}))}pointerToDocCoords(e){const t=de(this.wnd);return{docX:e.clientX+t.xDocOffset,docY:e.clientY+t.yDocOffset}}effectiveZoom(){if(!ml.UA.Blink)return 1;const e=parseFloat(this.wnd.getComputedStyle(this.wnd.document.documentElement).zoom),t=parseFloat(this.wnd.getComputedStyle(this.wnd.document.body).zoom);return(e||1)*(t||1)}hitGap(){return 2*this.effectiveZoom()}handleActivation(e){if(!this._activatable)return;const{docX:t,docY:i}=this.pointerToDocCoords(e),s=this.wnd.devicePixelRatio;for(const r of this.items){let o;if(r.decoration.style.type===E.Template)for(const a of r.clickableElements??[]){const l=a.getBoundingClientRect();if(Q(l,e.clientX,e.clientY,0)){o=l;break}}else for(const a of r.hitRects)if(Q(a,t,i,0)){o=r.range.getBoundingClientRect();break}if(o){this.comms.send("decoration_activated",{decorationId:r.decoration.id,group:this.name,rect:{top:o.top*s,left:o.left*s,width:o.width*s,height:o.height*s},point:{x:e.clientX*s,y:e.clientY*s}});return}}}handleHover(e){if(!this._hoverable)return;const{docX:t,docY:i}=this.pointerToDocCoords(e),s=this.wnd.devicePixelRatio;let r,o;for(const a of this.items){if(a.decoration.style.type===E.Template)for(const l of a.clickableElements??[]){const c=l.getBoundingClientRect();if(Q(c,e.clientX,e.clientY,0)){r=a,o=c;break}}else for(const l of a.hitRects)if(Q(l,t,i,0)){r=a,o=a.range.getBoundingClientRect();break}if(r)break}if(r!==this.hoveredItem){if(this.hoveredItem){const a=this.hoveredItem.range.commonAncestorContainer.isConnected?this.hoveredItem.range.getBoundingClientRect():null;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:a?{top:a.top*s,left:a.left*s,width:a.width*s,height:a.height*s}:void 0,point:{x:e.clientX*s,y:e.clientY*s}})}this.hoveredItem=r,r&&o&&this.comms.send("decoration_pointer_enter",{decorationId:r.decoration.id,group:this.name,rect:{top:o.top*s,left:o.left*s,width:o.width*s,height:o.height*s},point:{x:e.clientX*s,y:e.clientY*s}})}}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.wnd.document.fonts.ready.then(()=>{this.currentRender=this.wnd.requestAnimationFrame(()=>{this.items.forEach(e=>{this.layout(e),e.hitRects=this.clientRectsToDocCoords($e(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}repositionOverlays(){let e=!1;const t=[],i=de(this.wnd);this.items.forEach(s=>{if(!(this.experimentalHighlights&&!this.notTextFlag?.has(s.id))){if(s.decoration.style?.type===E.Mask){e=!0;return}this.repositionItem(s,i)||(s.container?.remove(),this.layout(s),t.push(s)),s.hitRects=this.clientRectsToDocCoords($e(s.range,!1,!1,(s.decoration.style.expand??0)+this.hitGap()),i)}}),t.length&&this.renderLayout(t),e&&this.updateSharedMask()}experimentalLayout(e){const t=this.requireContainer(!0),i=this.wnd.CSS.highlights,s=e.decoration.style,r=s.type??E.Highlight,o=s.tint??Jt(r),a=s.width,l=s.layout,c=this._getSubKey(r,o);e.highlightSubKey&&(i.get(e.highlightSubKey)?.delete(e.range),e.highlightSubKey!==c&&!this.items.some(p=>p!==e&&p.highlightSubKey===e.highlightSubKey)&&i.delete(e.highlightSubKey)),e.highlightSubKey=c;let u;i.has(c)?u=i.get(c):(u=new this.wnd.Highlight,i.set(c,u));const h=(p,m)=>this.wnd.document.caretPositionFromPoint?.(p,m)??null;if(r===E.TextColor&&(l==="bounds"||a==="bounds"||a==="page")){const p=de(this.wnd);if(p.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),u.add(e.range);else{const m=e.range.getBoundingClientRect();let y,w;a==="page"?(y=Math.floor(p.inlineStart(m)/p.pageInlineSize)*p.pageInlineSize,w=p.pageInlineSize):(y=p.inlineStart(m),w=p.inlineSize(m));const S=h(y,p.blockStart(m)+1),v=h(y+w,p.blockStart(m)+p.blockSize(m)-1);if(S&&v){const b=this.wnd.document.createRange();b.setStart(S.offsetNode,S.offset),b.setEnd(v.offsetNode,v.offset),u.add(b),e.range=b}else u.add(e.range)}}else u.add(e.range);const d=this.getBackgroundColor(),f=s.enforceContrast!==!1?ge(o,d):o;let g;switch(r){case E.Underline:g=`::highlight(${c}) {
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=n=>{if(!n)return["",void 0];const e=n.replace(/_/g,"-");try{const t=new Intl.Locale(e);return[t.language.toLowerCase(),t.region?.toUpperCase()]}catch{const t=e.split("-");return[t[0].toLowerCase(),t[1]?.toUpperCase()]}},G={ar:{defaultRegion:"SA",availableRegions:["001","AE","AS","BH","DZ","EG","IQ","JO","KW","LB","LY","MA","OM","QA","SA","SY","TN","YE"],testUtterance:"مرحبًا، اسمي {name} وأنا صوت عربي."},bg:{defaultRegion:"BG",availableRegions:["BG"],testUtterance:"Здравейте, казвам се {name} и съм български глас."},bho:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, हमार नाम {name} ह आ हम भोजपुरी आवाज हईं"},bn:{defaultRegion:"IN",availableRegions:["BD","IN"],testUtterance:"হ্যালো, আমার নাম {name} এবং আমি একজন বাংলা ভয়েস।"},ca:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Hola, em dic {name} i sóc una veu catalana"},cmn:{defaultRegion:"CN",availableRegions:["CN","CTW","TW"],testUtterance:"你好,我的名字是 {name},我是普通话配音。"},cs:{defaultRegion:"CZ",availableRegions:["CZ"],testUtterance:"Dobrý den, jmenuji se {name} a jsem český hlas."},da:{defaultRegion:"DK",availableRegions:["DK"],testUtterance:"Hej, mit navn er {name} og jeg er en dansk stemme."},de:{defaultRegion:"DE",availableRegions:["AT","CH","DE"],testUtterance:"Hallo, mein Name ist {name} und ich bin eine deutsche Stimme."},el:{defaultRegion:"GR",availableRegions:["GR"],testUtterance:"Γεια σας, με λένε {name} και είμαι ελληνική φωνή."},en:{defaultRegion:"US",availableRegions:["AU","CA","GB","HK","IE","IN","KE","NG","NZ","PH","SG","TZ","US","ZA"],testUtterance:"Hello, my name is {name} and I am an English voice."},es:{defaultRegion:"ES",availableRegions:["AR","BO","CL","CO","CR","CU","DO","EC","ES","GQ","GT","HN","MX","NI","PA","PE","PR","PY","SV","US","UY","VE"],testUtterance:"Hola, mi nombre es {name} y soy una voz española."},eu:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Kaixo, nire izena {name} da eta euskal ahotsa naiz."},fa:{defaultRegion:"IR",availableRegions:["IR"],testUtterance:"سلام اسم من {name} و صدای فارسی هستم"},fi:{defaultRegion:"FI",availableRegions:["FI"],testUtterance:"Hei, nimeni on {name} ja olen suomalainen ääni."},fr:{defaultRegion:"FR",availableRegions:["BE","CA","CH","FR"],testUtterance:"Bonjour, mon nom est {name} et je suis une voix française."},gl:{defaultRegion:"ES",availableRegions:["ES"],testUtterance:"Ola, chámome {name} e son unha voz galega."},he:{defaultRegion:"IL",availableRegions:["IL"],testUtterance:"שלום, שמי {name} ואני קול עברי."},hi:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, मेरा नाम {name} है और मैं एक हिंदी आवाज़ हूँ।"},hr:{defaultRegion:"HR",availableRegions:["HR"],testUtterance:"Pozdrav, ja sam {name} i hrvatski sam glas."},hu:{defaultRegion:"HU",availableRegions:["HU"],testUtterance:"Helló, a nevem {name} és magyar hangú vagyok."},id:{defaultRegion:"ID",availableRegions:["ID"],testUtterance:"Halo, nama saya {name} dan saya suara Indonesia."},it:{defaultRegion:"IT",availableRegions:["IT"],testUtterance:"Ciao, mi chiamo {name} e sono una voce italiana."},ja:{defaultRegion:"JP",availableRegions:["JP"],testUtterance:"こんにちは。私の名前は{name}で、日本語の声を担当しています。"},kk:{defaultRegion:"KZ",availableRegions:["KZ"],testUtterance:"Sälemetsiz be, meniñ atım {name} jäne men qazaq dawısımın."},kn:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"ಹಲೋ, ನನ್ನ ಹೆಸರು {name} ಮತ್ತು ನಾನು ಕನ್ನಡ ಧ್ವನಿ."},ko:{defaultRegion:"KR",availableRegions:["KR"],testUtterance:"안녕하세요, 저는 {name}이고 한국어 음성입니다."},mr:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"नमस्कार, माझे नाव {name} आहे आणि मी एक मराठी आवाज आहे."},ms:{defaultRegion:"MY",availableRegions:["MY"],testUtterance:"Hello, nama saya {name} dan saya suara Melayu."},nb:{defaultRegion:"NO",availableRegions:["NO"],testUtterance:"Hei, jeg heter {name} og er en norsk stemme."},nl:{defaultRegion:"NL",availableRegions:["BE","NL"],testUtterance:"Hallo, mijn naam is {name} en ik ben een Nederlandse stem."},pl:{defaultRegion:"PL",availableRegions:["PL"],testUtterance:"Cześć, nazywam się {name} i mam polski głos."},pt:{defaultRegion:"BR",availableRegions:["BR","PT"],testUtterance:"Olá, o meu nome é {name} e sou uma voz portuguesa."},ro:{defaultRegion:"RO",availableRegions:["RO"],testUtterance:"Buna ziua, ma numesc {name} si sunt o voce romaneasca."},ru:{defaultRegion:"RU",availableRegions:["RU"],testUtterance:"Здравствуйте, меня зовут {name} и я русский голос."},sk:{defaultRegion:"SK",availableRegions:["SK"],testUtterance:"Dobrý deň, volám sa {name} a som slovenský hlas."},sl:{defaultRegion:"SI",availableRegions:["SI"],testUtterance:"Pozdravljeni, moje ime je {name} in sem slovenski glas."},sv:{defaultRegion:"SE",availableRegions:["SE"],testUtterance:"Hej, jag heter {name} och jag är en svensk röst."},ta:{defaultRegion:"IN",availableRegions:["IN","LK","MY","SG"],testUtterance:"வணக்கம், என் பெயர் {name} மற்றும் நான் ஒரு தமிழ் குரல்"},te:{defaultRegion:"IN",availableRegions:["IN"],testUtterance:"హలో, నా పేరు {name} మరియు నేను తెలుగు వాణిని."},th:{defaultRegion:"TH",availableRegions:["TH"],testUtterance:"สวัสดีค่ะ ฉันชื่อ {name} และฉันเป็นคนมีเสียงภาษาไทย"},tr:{defaultRegion:"TR",availableRegions:["TR"],testUtterance:"Merhaba, adım {name} ve Türk sesiyim."},uk:{defaultRegion:"UA",availableRegions:["UA"],testUtterance:"Здравствуйте, меня зовут {name} и я украинский голос."},vi:{defaultRegion:"VN",availableRegions:["VN"],testUtterance:"Xin chào, tôi tên là {name} và tôi là giọng nói tiếng Việt."},wuu:{defaultRegion:"CN",availableRegions:["CN"],testUtterance:"你好,我的名字是 {name},我是吴语配音。"},yue:{defaultRegion:"HK",availableRegions:["HK"],testUtterance:"你好,我叫 {name},係越中文聲。"}},Vt=new Map,Vo=Object.assign({"../../json/ar.json":()=>Promise.resolve().then(()=>require("./ar-BYWkyZgW.cjs")),"../../json/bg.json":()=>Promise.resolve().then(()=>require("./bg-D7xe9YTl.cjs")),"../../json/bho.json":()=>Promise.resolve().then(()=>require("./bho-UB6aO8oz.cjs")),"../../json/bn.json":()=>Promise.resolve().then(()=>require("./bn-boRZ2pl5.cjs")),"../../json/ca.json":()=>Promise.resolve().then(()=>require("./ca-DkC8kSJ8.cjs")),"../../json/cmn.json":()=>Promise.resolve().then(()=>require("./cmn-BsNLjyA4.cjs")),"../../json/cs.json":()=>Promise.resolve().then(()=>require("./cs-p05r08p7.cjs")),"../../json/da.json":()=>Promise.resolve().then(()=>require("./da-crefCup9.cjs")),"../../json/de.json":()=>Promise.resolve().then(()=>require("./de-xoW-RuhZ.cjs")),"../../json/el.json":()=>Promise.resolve().then(()=>require("./el-C025sTug.cjs")),"../../json/en.json":()=>Promise.resolve().then(()=>require("./en-CbfmLXbR.cjs")),"../../json/es.json":()=>Promise.resolve().then(()=>require("./es-DW7IPf8I.cjs")),"../../json/eu.json":()=>Promise.resolve().then(()=>require("./eu-uq15ZgwW.cjs")),"../../json/fa.json":()=>Promise.resolve().then(()=>require("./fa-CHOnwiFr.cjs")),"../../json/fi.json":()=>Promise.resolve().then(()=>require("./fi-Bxlno6Zi.cjs")),"../../json/fr.json":()=>Promise.resolve().then(()=>require("./fr-yAth5-FC.cjs")),"../../json/gl.json":()=>Promise.resolve().then(()=>require("./gl-BEgzCAO0.cjs")),"../../json/he.json":()=>Promise.resolve().then(()=>require("./he-B-CTHJPL.cjs")),"../../json/hi.json":()=>Promise.resolve().then(()=>require("./hi-C0yUjV1-.cjs")),"../../json/hr.json":()=>Promise.resolve().then(()=>require("./hr-CZvFOcdo.cjs")),"../../json/hu.json":()=>Promise.resolve().then(()=>require("./hu-_2PInItj.cjs")),"../../json/id.json":()=>Promise.resolve().then(()=>require("./id-BROcb7-t.cjs")),"../../json/it.json":()=>Promise.resolve().then(()=>require("./it-Bmc8Ycff.cjs")),"../../json/ja.json":()=>Promise.resolve().then(()=>require("./ja-B8t6WOeg.cjs")),"../../json/kk.json":()=>Promise.resolve().then(()=>require("./kk-DskO1CW8.cjs")),"../../json/kn.json":()=>Promise.resolve().then(()=>require("./kn-Cy3NH6na.cjs")),"../../json/ko.json":()=>Promise.resolve().then(()=>require("./ko-CZdQzppZ.cjs")),"../../json/mr.json":()=>Promise.resolve().then(()=>require("./mr-9hGqBYlV.cjs")),"../../json/ms.json":()=>Promise.resolve().then(()=>require("./ms-DzpBxNFZ.cjs")),"../../json/nb.json":()=>Promise.resolve().then(()=>require("./nb-BQfw9EEH.cjs")),"../../json/nl.json":()=>Promise.resolve().then(()=>require("./nl-CyM0R4Gr.cjs")),"../../json/pl.json":()=>Promise.resolve().then(()=>require("./pl-Da8XOMa1.cjs")),"../../json/pt.json":()=>Promise.resolve().then(()=>require("./pt-tubyvYaM.cjs")),"../../json/ro.json":()=>Promise.resolve().then(()=>require("./ro-C-rXDfuM.cjs")),"../../json/ru.json":()=>Promise.resolve().then(()=>require("./ru-DJocRaDd.cjs")),"../../json/sk.json":()=>Promise.resolve().then(()=>require("./sk-BvpojIXp.cjs")),"../../json/sl.json":()=>Promise.resolve().then(()=>require("./sl-D0X3JKvQ.cjs")),"../../json/sv.json":()=>Promise.resolve().then(()=>require("./sv-4lEgrHda.cjs")),"../../json/ta.json":()=>Promise.resolve().then(()=>require("./ta-CyeVPdIs.cjs")),"../../json/te.json":()=>Promise.resolve().then(()=>require("./te-DqWIZZxL.cjs")),"../../json/th.json":()=>Promise.resolve().then(()=>require("./th-BcoSVZAp.cjs")),"../../json/tr.json":()=>Promise.resolve().then(()=>require("./tr-BuafNhfw.cjs")),"../../json/uk.json":()=>Promise.resolve().then(()=>require("./uk-DkXNxnD9.cjs")),"../../json/vi.json":()=>Promise.resolve().then(()=>require("./vi-Ct2avSE6.cjs")),"../../json/wuu.json":()=>Promise.resolve().then(()=>require("./wuu-DnwGQ6c-.cjs")),"../../json/yue.json":()=>Promise.resolve().then(()=>require("./yue-j9Y48sR-.cjs"))});async function jo(n){try{const e=n.split("-")[0],t=Vo[`../../json/${e}.json`];if(!t)throw new Error(`No voice data found for language: ${n}`);const s=(await t()).default;return{...s,voices:s.voices.map(Wo)}}catch(e){return console.warn(`Failed to load voice data for ${n}:`,e),{language:n,defaultRegion:"",testUtterance:"",voices:[]}}}function ai(n){return Vt.has(n)||Vt.set(n,jo(n)),Vt.get(n)}const Ho=["veryLow","low","normal","high","veryHigh"],qo=["android","apple"],Wo=n=>({...n,quality:n.quality?.filter(e=>Ho.includes(e)),localizedName:n.localizedName&&qo.includes(n.localizedName)?n.localizedName:void 0}),xe={cmn:"cmn","cmn-CN":"cmn-CN","cmn-TW":"cmn-TW",zh:"cmn","zh-CN":"cmn-CN","zh-TW":"cmn-TW",yue:"yue","yue-HK":"yue-HK","zh-HK":"yue-HK",wuu:"wuu","wuu-CN":"wuu-CN"},U=n=>{if(!n)return"";let e=n.toLowerCase().replace(/_/g,"-");if(/\w{2,3}-\w{2,3}/.test(e)){const[t,i]=e.split("-");e=`${t.toLowerCase()}-${i.toUpperCase()}`}return xe[e]||e},tn=async n=>{if(!n)return[];try{const e=U(n);try{const i=await ai(e);if(i?.voices?.length)return i.voices}catch(i){console.warn(`Failed to load voices for ${e}:`,i)}const[t]=F(e);if(t!==e)try{const i=await ai(t);if(i?.voices?.length)return i.voices}catch(i){console.warn(`Failed to load voices for base language ${t}:`,i)}return[]}catch(e){return console.error(`Error in getVoices for ${n}:`,e),[]}},nn=(n,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(n)||n.toUpperCase()}catch{return n.toUpperCase()}},li=n=>{if(!n)return"";try{const e=U(n),t=G[e];if(t?.testUtterance)return t.testUtterance;if(e in xe){const s=xe[e];if(s&&G[s]?.testUtterance)return G[s].testUtterance}const[i]=F(e);return i!==e&&G[i]?.testUtterance?G[i].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${n}:`,e),""}},Pt=n=>{if(!n)return"";try{const e=U(n),t=G[e];if(t?.defaultRegion)return`${e}-${t.defaultRegion}`;if(e in xe){const s=xe[e];if(s){const r=G[s];if(r?.defaultRegion)return`${s}-${r.defaultRegion}`}}const[i]=F(e);if(i!==e){const s=G[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${n}:`,e),""}},Ft=n=>{if(!n?.length)return[];const e=new Set,t=new Map,i=new Map;for(const[s,r]of n.entries()){if(!r)continue;const o=U(r),[a,l]=F(o);l&&(e.add(l),i.has(l)||i.set(l,s)),t.has(a)||t.set(a,new Set),l&&t.get(a).add(l)}return Array.from(t.entries()).map(([s,r])=>{const o=new Set(G[s]?.availableRegions||[]),a=Array.from(r),l=Array.from(e).filter(u=>o.has(u)&&!a.includes(u)),c=Array.from(new Set([...a,...l])).sort((u,h)=>{const d=i.get(u)??Number.MAX_SAFE_INTEGER,f=i.get(h)??Number.MAX_SAFE_INTEGER;return d-f});if(c.length===0){const u=Pt(s),[,h]=F(u);h&&c.push(h)}return{baseLang:s,regions:c}})},Ee=async n=>{const e=new Map;for(const i of n){if(i.source!=="json")continue;const[s]=F(i.language);e.has(s)||e.set(s,[]),e.get(s).push(i)}const t=new Map;for(const[i,s]of e.entries()){const r=new Map,o=await tn(i),a=new Map;o.forEach((l,c)=>{a.set(l.name.toLowerCase(),c),l.altNames?.forEach(u=>{a.set(u.toLowerCase(),c)})});for(const l of s){const c=l.name.toLowerCase(),u=a.get(c);u!==void 0&&r.set(l.name,u)}r.size>0&&t.set(i,r)}return t},Ko={veryLow:1,low:2,normal:3,high:4,veryHigh:5},mt=n=>n?Ko[n]??0:0,oe=(n,e,t,i)=>{const s=mt(n.quality),r=mt(e.quality);if(t&&i&&n.source==="json"&&e.source==="json"){const o=t.get(i);if(o){const a=o.get(n.name),l=o.get(e.name);if(a!==void 0&&l!==void 0)return a-l}}return r!==s?r-s:n.name.localeCompare(e.name)},It=(n,e)=>{const t=new Map(e.map(r=>[r.baseLang,r])),i=new Map,s=[];for(const r of n){const[o]=F(r.language);t.get(o)?(i.has(o)||i.set(o,[]),i.get(o).push(r)):s.push(r)}return{voicesByLang:i,otherLangVoices:s}},Os=(n,e,t,i)=>{const[,s]=F(n.language),[,r]=F(e.language),o=s&&t.regions.includes(s),a=r&&t.regions.includes(r);if(o&&a){const d=t.regions.indexOf(s),f=t.regions.indexOf(r);return d===f?oe(n,e,i,t.baseLang):d-f}if(o)return-1;if(a)return 1;const l=Pt(t.baseLang),[,c]=F(l),u=!!c&&s===c,h=!!c&&r===c;if(u&&!h)return-1;if(!u&&h)return 1;if(s&&r){const d=s.localeCompare(r);return d!==0?d:oe(n,e,i,t.baseLang)}return s?-1:r?1:oe(n,e,i,t.baseLang)},Go=async(n,e,t)=>{const i=t??await Ee(n);n.sort((s,r)=>Os(s,r,e,i))},Ts=(n,e,t)=>{const[i]=F(n.language),[s]=F(e.language),r=nn(i).toLowerCase(),o=nn(s).toLowerCase(),a=r.localeCompare(o);if(a!==0)return a;if(i===s){const l=Pt(i),[,c]=F(n.language),[,u]=F(e.language),h=l&&c===l.split("-")[1],d=l&&u===l.split("-")[1];if(h&&!d)return-1;if(!h&&d)return 1;if(c&&u){const f=c.localeCompare(u);if(f!==0)return f}return c&&!u?-1:!c&&u?1:oe(n,e,t,i)}return oe(n,e,t,i)},sn=async(n,e)=>{const t=e??await Ee(n);n.sort((i,s)=>Ts(i,s,t))},Xo=async(n,e)=>{if(!e?.length)return[];const t=Ft(n||[]),{voicesByLang:i,otherLangVoices:s}=It(e,t),r=await Ee(e),o=[];for(const a of t){const l=i.get(a.baseLang);l&&(await Go(l,a,r),o.push(...l))}return await sn(s,r),o.push(...s),o},Jo=async(n,e)=>{if(!e.length)return null;const[t]=Ft([n]),{voicesByLang:i,otherLangVoices:s}=It(e,[t]),r=i.get(t.baseLang),o=r?.length?r:s,a=await Ee(e),l=r?.length?(c,u)=>Os(c,u,t,a):(c,u)=>Ts(c,u,a);return o.reduce((c,u)=>l(u,c)<0?u:c)},Yo=[{name:"Albert",nativeID:["com.apple.speech.synthesis.voice.Albert"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bad News",nativeID:["com.apple.speech.synthesis.voice.BadNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Mauvaises nouvelles","Malas noticias","Brutte notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bahh",nativeID:["com.apple.speech.synthesis.voice.Bahh"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bells",nativeID:["com.apple.speech.synthesis.voice.Bells"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Cloches","Campanas","Campane"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Boing",nativeID:["com.apple.speech.synthesis.voice.Boing"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Bubbles",nativeID:["com.apple.speech.synthesis.voice.Bubbles"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bulles","Burbujas","Bollicine"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Cellos",nativeID:["com.apple.speech.synthesis.voice.Cellos"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Violoncelles","Violonchelos","Violoncelli"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Good News",nativeID:["com.apple.speech.synthesis.voice.GoodNews"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bonnes nouvelles","Buenas noticias","Buone notizie"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jester",nativeID:["com.apple.speech.synthesis.voice.Hysterical"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Bouffon","Bufón","Giullare"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Organ",nativeID:["com.apple.speech.synthesis.voice.Organ"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Orgue","Órgano","Organo"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Superstar",nativeID:["com.apple.speech.synthesis.voice.Princess"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Superestrella"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Trinoids",nativeID:["com.apple.speech.synthesis.voice.Trinoids"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Trinoïdes"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Whisper",nativeID:["com.apple.speech.synthesis.voice.Whisper"],note:"This novelty voice is part of a pack preloaded by Apple.",altNames:["Murmure","Susurro","Sussurro"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Wobble",nativeID:["com.apple.speech.synthesis.voice.Deranged"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Zarvox",nativeID:["com.apple.speech.synthesis.voice.Zarvox"],note:"This novelty voice is part of a pack preloaded by Apple.",os:["macOS","iOS","iPadOS"],preloaded:!0}],Qo={voices:Yo},Zo=[{name:"Eddy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Flo",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandma",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Grandpa",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Jacques",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Reed",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Rocko",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Sandy",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Shelley",localizedName:"apple",note:"Eloquence voices are preloaded by default on Apple devices.",language:"en-US",otherLanguages:["en-GB","de-DE","fr-FR","fr-CA","es-ES","es-MX","fi-FI","it-IT","ja-JP","ko-KR","pt-BR","zh-CN","zh-HK"],os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Fred",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Junior",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Kathy",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"Ralph",language:"en-US",os:["macOS","iOS","iPadOS"],preloaded:!0},{name:"eSpeak Arabic",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ar",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bulgarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bg",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Bengali",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"bn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Catalan",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ca",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Chinese (Mandarin, latin as English)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cmn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Czech",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"cs",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Danish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"da",os:["ChromeOS"],preloaded:!0},{name:"eSpeak German",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"de",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Greek",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"el",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Spanish (Spain)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"es",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Estonian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"et",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Finnish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"fi",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Gujarati",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"gu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Croatian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Hungarian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"hu",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Indonesian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"id",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Italian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"it",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Kannada",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"kn",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Korean",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ko",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Lithuanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lt",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Latvian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"lv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malayalm",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ml",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Marathi",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"mr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Malay",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ms",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Norwegian Bokmål",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"nb",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Polish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Portuguese (Brazil)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"pt-br",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Romanian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ro",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Russian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ru",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovak",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sk",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Slovenian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sl",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Serbian",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swedish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sv",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Swahili",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"sw",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Tamil",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"ta",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Telugu",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"te",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Turkish",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"tr",os:["ChromeOS"],preloaded:!0},{name:"eSpeak Vietnamese (Northern)",note:"eSpeak voices are preloaded by default on Chrome OS.",language:"vi",os:["ChromeOS"],preloaded:!0}],ea={voices:Zo},ta=Qo,na=ea,rn=(n,e)=>ta.voices.some(t=>n.includes(t.name)||e&&t.nativeID?.some(i=>e.includes(i))||t.altNames?.some(i=>n.includes(i))),on=(n,e)=>na.voices.some(t=>n.includes(t.name))||e==="veryLow",ci=n=>n?.length?n.filter(e=>!(e.isNovelty||rn(e.name,e.voiceURI))):[],ui=n=>n?.length?n.filter(e=>!on(e.name,e.quality)):[],ia={ar:{normal:"محسن",high:"استثنائي"},ca:{normal:"millorada",high:"prèmium"},"cmn-CN":{normal:"优化音质",high:"高音质"},"cmn-TW":{normal:"增強音質",high:"高音質"},cs:{normal:"vylepšená verze",high:"prémiový"},da:{normal:"forbedret",high:"høj kvalitet"},de:{normal:"erweitert",high:"premium"},el:{normal:"βελτιωμένη",high:"υψηλής ποιότητας"},en:{normal:"Enhanced",high:"Premium"},es:{normal:"mejorada",high:"premium"},fi:{normal:"parannettu",high:"korkealaatuinen"},fr:{normal:"premium",high:"de qualité"},he:{normal:"משופר",high:"פרימיום"},hi:{normal:"बेहतर",high:"प्रीमियम"},hr:{normal:"poboljšani",high:"vrhunski"},hu:{normal:"továbbfejlesztett",high:"prémium"},id:{normal:"Ditingkatkan",high:"Premium"},it:{normal:"ottimizzata",high:"premium"},ja:{normal:"拡張",high:"プレミアム"},ko:{normal:"고품질",high:"프리미엄"},ms:{normal:"Dipertingkat",high:"Premium"},nb:{normal:"forbedret",high:"premium"},nl:{normal:"verbeterd",high:"premium"},pl:{normal:"rozszerzony",high:"premium"},pt:{normal:"melhorada",high:"premium"},ro:{normal:"îmbunătățită",high:"premium"},ru:{normal:"улучшенный",high:"высшее качество"},sk:{normal:"vylepšený",high:"prémiový"},sl:{normal:"izboljšano",high:"prvovrsten"},sv:{normal:"förbättrad",high:"premium"},th:{normal:"คุณภาพสูง",high:"คุณภาพสูง"},tr:{normal:"Geliştirilmiş",high:"Yüksek Kaliteli"},uk:{normal:"вдосконалений",high:"високої якості"},vi:{normal:"Nâng cao",high:"Cao cấp"}},sa={quality:ia},an={apple:sa.quality},ra=(n,e,t)=>{if(!n)return;const i=Array.isArray(t)?t:t?[t]:[];for(const s of i)if(s&&an[s]){const r=an[s],o=F(e)[0],a=r[e]||r[o];if(a){const l=n.toLowerCase(),{normal:c,high:u}=a;if(u&&l.includes(u.toLowerCase()))return"high";if(c&&l.includes(c.toLowerCase()))return"normal"}}},oa=(n,e)=>{const t=an[e];if(t)for(const[i,{high:s,normal:r}]of Object.entries(t)){const o=s&&n.some(l=>l.includes(s)),a=r&&n.some(l=>l.includes(r));if(o&&a)return i}},aa={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},hi=n=>{if(!n)return;const t=n.toLowerCase().split(/[._-]/);for(const i of Object.values(aa))if(i.values.some(s=>t.includes(s)))return i.quality};function la(n,e){if(n.name===n.originalName)return n;if(e.name===e.originalName)return e;const t=[n.originalName,...n.altNames||[]],i=[e.originalName,...e.altNames||[]],s=t.findIndex(o=>i.includes(o)),r=i.findIndex(o=>t.includes(o));return s===-1&&r===-1||s!==-1&&(r===-1||s<=r)?n:e}function ca(n,e){if(!n.altNames&&!e.altNames)return!1;const t=n.originalName,i=e.originalName,s=n.altNames||[],r=e.altNames||[];return r.includes(t)||s.includes(i)?!0:s.filter(a=>r.includes(a)).length>0}class T{static instance;static initializationPromise=null;systemLocale;voices=[];browserVoices=[];isInitialized=!1;scopedLanguages=null;broadenPromises=new Map;constructor(){if(typeof window>"u"||!window.speechSynthesis)throw new Error("Web Speech API is not available in this environment");this.systemLocale=navigator.languages?.[0]?.split("-")[0]||"en"}static async initialize(e){if(T.instance?.isInitialized){const t=T.instance;return e?.languages&&e.languages.length>0&&await t.broadenLanguages(e.languages),t}return T.initializationPromise||(T.initializationPromise=(async()=>{try{const t=new T;T.instance=t,t.browserVoices=await t.getBrowserVoices(e?.maxTimeout,e?.interval),t.updateSystemLocale(t.browserVoices);let i=t.browserVoices;return e?.languages&&e.languages.length>0?(i=t.filterBrowserVoicesByLanguages(t.browserVoices,e.languages),t.scopedLanguages=T.toBaseLangSet(e.languages)):t.scopedLanguages=null,t.voices=await t.parseToReadiumSpeechVoices(i),t.isInitialized=!0,t}catch(t){throw T.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",t),t}})()),T.initializationPromise}filterBrowserVoicesByLanguages(e,t){if(!t?.length)return e;const i=T.toBaseLangSet(t);return e.filter(s=>{if(!s?.lang)return!1;const r=U(s.lang),[o]=T.extractLangRegionFromBCP47(r);return i.has(o)})}static toBaseLangSet(e){return new Set(e.map(t=>{const i=U(t),[s]=T.extractLangRegionFromBCP47(i);return s}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const i=[...T.toBaseLangSet(e)].filter(a=>!this.scopedLanguages.has(a));if(i.length===0)return;const s=i.filter(a=>this.broadenPromises.has(a)),r=i.filter(a=>!this.broadenPromises.has(a));let o;r.length>0&&(o=(async()=>{const a=this.filterBrowserVoicesByLanguages(this.browserVoices,r),l=await this.parseToReadiumSpeechVoices(a);this.voices=[...this.voices,...l],r.forEach(c=>this.scopedLanguages.add(c)),r.forEach(c=>this.broadenPromises.delete(c))})(),r.forEach(a=>this.broadenPromises.set(a,o))),await Promise.all([...o?[o]:[],...s.map(a=>this.broadenPromises.get(a))])}static extractLangRegionFromBCP47(e){return F(e)}cleanVoiceName(e){return e?e.replace(/\s*\([^)]*\)/g,"").replace(/[^\p{L}\p{N}\s-]/gu,"").replace(/\s+/g," ").trim():""}normalizeVoiceName(e){return this.cleanVoiceName(e.toLowerCase())}countVoiceDuplicates(e){const t=new Map;for(const i of e){if(!i?.name||!i?.lang)continue;const s=`${i.lang.toLowerCase()}_${this.normalizeVoiceName(i.name)}`;t.set(s,(t.get(s)||0)+1)}return t}updateSystemLocale(e){if(!e?.length)return;const t=e.map(s=>s.name),i=oa(t,"apple");i&&(this.systemLocale=i)}inferVoiceQuality(e,t,i){const s=e.voiceURI?hi(e.voiceURI):void 0;if(s)return s;if(t?.nativeID&&Array.isArray(t.nativeID))for(const r of t.nativeID){const o=hi(r);if(o)return o}if(t?.localizedName&&e.voiceURI&&e.lang){const r=ra(e.voiceURI,this.systemLocale,t.localizedName);if(r)return r}if(t?.quality&&t.quality.length>0){const r=Math.min(i-1,t.quality.length-1),o=t.quality[r];if(o)return o}return null}findMatchingJsonVoice(e,t){return e.find(i=>this.normalizeVoiceName(i.name)===t||i.altNames?.some(s=>this.normalizeVoiceName(s)===t))}removeDuplicates(e){const t=new Map;for(const i of e){const s=`${i.language.toLowerCase()}_${this.normalizeVoiceName(i.name)}`,r=t.get(s);if(!r)t.set(s,i);else if(ca(i,r)){const o=la(i,r);t.set(s,o)}else{const o=mt(r.quality);mt(i.quality)>=o&&t.set(s,i)}}return Array.from(t.values())}getTestUtterance(e){if(!e)return"";const t=li(e);if(t)return t;const[i]=T.extractLangRegionFromBCP47(e);if(i&&i!==e){const s=li(i);if(s)return s}return""}getVoices(e={}){if(!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");return this.filterVoices(e,[...this.voices])}getLanguages(e,t,i){if(!i&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const s=i??this.voices,r=t?this.filterVoices(t,s):s,o=[],a=new Set;for(const l of r){const u=U(l.language).split("-")[0];if(!a.has(u)){const h=nn(u,e),d=r.filter(f=>U(f.language).split("-")[0]===u).length;o.push({code:u,label:h,count:d}),a.add(u)}}return i?o:o.sort((l,c)=>l.label.localeCompare(c.label))}getRegions(e,t,i){if(!i&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const s=i??this.voices,r=t?this.filterVoices(t,s):s,o=[],a=new Set,l=new Map;for(const c of r){const[,u]=T.extractLangRegionFromBCP47(c.language);u&&l.set(u,(l.get(u)||0)+1)}for(const c of r){const[,u]=T.extractLangRegionFromBCP47(c.language);if(u&&!a.has(u)){let h=c.language;try{const d=e||navigator.language;h=new Intl.DisplayNames([d],{type:"region"}).of(u)||c.language}catch(d){console.warn(`Failed to get display name for region ${u}`,d)}o.push({code:u,label:h,count:l.get(u)||0}),a.add(u)}}return i?o:o.sort((c,u)=>c.label.localeCompare(u.label))}async getDefaultVoice(e,t){if(!e)return null;const i=Array.isArray(e)?e:[e];let s=t||this.getVoices({languages:i});return s.length?(s=await this.sortVoicesByRegions(i,s),s[0]):null}getBrowserVoices(e=1e4,t=10){const i=()=>window.speechSynthesis?.getVoices()||[];if(!window.speechSynthesis)return Promise.resolve([]);const s=i();return Array.isArray(s)&&s.length?Promise.resolve(s):new Promise((r,o)=>{let a=Math.floor(e/t),l=!1;const c=()=>{if(l)return;l=!0;const u=()=>{if(a<1)return r([]);--a;const h=i();if(Array.isArray(h)&&h.length)return r(h);setTimeout(u,t)};setTimeout(u,t)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const u=i();Array.isArray(u)&&u.length?r(u):c()}:c(),setTimeout(()=>r([]),e)})}async parseToReadiumSpeechVoices(e){const t=this.countVoiceDuplicates(e);return await Promise.all(e.filter(s=>s?.name&&s?.lang).map(async s=>{const r=U(s.lang),[o]=T.extractLangRegionFromBCP47(r),a=this.normalizeVoiceName(s.name),l=`${s.lang.toLowerCase()}_${a}`,c=t.get(l)||1;let u=await tn(r);(!u||u.length===0)&&(u=await tn(o));const h=this.findMatchingJsonVoice(u,a),d=this.inferVoiceQuality(s,h,c);return h?{...h,label:h.label??this.cleanVoiceName(s.name),source:"json",originalName:s.name,language:h.language??r,voiceURI:s.voiceURI,quality:d,isDefault:s.default||!1,offlineAvailability:s.localService||!1,isNovelty:rn(s.name,s.voiceURI),isLowQuality:on(s.name,d)}:{source:"browser",label:this.cleanVoiceName(s.name),name:s.name,originalName:s.name,language:r,voiceURI:s.voiceURI,quality:d,isDefault:s.default||!1,offlineAvailability:s.localService||!1,isNovelty:rn(s.name,s.voiceURI),isLowQuality:on(s.name,d)}}))}convertToSpeechSynthesisVoice(e){if(e)return this.browserVoices.find(t=>t.voiceURI===e.voiceURI||t.name===e.originalName||this.normalizeVoiceName(t.name)===this.normalizeVoiceName(e.name))}filterVoices(e,t){let i=t?[...t]:[...this.voices];const s={excludeNovelty:!0,excludeVeryLowQuality:!0,removeDuplicates:!0,...e};if(s.languages){const r=Array.isArray(s.languages)?s.languages:[s.languages];i=i.filter(o=>r.some(a=>{const l=a.toLowerCase(),c=o.language?.toLowerCase(),u=o.altLanguage?.toLowerCase();if(c===l||u===l)return!0;const[h]=l.split("-");return c&&c.startsWith(h)||u&&u.startsWith(h)}))}if(s.source&&(i=i.filter(r=>r.source===s.source)),s.gender&&(i=i.filter(r=>r.gender===s.gender)),s.quality){const r=Array.isArray(s.quality)?s.quality:[s.quality];i=i.filter(o=>o.quality&&r.includes(o.quality))}return s.offlineOnly&&(i=i.filter(r=>r.offlineAvailability===!0)),s.provider&&(i=i.filter(r=>r.provider?.toLowerCase()===s.provider?.toLowerCase())),s.excludeNovelty&&(i=ci(i)),s.excludeVeryLowQuality&&(i=ui(i)),s.removeDuplicates&&(i=this.removeDuplicates(i)),i}filterOutNoveltyVoices(e){const t=e??this.voices;return ci(t)}filterOutVeryLowQualityVoices(e){const t=e??this.voices;return ui(t)}async sortVoicesByQuality(e){const t=e||this.voices;if(!t?.length)return[];const i=await Ee(t);return[...t].sort((s,r)=>oe(s,r,i))}static async sortByDefaultRegion(e,t){const i=await Ee(e),s=Pt(t);e.sort((r,o)=>{const[,a]=T.extractLangRegionFromBCP47(r.language),[,l]=T.extractLangRegionFromBCP47(o.language),c=s&&a===s.split("-")[1],u=s&&l===s.split("-")[1];return c&&!u?-1:!c&&u?1:oe(r,o,i,t)})}async sortVoicesByLanguages(e,t){const i=t||this.voices;if(!i?.length)return[];if(!e?.length){const l=[...i];return await sn(l),l}const s=Ft(e),{voicesByLang:r,otherLangVoices:o}=It(i,s),a=[];for(const l of s){const c=r.get(l.baseLang);c&&(await T.sortByDefaultRegion(c,l.baseLang),a.push(...c))}return await sn(o),a.push(...o),a}async sortVoicesByRegions(e,t){return Xo(e,t||this.voices)}groupVoices(e,t){const i={},s=t||this.voices;for(const r of s){let o="Unknown";switch(e){case"languages":o=T.extractLangRegionFromBCP47(r.language)[0];break;case"gender":o=r.gender||"unknown";break;case"quality":o=r.quality||"unknown";break;case"region":const[,a]=T.extractLangRegionFromBCP47(r.language);o=a||"unknown";break}i[o]||(i[o]=[]),i[o].push(r)}return i}}const ua=["webKit","moz","ms","o"],ha=["boundary","end","error","mark","pause","resume","start"],da=n=>`${n.charAt(0).toUpperCase()}${n.slice(1)}`,Ie=(n={},e)=>Object.hasOwnProperty.call(n,e)||e in n||!!n[e],fa=n=>typeof window<"u"&&n in window,ga=n=>{const e=da(n),t=ua.map(s=>`${s}${e}`),i=[n,e].concat(t).find(fa);return i&&typeof window<"u"?window[i]:void 0},pa=()=>{const n={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(t=>{n[t]=ga(t)}),n.onvoiceschanged=Ie(n.speechSynthesis,"onvoiceschanged"),n.speechSynthesisSpeaking=Ie(n.speechSynthesis,"speaking"),n.speechSynthesisPaused=Ie(n.speechSynthesis,"paused");const e=n.speechSynthesisUtterance?Ie(n.speechSynthesisUtterance,"prototype"):!1;return ha.forEach(t=>{const i=`on${t}`;n[i]=e&&n.speechSynthesisUtterance?Ie(n.speechSynthesisUtterance.prototype,i):!1}),n},ma=()=>{const e=typeof window<"u"&&(window.navigator||{}).userAgent||"",t=()=>/android/i.test(e),i=()=>/kaios/i.test(e),s=()=>typeof window.InstallTrigger<"u"?!0:/firefox/i.test(e),r=()=>typeof window.GestureEvent<"u"||/safari/i.test(e);return{isAndroid:t(),isFirefox:s()||i(),isSafari:r(),isKaiOS:i()}};let Lt=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>{const i=this.listeners.get(e);if(i){const s=i.indexOf(t);s>-1&&i.splice(s,1)}}}emit(e,t){const i=this.listeners.get(e);i&&[...i].forEach(s=>{try{s(t)}catch(r){console.error(`Error in "${String(e)}" listener:`,r)}})}clear(){this.listeners.clear()}};const dt=(n,e)=>Math.min(Math.max(n,0),Math.max(e-1,0));function ae(n,e,t,i){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):i}const ve="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",ln="\\p{Ps}\\p{Pi}¿¡",Sa=new RegExp(`^[${ve}]`,"u"),ya=new RegExp(`^[${ln}]`,"u"),va=new RegExp("^\\p{P}$","u");function Oe(n){return Sa.test(n)}function ba(n){return ya.test(n)}function wa(n){return va.test(n)}function Ns(n){return n.replace(/[<>]/g,"")}function xa(n){return n.replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>String.fromCodePoint(parseInt(t,16)))}function Je(n){return n.plain===""&&n.ssml===""&&n.language===""}function Ea(n){if(!n||Je(n))return;if(n.ssml===""&&n.language==="")return n.plain;const e={language:n.language};return n.plain!==""&&(e.plain=n.plain),n.ssml!==""&&(e.ssml=n.ssml),e}function Ca(n,e){if(n.lang!==e.lang||n.tag!==e.tag)return!1;const t=Object.entries(n.attrs??{}),i=Object.entries(e.attrs??{});return t.length!==i.length?!1:t.every(([s,r])=>e.attrs?.[s]===r)}const X=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),jt=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ka=/[\u00A0\u2007\u202F]/;function Ra(n){return ka.test(n)}function Ce(n,e){let t="",i=!1,s=!1;for(const r of n)if(Ra(r))t+=r,i=!1,s=!0;else if(/\s/.test(r)){if(e&&!s||i)continue;t+=" ",i=!0}else r!==""&&r!==""&&(t+=r,i=!1,s=!0);return t}const Aa=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function Oa(n){return n.replace(Aa,(t,i,s)=>{const r=s.slice(i+t.length);return r.length===0||Oe(r)?"":" "}).replace(/ {2,}/g," ").trim()}function Ta(n){return n.includes("<")}function Pn(n){if(n===void 0)return;if(typeof n=="string")return{plain:n};const e={language:n.language};if(n.ssml){const t=Oa(n.ssml);Ta(t)&&(e.ssml=t)}return n.plain&&(e.plain=n.plain),e.plain||e.ssml?e:void 0}function le(n){return Ds(n).plain}function Ds(n){let e="";const t=[];let i=!1,s=0;for(;s<n.length;){const a=n[s];if(a==="<"){const c=n.indexOf(">",s),u=c===-1?"":n.slice(c+1);s=c===-1?n.length:c+1,!i&&e.length>0&&u.length>0&&!Oe(u)&&(e+=" ",t.push(s),i=!0);continue}const l=n.startsWith("<",s)?"<":n.startsWith(">",s)?">":n.startsWith("&",s)?"&":void 0;if(l){e+=l,t.push(s),s+=l==="&"?5:4,i=!1;continue}if(a===" "){i||(e+=a,t.push(s),i=!0),s++;continue}e+=a,t.push(s),i=!1,s++}let r=0;for(;r<e.length&&/\s/.test(e[r]);)r++;let o=e.length;for(;o>r&&/\s/.test(e[o-1]);)o--;return{plain:e.slice(r,o),map:t.slice(r,o)}}function di(n,e){let t=0,i=n.length;for(;t<i;){const s=t+i>>1;n[s]<e?t=s+1:i=s}return t}const fi=new WeakMap;function Na(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Da(n){const e=Na(n),t=/\w/.test(n[0])?"(?<!\\w)":"",i=/\w/.test(n[n.length-1])?"(?!\\w)":"";return`${t}${e}${i}`}function Pa(n,e){if(typeof e=="string")return{regex:new RegExp(Da(n),"g"),replace:e};const t=e.pattern.flags.includes("g")?e.pattern.flags:`${e.pattern.flags}g`;return{regex:new RegExp(e.pattern.source,t),replace:e.replace}}function Fa(n){let e=fi.get(n);return e||(e=Object.entries(n).map(([t,i])=>Pa(t,i)),fi.set(n,e)),e}function Ps(n,e){const t=[];for(const r of Fa(e))for(const o of n.matchAll(r.regex)){const a=o.index,l=typeof r.replace=="string"?r.replace:r.replace(...o);t.push({start:a,end:a+o[0].length,replacement:l})}t.sort((r,o)=>r.start-o.start);const i=[];let s=0;for(const r of t)r.start<s||(i.push(r),s=r.end);return i}function Ia(n,e){let t="";const i=[];let s=0;for(const r of Ps(n,e)){for(;s<r.start;)t+=n[s],i.push(s),s++;for(let o=0;o<r.replacement.length;o++)t+=r.replacement[o],i.push(r.start);s=r.end}for(;s<n.length;)t+=n[s],i.push(s),s++;return{text:t,map:i}}function gi(n,e){return n.length?e<=0?n[0]:e>=n.length?n[n.length-1]+1:n[e]:e}const La=/<([a-zA-Z][\w-]*)([^>]*)>([\s\S]*?)<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function pi(n){return n.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Fs(n){const e=[];for(const t of n.matchAll(La))t[1]!==void 0?e.push({kind:"paired",raw:t[0],tag:t[1],attrs:t[2],innerText:pi(t[3])}):t[0][0]==="<"?e.push({kind:"selfClosing",raw:t[0]}):e.push({kind:"text",raw:t[0],text:pi(t[0])});return e}function $a(n,e){const t=Fs(n);let i="",s=!1;const r=[],o=t.map(()=>[]);t.forEach((b,C)=>{if(b.kind==="selfClosing")return;const R=b.kind==="paired"?b.innerText:b.text;if(!s&&i.length>0&&R.length>0&&!Oe(R)&&!/^\s/.test(R)){const N=i.length;i+=" ",o[C].push(r.length),r.push({start:N,end:N+1,atomIndex:-1}),s=!0}const A=i.length;i+=R,o[C].push(r.length),r.push({start:A,end:i.length,atomIndex:C}),R.length>0&&(s=/\s$/.test(R))});const a=Ps(i,e);let l="",c="";const u=[];let h=-2,d="",f=0;const g=()=>{if(h>=0){const b=t[h];l+=b.kind==="paired"?`<${b.tag}${b.attrs}>${d}</${b.tag}>`:d}d="",h=-2};for(let b=0;b<t.length;b++){const C=t[b];if(C.kind==="selfClosing"){g(),l+=C.raw;continue}for(const R of o[b]){const A=r[R];let N=A.start;for(;N<A.end;){const O=f<a.length?a[f]:void 0;if(O&&O.start<=N&&O.end>N){const P=O.start===N,$=O.end>A.end;if(P){c+=O.replacement;for(let De=0;De<O.replacement.length;De++)u.push(O.start);A.atomIndex===-1||$?(g(),l+=X(O.replacement)):(h!==A.atomIndex&&(g(),h=A.atomIndex),d+=X(O.replacement))}N=Math.min(O.end,A.end),O.end<=A.end&&f++;continue}const tt=O?Math.min(O.start,A.end):A.end,he=i.slice(N,tt);c+=he;for(let P=0;P<he.length;P++)u.push(N+P);A.atomIndex===-1?(g(),l+=X(he)):(h!==A.atomIndex&&(g(),h=A.atomIndex),d+=X(he)),N=tt}}}g();let p=0;for(;p<i.length&&/\s/.test(i[p]);)p++;let m=i.length;for(;m>p&&/\s/.test(i[m-1]);)m--;let v=0;for(;v<c.length&&/\s/.test(c[v]);)v++;let w=c.length;for(;w>v&&/\s/.test(c[w-1]);)w--;const S=i.slice(p,m),y=u.slice(v,w).map(b=>Math.min(Math.max(b-p,0),Math.max(S.length-1,0)));return{ssml:l,plain:S,map:y}}const Is=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function Ls(n){return new RegExp(Is).test(n)}function mi(n){return n.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/ {2,}/g," ")}const Ma=new RegExp(`\\s+|[${ln}]+|[${ve}]+|[^\\s${ln}${ve}]+`,"gu");function Ht(n){const e=[];for(const[t]of n.matchAll(Ma))/^\s/.test(t)?e.push({kind:"space"}):ba(t)?e.push({kind:"open",text:t}):Oe(t)?e.push({kind:"close",text:t}):e.push({kind:"word",text:t});return e}function _a(n){let e="",t=!1;for(const i of n){if(i.kind==="space"){e&&(t=!0);continue}t&&(e+=" "),e+=i.text,t=!1}return e}function Ba(n){let e=n.length;for(;e>0&&(n[e-1].kind==="space"||n[e-1].kind==="open");)e--;return n.slice(e).some(t=>t.kind==="open")?n.splice(e):[]}function Ua(n){let e=0;for(;e<n.length&&(n[e].kind==="space"||n[e].kind==="close");)e++;return n.slice(0,e).some(t=>t.kind==="close")?n.splice(0,e):[]}function $s(n,e){const t=[];let i=0;for(const o of n.matchAll(Is))t.push({tokens:Ht(mi(n.slice(i,o.index))),language:e,tagged:!1}),t.push({tokens:Ht(le(o[2])),language:o[1],tagged:!0}),i=o.index+o[0].length;t.push({tokens:Ht(mi(n.slice(i))),language:e,tagged:!1});for(let o=0;o<t.length-1;o++)!t[o].tagged&&t[o+1].tagged?t[o+1].tokens.unshift(...Ba(t[o].tokens)):t[o].tagged&&!t[o+1].tagged&&t[o].tokens.push(...Ua(t[o+1].tokens));const s=[];let r=0;for(const o of t){const a=_a(o.tokens);a&&(s.push({plain:a,language:o.language,start:r,end:r+a.length}),r+=a.length)}return s}const Ms=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function za(n){return new RegExp(Ms).test(n)}function Va(n){const e=[];let t=0;for(const s of n.matchAll(Ms)){const r=n.slice(t,s.index).trim();r&&e.push({ssml:r}),e.push({placeholderId:s[1]}),t=s.index+s[0].length}const i=n.slice(t).trim();return i&&e.push({ssml:i}),e}class cn{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Lt;voiceManager=null;voices=[];defaultVoice=null;speakInContentLanguage=!1;languageVoiceCache=new Map;warmingLanguages=new Map;speakGeneration=0;resumeInfinityTimer;isSpeakingInternal=!1;restartPending=!1;isPausedInternal=!1;isAndroidPaused=!1;pausedAtUtteranceIndex=null;initialized=!1;maxLengthExceeded="warn";utterancesBeingCancelled=!1;rate=1;pitch=1;volume=1;features;patches;constructor(){if(this.features=pa(),this.patches=ma(),!this.features.speechSynthesis||!this.features.speechSynthesisUtterance)throw new Error("Web Speech API is not available in this environment");this.speechSynthesis=this.features.speechSynthesis,this.speechSynthesisUtterance=this.features.speechSynthesisUtterance}shouldUseResumeInfinity(){const e=this.currentVoice,t=!!(e?.name&&typeof e.name=="string"&&e.name.toLocaleLowerCase().includes("(natural)"));return this.patches.isAndroid!==!0&&!this.patches.isFirefox&&!this.patches.isSafari&&!t}createUtterance(e){return new this.speechSynthesisUtterance(e)}async initialize(e={}){const{languages:t,maxTimeout:i,interval:s,maxLengthExceeded:r="warn"}=e;if(this.initialized)return!1;this.maxLengthExceeded=r;try{this.voiceManager=await T.initialize({languages:t,maxTimeout:i,interval:s}),this.voices=this.voiceManager.getVoices();const o=t||[...navigator.languages||["en"]];return this.defaultVoice=await this.voiceManager.getDefaultVoice(o,this.voices),this.initialized=!0,!0}catch(o){return console.error("Failed to initialize WebSpeechEngine:",o),this.initialized=!1,!1}}validateText(e){if(new TextEncoder().encode(e).length>4096){const i="Text exceeds max length of 4096 bytes, which may not work with some voices.";switch(this.maxLengthExceeded){case"none":break;case"error":throw new Error(`WebSpeechEngine: ${i}`);default:console.warn(`WebSpeechEngine: ${i}`)}}}getCurrentVoiceForUtterance(e){return e&&typeof e=="object"?e:typeof e=="string"?this.voices.find(t=>t.name===e||t.language===e)||null:this.currentVoice||this.defaultVoice}voiceMatchesLanguage(e,t){const[i,s]=F(t),[r,o]=F(e.language);return r===i&&(!s||o===s)}voiceForUtteranceSync(e){const t=this.getCurrentVoiceForUtterance(this.currentVoice);if(!this.speakInContentLanguage||!e.language)return t;const i=U(e.language);if(t&&this.voiceMatchesLanguage(t,i))return t;if(this.languageVoiceCache.has(i))return this.languageVoiceCache.get(i)??t}async voiceForUtterance(e){const t=this.voiceForUtteranceSync(e);return t!==void 0?t:(await this.warmLanguageVoiceCache([e]),this.voiceForUtteranceSync(e)??this.getCurrentVoiceForUtterance(this.currentVoice))}async warmLanguageVoiceCache(e){if(!this.speakInContentLanguage||!this.voiceManager)return;const t=new Set(e.map(o=>o.language).filter(o=>!!o).map(o=>U(o)).filter(o=>!this.languageVoiceCache.has(o))),i=[...t].filter(o=>this.warmingLanguages.has(o)),r=[...t].filter(o=>!this.warmingLanguages.has(o)).map(o=>{const a=(async()=>{await T.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const l=this.voices.filter(h=>this.voiceMatchesLanguage(h,o)),u=(await this.voiceManager.sortVoicesByQuality(l))[0]??null;this.languageVoiceCache.set(o,u),u||this.emitEvent({type:"languagefallback",detail:{language:o,reason:"no-matching-voice"}})})();return this.warmingLanguages.set(o,a.finally(()=>this.warmingLanguages.delete(o))),this.warmingLanguages.get(o)});await Promise.all([...r,...i.map(o=>this.warmingLanguages.get(o))])}getCurrentVoice(){return this.currentVoice}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,e&&this.warmLanguageVoiceCache(this.currentUtterances)}getSpeakInContentLanguage(){return this.speakInContentLanguage}toPlainText(e){return e.map(t=>({...t,plain:t.plain??(t.ssml?le(xa(t.ssml)):"")}))}loadUtterances(e,t){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=dt(t??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="ready",this.emitEvent({type:"ready"})}async setVoice(e){const t=this.currentVoice;if(typeof e=="string"){const i=this.voices.find(s=>s.name===e||s.language===e);i?(this.currentVoice=i,t&&t.name!==i.name&&(this.currentUtteranceIndex=0)):console.warn(`Voice "${e}" not found`)}else this.currentVoice=e,t&&t.name!==e.name&&(this.currentUtteranceIndex=0);this.voiceManager&&this.defaultVoice&&this.currentVoice&&this.currentVoice.language!==this.defaultVoice.language&&(this.defaultVoice=await this.voiceManager.getDefaultVoice([this.currentVoice.language],this.voices))}async getAvailableVoices(){if(this.voices.length>0)return this.voices;try{return await this.initialize(),this.voices}catch{return[]}}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.cancelCurrentSpeech();const t=++this.speakGeneration;this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length&&(this.currentUtteranceIndex=0),this.speakCurrentUtterance(t)}cancelCurrentSpeech(){this.patches.isFirefox&&this.speechSynthesis.speaking&&(this.utterancesBeingCancelled=!0,setTimeout(()=>{this.utterancesBeingCancelled=!1},100)),this.speechSynthesis.cancel()}async speakCurrentUtterance(e){if(this.currentUtteranceIndex>=this.currentUtterances.length){this.setState("idle"),this.emitEvent({type:"end"});return}const t=this.currentUtterances[this.currentUtteranceIndex],i=t.plain??"";this.validateText(i);const s=this.createUtterance(Ns(i)),r=await this.voiceForUtterance(t);if(e===this.speakGeneration){if(r&&this.voiceManager){const o=this.voiceManager.convertToSpeechSynthesisVoice(r);o&&(s.voice=o,s.lang=o.lang)}t.language&&(s.lang=t.language),s.rate=this.rate,s.pitch=this.pitch,s.volume=this.volume,s.onstart=()=>{this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.patches.isAndroid&&this.isAndroidPaused&&(this.isAndroidPaused=!1),this.shouldUseResumeInfinity()&&this.startResumeInfinity(s)},s.onend=()=>{if(this.utterancesBeingCancelled){this.utterancesBeingCancelled=!1;return}this.playbackState!=="idle"&&(this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))},s.onerror=o=>{if(o.error==="interrupted"&&this.patches.isAndroid&&this.isAndroidPaused)return;this.isSpeakingInternal=!1,this.isPausedInternal=!1,this.stopResumeInfinity(),this.setState("idle"),["synthesis-unavailable","audio-hardware","voice-unavailable"].includes(o.error)&&(console.log("[ENGINE] fatal error detected, resetting index to 0"),this.currentUtteranceIndex=0),o.error==="interrupted"||o.error==="canceled"?this.emitEvent({type:"stop"}):this.emitEvent({type:"error",detail:{error:o.error,message:`Speech synthesis error: ${o.error}`}})},s.onpause=()=>{this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.emitEvent({type:"pause"})},s.onresume=()=>{this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.emitEvent({type:"resume"})},s.onboundary=o=>{e===this.speakGeneration&&this.emitEvent({type:"boundary",detail:{charIndex:o.charIndex,charLength:o.charLength,elapsedTime:o.elapsedTime,name:o.name}})},s.onmark=o=>{this.emitEvent({type:"mark",detail:{name:o.name}})},this.speechSynthesis.speak(s)}}startResumeInfinity(e){this.shouldUseResumeInfinity()&&(this.resumeInfinityTimer=window.setTimeout(()=>{if(e){const{paused:i,speaking:s}=this.speechSynthesis,r=s||this.isSpeakingInternal,o=i||this.isPausedInternal;r&&!o&&(this.speechSynthesis.pause(),this.speechSynthesis.resume())}this.startResumeInfinity(e)},5e3))}stopResumeInfinity(){this.resumeInfinityTimer&&(clearTimeout(this.resumeInfinityTimer),this.resumeInfinityTimer=void 0)}pause(){this.playbackState==="playing"&&(this.pausedAtUtteranceIndex=this.currentUtteranceIndex,this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.setState("paused"),this.patches.isAndroid?(this.isAndroidPaused=!0,this.speechSynthesis.cancel(),this.emitEvent({type:"pause"})):this.speechSynthesis.pause())}resume(){this.playbackState==="paused"&&this.currentUtteranceIndex<this.currentUtterances.length&&(this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.setState("playing"),this.patches.isAndroid||this.pausedAtUtteranceIndex!==this.currentUtteranceIndex?(this.emitEvent({type:"resume"}),this.speak(this.currentUtteranceIndex)):this.speechSynthesis.resume(),this.pausedAtUtteranceIndex=null)}stop(){this.cancelCurrentSpeech(),this.speakGeneration++,this.currentUtteranceIndex=0,this.patches.isAndroid&&(this.isAndroidPaused=!1),this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const t=ae(e,.1,10,this.rate);t!==this.rate&&(this.rate=t,this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const t=ae(e,0,2,this.pitch);t!==this.pitch&&(this.pitch=t,this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const t=ae(e,0,1,this.volume);t!==this.volume&&(this.volume=t,this.scheduleRestartIfSpeaking())}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,t){if(e<0||e>=this.currentUtterances.length){t?.(!1);return}e!==this.currentUtteranceIndex&&(!this.isPausedInternal&&this.isSpeakingInternal&&this.cancelCurrentSpeech(),this.currentUtteranceIndex=e,t?.(!0))}getUtteranceCount(){return this.currentUtterances.length}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const t=this.playbackState;if(this.playbackState=e,t!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),this.stopResumeInfinity(),this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[],this.defaultVoice=null,this.languageVoiceCache.clear(),this.warmingLanguages.clear(),this.initialized=!1}}class ja{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new cn,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const t=new cn;return await t.initialize(),e&&await t.setVoice(e),t}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}function _s(n,e){const t=[];let i=-1,s=-1;const r=()=>{i!==-1&&(t.push({text:Ha(n,i,s),offset:n[i].offset}),i=-1,s=-1)};for(let o=0;o<n.length;o++){const a=n[o];if(a.text.length>e){r(),t.push({text:a.text,offset:a.offset});continue}const l=a.offset+a.text.length,c=i===-1?a.text.length:l-n[i].offset;i!==-1&&c>e&&r(),i===-1&&(i=o),s=o}return r(),t}function Ha(n,e,t){const i=n[e],s=n[t];return i===s?i.text:n.slice(e,t+1).map(r=>r.text).join("")}const Bs=new RegExp(`[^${ve}]*[${ve}]+\\s*|[^${ve}]+$`,"gu"),qa=/\S+\s*|\s+/g;function Fn(n,e,t){const i=[];for(const s of n.matchAll(t))s[0].length!==0&&i.push({text:s[0],offset:e+s.index,atomic:!1});return i}function In(n,e){if(n.text.length<=e||n.atomic)return[n];const t=Fn(n.text,n.offset,qa);if(t.length>1)return t.flatMap(o=>In(o,e));const i=[];let s=n.offset,r="";for(const o of n.text)r.length>0&&r.length+o.length>e&&(i.push({text:r,offset:s,atomic:!1}),s+=r.length,r=""),r+=o;return r.length>0&&i.push({text:r,offset:s,atomic:!1}),i}function Us(n,e){if(n.length<=e)return[{text:n,offset:0}];const i=Fn(n,0,Bs).flatMap(s=>In(s,e));return _s(i,e)}const Wa=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function zs(n,e){if(n.length<=e)return[{text:n,offset:0}];const t=[];for(const s of n.matchAll(Wa))s[0][0]==="<"?t.push({text:s[0],offset:s.index,atomic:!0}):t.push(...Fn(s[0],s.index,Bs));const i=t.flatMap(s=>In(s,e));return _s(i,e)}const Ka={wav:"audio/wav",mp3:"audio/mpeg",opus:"audio/ogg",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",m4a:"audio/mp4"};function Vs(n){return Ka[n]??`audio/${n}`}const Ga=["flac","wav","opus","aac","ogg","webm","mp3"],Xa=["opus","aac","webm","ogg","mp3","wav","flac"];function js(n,e,t){const i=a=>t(Vs(a))!=="",s=n.formats.filter(i);if(e.preferredFormat&&s.includes(e.preferredFormat))return e.preferredFormat;const r=e.strategy==="bandwidth"?Xa:Ga,o=[...r,...s.filter(a=>!r.includes(a))];for(const a of o)if(s.includes(a))return a;return n.default}const Ja=new Set(["wav","flac"]),Ya={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function Hs(n,e,t){return Ja.has(n)||!e||!t?void 0:t.saveData===!0||/2g/.test(t.effectiveType??"")?Ya[n]:void 0}function Ln(n,e){return{source:"server",label:n.name,name:n.name,originalName:n.originalName,language:n.language,otherLanguages:n.otherLanguages,gender:n.gender??void 0,quality:n.quality,provider:n.provider,identifier:n.identifier,controls:e}}class ke extends Error{status;type;title;instance;constructor(e,t){super(e),this.name="SpeechServerError",this.status=t.status,this.type=t.type,this.title=t.title,this.instance=t.instance}}class $n extends ke{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class Mn extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class _n extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function be(n){if((n.headers.get("content-type")??"").includes("application/problem+json"))try{const t=await n.json();return new ke(t.detail||t.title||`Request failed with status ${n.status}`,{status:t.status??n.status,type:t.type,title:t.title,instance:t.instance})}catch{}return new ke(`Request failed with status ${n.status}`,{status:n.status})}const Qa=3,Za=400;function el(n){const e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t.buffer}function tl(n){return ae(n,.25,4,1)}function it(n){return n?.plain??n?.ssml??void 0}function Si(n){return n instanceof $n?{message:n.message,status:n.status,type:n.type,title:n.title,instance:n.instance,recoverable:!0}:n instanceof ke?{message:n.message,status:n.status,type:n.type,title:n.title,instance:n.instance,recoverable:!1}:n instanceof Mn?{message:n.message,recoverable:!1}:n instanceof _n?{message:n.message,recoverable:!0}:n instanceof Error?{message:n.message,recoverable:!1}:{message:String(n),recoverable:!1}}class qs{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Lt;speakInContentLanguage=!1;speakGeneration=0;loadGeneration=0;prefetchWindow;readyBufferChars;overLengthText;timeoutMs;formatOptions;canPlayType;prefetchCache=new Map;prefetchChainTail=Promise.resolve();activeControllers=new Set;liveControllers=new Set;isSpeakingInternal=!1;restartPending=!1;audioContext=null;masterGain=null;scheduledChunks=[];boundaryRafHandle=null;rate=1;pitch=1;volume=1;constructor(e){this.endpoints=e.endpoints,this.fetchImpl=e.fetch??fetch.bind(globalThis),this.prefetchWindow=e.prefetchWindow??Qa,this.readyBufferChars=e.readyBufferChars??Za,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?t=>new Audio().canPlayType(t):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,t){try{return await this.fetchImpl(e,t)}catch(i){throw i instanceof TypeError?new _n(i.message):i}}loadUtterances(e,t){this.abortLiveControllers(),this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=dt(t??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const t=dt(this.currentUtteranceIndex,this.currentUtterances.length),i=Math.min(this.indexCoveringChars(this.readyBufferChars,t),t+this.prefetchWindow),s=[];for(let r=t;r<=i;r++){this.queuePrefetch(r);const o=this.prefetchCache.get(r);o&&s.push(o.then(a=>a[0].promise))}try{await Promise.all(s)}catch{}e!==this.loadGeneration||this.playbackState!=="loading"||this.setState("ready")}indexCoveringChars(e,t){if(this.currentUtterances.length===0)return-1;const i=dt(t,this.currentUtterances.length);let s=0;for(let r=i;r<this.currentUtterances.length;r++)if(s+=(it(this.currentUtterances[r])??"").length,s>=e)return r;return this.currentUtterances.length-1}setVoice(e){if(typeof e=="string"){const t=this.voices.find(i=>i.identifier===e||i.name===e);t?this.currentVoice=t:(this.currentVoice={source:"server",label:e,name:e,originalName:e,language:"",identifier:e},this.getAvailableVoices().then(i=>{if(this.currentVoice?.identifier!==e)return;const s=i.find(r=>r.identifier===e||r.name===e);s&&(this.currentVoice=s)}).catch(()=>{}))}else this.currentVoice=e;this.abortLiveControllers(),this.clearPrefetchCache()}getCurrentVoice(){return this.currentVoice}async getAvailableVoices(){if(this.voices.length>0)return this.voices;const[e,t]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await be(e);const i=await e.json(),s=new Map(t.providers.map(r=>[r.id,r.controls]));return this.voices=i.map(r=>Ln(r,s.get(r.provider))),this.voices}async getServiceInfo(){return this.serviceInfo?this.serviceInfo:(this.serviceInfoPromise||(this.serviceInfoPromise=this.fetchServiceInfo().catch(e=>{throw this.serviceInfoPromise=null,e})),this.serviceInfo=await this.serviceInfoPromise,this.serviceInfo)}async fetchServiceInfo(){const e=await this.fetchNetwork(this.endpoints.service);if(!e.ok)throw await be(e);return e.json()}setSpeakInContentLanguage(e){this.speakInContentLanguage=e,this.abortLiveControllers(),this.clearPrefetchCache()}getSpeakInContentLanguage(){return this.speakInContentLanguage}speak(e){if(e!==void 0){if(e<0||e>=this.currentUtterances.length)throw new Error("Invalid utterance index");this.currentUtteranceIndex=e}if(this.restartPending=!1,this.currentUtterances.length===0){console.warn("No utterances loaded");return}this.stopAudio(),this.abortLiveControllers();const t=++this.speakGeneration;this.isSpeakingInternal=!0,this.setState("loading"),this.synthesizeAndPlay(t)}async synthesizeAndPlay(e){const t=this.currentUtteranceIndex;try{const i=await this.resolveSynthesisStream(t);if(e!==this.speakGeneration)return;await this.scheduleChunksStreaming(i,e),this.fillPrefetchWindow(t)}catch(i){if(e!==this.speakGeneration)return;this.isSpeakingInternal=!1,this.setState("idle"),this.emitEvent({type:"error",detail:Si(i)})}}async resolveSynthesisStream(e){const t=this.prefetchCache.get(e);if(t){this.prefetchCache.delete(e);try{const i=await t;for(const{controller:s}of i)this.activeControllers.delete(s),this.liveControllers.add(s);return i}catch{}}return this.synthesizeStream(e,!1)}fillPrefetchWindow(e){const t=Math.min(e+this.prefetchWindow,this.currentUtterances.length-1);for(let i=e+1;i<=t;i++)this.queuePrefetch(i)}queuePrefetch(e){if(this.prefetchCache.has(e))return;const t=this.prefetchChainTail.then(()=>this.synthesizeStream(e,!0));this.prefetchCache.set(e,t),this.prefetchChainTail=t.then(i=>Promise.all(i.map(s=>s.promise))).then(()=>{},()=>{}),t.catch(()=>{}),t.then(i=>i.forEach(s=>s.promise.catch(()=>{}))).catch(()=>{})}clearPrefetchCache(){this.prefetchCache.clear(),this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear()}abortLiveControllers(){this.liveControllers.forEach(e=>e.abort()),this.liveControllers.clear()}async synthesizeStream(e,t){const i=this.currentUtterances[e],s=!i.plain&&!!i.ssml,r=this.speakInContentLanguage?i.language:void 0,o=it(i)??"",a=s?Ds(o).map:void 0,l=it(this.currentUtterances[e-1]),c=it(this.currentUtterances[e+1]),u=await this.getServiceInfo(),h=js(u.output,this.formatOptions,this.canPlayType),d=navigator.connection,f=Hs(h,this.formatOptions.adaptBitrateToNetwork??!1,d);if(o.length<=u.limits.maxTextLength){const w=new AbortController;return(t?this.activeControllers:this.liveControllers).add(w),[{promise:this.synthesizeChunk({content:i,text:o,textOffset:0,useSSML:s,ssmlMap:a,language:r,prevText:l,nextText:c,format:h,bitrate:f,controller:w}),controller:w}]}if(this.overLengthText==="error")throw new ke(`Text exceeds this server's maximum length of ${u.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(u.limits.maxTextLength,this.readyBufferChars),p=s?zs(o,g):Us(o,g),m=[];let v=Promise.resolve();for(let w=0;w<p.length;w++){const S=w===0?l:p[w-1].text,y=w===p.length-1?c:p[w+1].text,b=p[w],C=new AbortController;(t?this.activeControllers:this.liveControllers).add(C);const R=v.then(()=>this.synthesizeChunk({content:i,text:b.text,textOffset:b.offset,useSSML:s,ssmlMap:a,language:r,prevText:S,nextText:y,format:h,bitrate:f,controller:C}));m.push({promise:R,controller:C}),v=R}return m}async synthesizeChunk(e){const{content:t,text:i,textOffset:s,useSSML:r,ssmlMap:o,language:a,prevText:l,nextText:c,format:u,bitrate:h,controller:d}=e;try{const f=await this.fetchNetwork(this.endpoints.synthesize,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t.id,text:r?i:Ns(i),ssml:r,language:a,voice:this.currentVoice?.identifier??this.currentVoice?.name,prev_utterance:l,next_utterance:c,boundary:!0,output:{format:u,bitrate:h,speed:this.rate,pitch:this.pitch}}),signal:d.signal});if(!f.ok)throw await be(f);const g=await f.json(),p=el(g.audio);let m;try{m=await this.ensureAudioContext().decodeAudioData(p)}catch{throw new Mn("Audio playback failed")}return{audioBuffer:m,format:g.format,boundaries:g.boundaries,textOffset:s,ssmlMap:o}}finally{this.activeControllers.delete(d),this.liveControllers.delete(d)}}ensureAudioContext(){return this.audioContext||(this.audioContext=new AudioContext,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this.volume,this.masterGain.connect(this.audioContext.destination)),this.audioContext.state==="suspended"&&this.audioContext.resume().catch(()=>{}),this.audioContext}awaitWithStallDeadline(e,t,i){if(this.timeoutMs===void 0)return e;const s=i+this.timeoutMs;return new Promise((r,o)=>{const a=setTimeout(()=>{t.abort(),o(new $n(`No audio chunk arrived within ${s.toFixed(0)}ms of the playback buffer running dry`))},s);e.then(l=>{clearTimeout(a),r(l)},l=>{clearTimeout(a),o(l)})})}async scheduleChunksStreaming(e,t){const i=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(t!==this.speakGeneration)return;const s=this.ensureAudioContext(),r=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:tl(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let l=s.currentTime,c=null;const u=h=>{const d=s.createBufferSource();d.buffer=h.audioBuffer,d.playbackRate.value=a,d.connect(r),d.start(l),c&&(c.onended=null),d.onended=()=>this.handleUtteranceEnded(t),c=d,this.scheduledChunks.push({chunk:h,startTime:l,node:d,nextBoundaryIndex:0,rate:a}),l+=h.audioBuffer.duration/a};u(i),this.startBoundaryPolling(t);for(let h=1;h<e.length;h++){let d;try{const f=Math.max(0,(l-s.currentTime)*1e3);d=await this.awaitWithStallDeadline(e[h].promise,e[h].controller,f)}catch(f){t===this.speakGeneration&&this.emitEvent({type:"error",detail:Si(f)});return}if(t!==this.speakGeneration)return;u(d)}}handleUtteranceEnded(e){e===this.speakGeneration&&(this.checkBoundaries(),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,this.currentUtteranceIndex>=this.currentUtterances.length-1&&this.setState("idle"),this.emitEvent({type:"end"}))}startBoundaryPolling(e){const t=()=>{e===this.speakGeneration&&(this.checkBoundaries(),this.boundaryRafHandle=requestAnimationFrame(t))};this.boundaryRafHandle=requestAnimationFrame(t)}stopBoundaryPolling(){this.boundaryRafHandle!==null&&(cancelAnimationFrame(this.boundaryRafHandle),this.boundaryRafHandle=null)}checkBoundaries(){if(!this.audioContext)return;const e=this.audioContext.currentTime;for(const t of this.scheduledChunks){const i=t.chunk.boundaries??[];for(;t.nextBoundaryIndex<i.length&&e>=t.startTime+i[t.nextBoundaryIndex].elapsedTime/t.rate;){const s=i[t.nextBoundaryIndex],r=s.charIndex+t.chunk.textOffset;let o=r,a=s.charLength;if(t.chunk.ssmlMap){const l=t.chunk.ssmlMap;o=di(l,r),a=Math.max(0,di(l,r+s.charLength)-o)}this.emitEvent({type:"boundary",detail:{name:s.name,charIndex:o,charLength:a,elapsedTime:s.elapsedTime}}),t.nextBoundaryIndex++}}}stopAudio(){this.stopBoundaryPolling();for(const e of this.scheduledChunks){e.node.onended=null;try{e.node.stop()}catch{}e.node.disconnect()}this.scheduledChunks=[]}pause(){this.playbackState==="playing"&&this.audioContext&&(this.audioContext.suspend().catch(()=>{}),this.stopBoundaryPolling(),this.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.audioContext&&(this.audioContext.resume().catch(()=>{}),this.startBoundaryPolling(this.speakGeneration),this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}))}stop(){this.speakGeneration++,this.loadGeneration++,this.stopAudio(),this.abortLiveControllers(),this.clearPrefetchCache(),this.isSpeakingInternal=!1,this.currentUtteranceIndex=0,this.setState("idle"),this.emitEvent({type:"stop"})}setRate(e){const t=ae(e,.1,10,this.rate);t!==this.rate&&(this.rate=t,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const t=ae(e,0,2,this.pitch);t!==this.pitch&&(this.pitch=t,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const t=ae(e,0,1,this.volume);t!==this.volume&&(this.volume=t,this.masterGain&&(this.masterGain.gain.value=this.volume))}getVolume(){return this.volume}scheduleRestartIfSpeaking(){!this.isSpeakingInternal||this.restartPending||(this.restartPending=!0,queueMicrotask(()=>{this.restartPending&&(this.restartPending=!1,this.isSpeakingInternal&&this.speak(this.currentUtteranceIndex))}))}getState(){return this.playbackState}getCurrentUtteranceIndex(){return this.currentUtteranceIndex}setCurrentUtteranceIndex(e,t){if(e<0||e>=this.currentUtterances.length){t?.(!1);return}if(e===this.currentUtteranceIndex){t?.(!0);return}this.stopAudio(),this.currentUtteranceIndex=e,t?.(!0)}getUtteranceCount(){return this.currentUtterances.length}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const t=this.playbackState;if(this.playbackState=e,t!==e)switch(e){case"idle":this.emitEvent({type:"idle"});break;case"loading":this.emitEvent({type:"loading"});break;case"ready":this.emitEvent({type:"ready"});break}}async destroy(){this.stop(),await this.audioContext?.close(),this.audioContext=null,this.masterGain=null,this.events.clear(),this.currentUtterances=[],this.currentVoice=null,this.voices=[]}}class nl{id="speech-server";name="Readium Speech Server";options;fetchImpl;voices=[];constructor(e){this.options=e,this.fetchImpl=e.fetch??fetch.bind(globalThis)}async getVoices(e){if(this.voices.length>0&&!e)return this.voices;const[t,i]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!t.ok)throw await be(t);if(!i.ok)throw await be(i);const s=await t.json(),r=await i.json(),o=new Map(r.providers.map(a=>[a.id,a.controls]));return this.voices=s.map(a=>Ln(a,o.get(a.provider))),this.voices}async createEngine(e){const t=new qs(this.options);return this.voices.length>0&&t.setAvailableVoices(this.voices),e&&t.setVoice(e),t}async destroy(){this.voices=[]}}function Ws(n){return n.detail?.recoverable===!0}const il=3e4,sl=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Ks{activeEngine;primaryProvider;fallbackProvider;onFailure;healthCheckIntervalMs;hasFallenBack=!1;healthCheckTimer=null;primaryReachable=!1;currentUtterances=[];lastVoiceRequest;desiredIndex=0;desiredPlaying=!1;engineStarted=!0;swapInFlight=!1;teardownEpoch=0;loadToken=0;events=new Lt;unbindActiveEngine=null;constructor(e){this.activeEngine=e.primaryEngine,this.primaryProvider=e.primaryProvider,this.fallbackProvider=e.fallbackProvider,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs??il,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,t){this.loadToken++,this.currentUtterances=e,this.desiredIndex=t??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,t))}setVoice(e){this.lastVoiceRequest=e,this.activeEngine.setVoice(e)}getCurrentVoice(){return this.activeEngine.getCurrentVoice()}getAvailableVoices(){return this.activeEngine.getAvailableVoices()}setSpeakInContentLanguage(e){this.activeEngine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.activeEngine.getSpeakInContentLanguage()}speak(e){if(this.desiredIndex=e??this.desiredIndex,this.desiredPlaying=!0,!this.swapInFlight){if(this.hasFallenBack&&this.primaryReachable&&this.activeEngine.getState()!=="playing"){this.recoverToPrimary();return}this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex)}}pause(){this.desiredPlaying=!1,this.isEngineTrusted()&&this.activeEngine.pause()}resume(){if(this.desiredPlaying=!0,!this.swapInFlight){if(!this.engineStarted){this.engineStarted=!0,this.activeEngine.speak(this.desiredIndex);return}this.activeEngine.resume()}}stop(){this.desiredPlaying=!1,this.desiredIndex=0,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.stop())}setRate(e){this.activeEngine.setRate(e)}getRate(){return this.activeEngine.getRate()}setPitch(e){this.activeEngine.setPitch(e)}getPitch(){return this.activeEngine.getPitch()}setVolume(e){this.activeEngine.setVolume(e)}getVolume(){return this.activeEngine.getVolume()}isEngineTrusted(){return!this.swapInFlight&&this.engineStarted}getState(){return this.isEngineTrusted()?this.activeEngine.getState():this.desiredPlaying?"loading":"paused"}getCurrentUtteranceIndex(){return this.isEngineTrusted()?this.activeEngine.getCurrentUtteranceIndex():this.desiredIndex}setCurrentUtteranceIndex(e,t){if(this.desiredIndex=e,!this.isEngineTrusted()){t?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,t)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,t=sl.map(i=>e.on(i,s=>{this.emitEvent(s),this.maybeRecoverNow()}));t.push(e.on("error",i=>this.handleError(i))),this.unbindActiveEngine=()=>t.forEach(i=>i())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!Ws(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,t){t.setRate(e.getRate()),t.setPitch(e.getPitch()),t.setVolume(e.getVolume()),t.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const t=this.loadToken,i=e.on("ready",()=>{i(),t===this.loadToken&&(this.desiredPlaying?(this.engineStarted=!0,e.speak(this.desiredIndex)):this.engineStarted=!1)})}startHealthCheck(){this.healthCheckTimer===null&&(this.healthCheckTimer=setTimeout(async()=>{this.healthCheckTimer=null;try{await this.primaryProvider.getVoices(!0),this.primaryReachable=!0,this.maybeRecoverNow()}catch{this.startHealthCheck()}},this.healthCheckIntervalMs))}maybeRecoverNow(){!this.hasFallenBack||!this.primaryReachable||this.swapInFlight||this.activeEngine.getState()!=="playing"&&this.recoverToPrimary()}async swapToFallback(e){let t=null;await this.performSwap(async()=>{const s=this.activeEngine.getCurrentVoice()??(typeof this.lastVoiceRequest=="object"?this.lastVoiceRequest:null),r=s?.language||this.currentUtterances[this.desiredIndex]?.language||(typeof navigator<"u"?navigator.language:"en");if(t=await this.pickBestFallbackVoice(r,s?.gender),!t)throw new Error("no offline-available fallback voice found");return this.fallbackProvider.createEngine(t)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:t}}),()=>{this.hasFallenBack=!0,this.emitEvent(e)})}async recoverToPrimary(){await this.performSwap(()=>this.primaryProvider.createEngine(this.lastVoiceRequest),e=>(this.hasFallenBack=!1,this.primaryReachable=!1,{type:"enginerecovered",detail:{voice:e.getCurrentVoice()}}),()=>{this.primaryReachable=!1,this.startHealthCheck()})}async performSwap(e,t,i){this.swapInFlight=!0;const s=this.teardownEpoch,r=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,i();return}if(s!==this.teardownEpoch){this.swapInFlight=!1,await o.destroy();return}this.copyPlaybackParameters(r,o),this.unbindActiveEngine?.(),this.activeEngine=o,this.engineStarted=!1,this.swapInFlight=!1,this.bindActiveEngine(),this.emitEvent(t(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await r.destroy()}async pickBestFallbackVoice(e,t){const i=await this.fallbackProvider.getVoices(),r=typeof navigator<"u"&&navigator.onLine===!0?i:i.filter(d=>d.offlineAvailability===!0);if(r.length===0)return null;const[o]=Ft([e]),{voicesByLang:a}=It(r,[o]),l=a.get(o.baseLang)??[],c=l.length>0?l:r,u=t?c.filter(d=>d.gender===t):[],h=u.length>0?u:c;return Jo(e,h)}async destroy(){this.teardownEpoch++,this.healthCheckTimer!==null&&(clearTimeout(this.healthCheckTimer),this.healthCheckTimer=null),this.unbindActiveEngine?.(),this.events.clear(),await this.activeEngine.destroy()}}class rl{id="fallback";name="Fallback";primary;fallback;onFailure;healthCheckIntervalMs;constructor(e){this.primary=e.primary,this.fallback=e.fallback,this.onFailure=e.onFailure??"fallback",this.healthCheckIntervalMs=e.healthCheckIntervalMs}async getVoices(e){try{return await this.primary.getVoices(e)}catch(t){if(this.onFailure==="error")throw t;return this.fallback.getVoices(e)}}async createEngine(e){let t;try{t=await this.primary.createEngine(e)}catch(i){if(this.onFailure==="error")throw i;return this.fallback.createEngine(e)}return new Ks({primaryEngine:t,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let ol=class{};function al(n){return(n.getComputedStyle(n.document.documentElement).writingMode||n.getComputedStyle(n.document.body).writingMode)==="vertical-lr"}function ll(n){const e=n.getComputedStyle(n.document.documentElement).writingMode||n.getComputedStyle(n.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function de(n){const e=ll(n),t=e&&al(n),i=n.innerWidth,s=n.innerHeight,r=n.document.scrollingElement,o=r.scrollLeft,a=r.scrollTop,l=parseInt(n.getComputedStyle(n.document.documentElement).getPropertyValue("column-count")),c=e&&!t?r.scrollWidth-i+o:o,u=a;return{isVertical:e,isVertLR:t,viewportInlineSize:e?s:i,viewportBlockSize:e?i:s,pageInlineSize:e?s:i/(l||1),xDocOffset:c,yDocOffset:u,inlineScrollOffset:e?u:c,blockScrollOffset:e?c:u,inlineStart:h=>e?h.top:h.left,blockStart:h=>e?h.left:h.top,inlineSize:h=>e?h.height:h.width,blockSize:h=>e?h.width:h.height,applyPosition(h,d,f,g,p,m){h.style.position="absolute",h.style.zIndex="2147483646",e?(h.style.top=`${d*m}px`,h.style.left=`${f*m}px`,h.style.height=`${g*m}px`,h.style.width=`${p*m}px`):(h.style.left=`${d*m}px`,h.style.top=`${f*m}px`,h.style.width=`${g*m}px`,h.style.height=`${p*m}px`)},toRect(h,d,f,g){return e?new DOMRect(d,h,g,f):new DOMRect(h,d,f,g)}}}function yi(n,e){return n.document.documentElement.style.getPropertyValue(e)}function cl(n){return n&&Array.isArray(n)?n:void 0}function ul(n){return n&&typeof n=="string"?[n]:cl(n)}function ft(n){return isNaN(n)?void 0:n}function qt(n){return ft(n)!==void 0&&Math.sign(n)>=0?n:void 0}let St=class Gs{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=qt(e.textNodeIndex);if(t===void 0)return;let i=qt(e.charOffset);return i===void 0&&(i=qt(e.offset)),new Gs({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:i})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}},Xs=class Js{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=St.deserialize(e.start);if(t)return new Js({start:t,end:St.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}},st=null,Wt=null,Le=0;const pe={r:255,g:255,b:255,a:1},fe=new Map,hl=()=>{if(!st)if(typeof OffscreenCanvas<"u")st=new OffscreenCanvas(5,5),Wt=st.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const n=document.createElement("canvas");n.width=5,n.height=5,st=n,Wt=n.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return Wt},dl=n=>{if(!n)return!0;const e=n.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(t=>e.includes(t))},rt=(n,e)=>{console.warn(`[Decorator] Could not parse color: "${n}". ${e} Falling back to ${JSON.stringify(pe)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},ce=(n,e=null)=>{const t=e?`${n}|${e}`:n,i=fe.get(t);if(i!==void 0)return i??pe;if(dl(n))return rt(n,"Unsupported color format or special value."),fe.set(t,null),pe;const s=hl();if(!s)return rt(n,"Could not get canvas context."),fe.set(t,null),pe;try{Le===0&&s.clearRect(0,0,5,5);const r=Le%5,o=Math.floor(Le/5);s.clearRect(r,o,1,1),e&&(s.fillStyle=e,s.fillRect(r,o,1,1)),s.fillStyle=n,s.fillRect(r,o,1,1);const a=s.getImageData(r,o,1,1);Le=(Le+1)%25;const[l,c,u,h]=a.data;if(h===0)return rt(n,"Fully transparent color."),fe.set(t,null),pe;const d={r:l,g:c,b:u,a:h/255};return fe.set(t,d),d}catch(r){return rt(n,`Error: ${r instanceof Error?r.message:String(r)}`),fe.set(t,null),pe}},Kt=n=>{const e=n/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},un=n=>{const e=Kt(n.r),t=Kt(n.g),i=Kt(n.b);return .2126*e+.7152*t+.0722*i},yt=(n,e)=>{const t=typeof n=="string"?ce(n):n,i=typeof e=="string"?ce(e):e,s=un(t),r=un(i),o=Math.max(s,r),a=Math.min(s,r);return(o+.05)/(a+.05)},Ys=(n,e=null)=>{const t=ce(n,e),i=yt(t,{r:255,g:255,b:255,a:1}),s=yt(t,{r:0,g:0,b:0,a:1});return i>s},vi=(n,e=null)=>Ys(n,e)?"white":"black",fl=n=>{const e=n.a!==void 0?n.a:1;return`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`},gl=(n,e)=>({r:Math.min(255,n.r+(255-n.r)*e),g:Math.min(255,n.g+(255-n.g)*e),b:Math.min(255,n.b+(255-n.b)*e),a:n.a??1}),pl=(n,e)=>({r:Math.max(0,n.r*(1-e)),g:Math.max(0,n.g*(1-e)),b:Math.max(0,n.b*(1-e)),a:n.a??1}),ge=(n,e=null,t=3)=>{const i=ce(n),s=e?ce(e):{r:255,g:255,b:255,a:1};let r=yt(i,s);if(r>=t)return n;const o=un(s)<.5;let a={...i,a:i.a??1};const l=20,c=.1;for(let u=0;u<l&&(o?a=gl(a,c):a=pl(a,c),r=yt(a,s),!(r>=t));u++);return fl(a)},Qs=()=>typeof navigator>"u"?"":navigator.userAgent||"",Zs=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let er=class{constructor(){const e=Zs(),t=Qs(),i=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(o=>parseInt(o)||0):[],s=(r="")=>{if(!r)return[];const o=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return o.test(t)?i(t.replace(o,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(r.iOS=s("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?r.iOS=r.iPadOS=s("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=s():r.macOS=s("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?r.Windows=(o=>o[0]!==6||!o[1]?o:o[1]===1?[7]:o[1]===2?[8]:[8,1])(s("Windows(?: NT)?")):/Android \d/.test(t)?r.Android=s("Android"):/CrOS/.test(t)?r.ChromeOS=s():/X11;/.test(t)&&(r.Linux=s()),r))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(o=>{const a=r.platform,l=r.platformVersion;if(!(!a||!l)){if(/^i(OS|P(hone|od touch))$/.test(a))o.iOS=i(l);else if(/^iPad(OS)?$/.test(a))o.iOS=o.iPadOS=i(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?o.iOS=o.iPadOS=i():o.macOS=i(l);else if(/^(Microsoft )?Windows$/.test(a))o.Windows=i(l);else if(/^(Google )?Android$/.test(a))o.Android=i(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))o.ChromeOS=i(l);else if(/^(Linux|Ubuntu|X11)$/.test(a))o.Linux=i(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,o)}})({})),this.UA=(r=>{let o=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});a["Google Chrome"]?(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Edge=a["Microsoft Edge"]):a.Opera&&(o=!0,r.Blink=r.Chromium=a.Chromium||[],r.Opera=a.Opera)}return o||(/ Gecko\/\d/.test(t)?(r.Gecko=s("rv"),/ Waterfox\/\d/.test(t)?r.Waterfox=s("Waterfox"):/ Firefox\/\d/.test(t)&&(r.Firefox=s("Firefox"))):/ Edge\/\d/.test(t)?(r.EdgeHTML=s("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(r.Blink=r.Chromium=(a=>a[0]?a:s("Chrome"))(s("Chromium")),/ EdgA?\/\d/.test(t)?r.Edge=(a=>a[0]?a:s("Edg"))(s("EdgA")):/ OPR\/\d/.test(t)?r.Opera=s("OPR"):/ Vivaldi\/\d/.test(t)?r.Vivaldi=s("Vivaldi"):/ Silk\/\d/.test(t)?r.Silk=s("Silk"):/ UCBrowser\/\d/.test(t)?r.UCBrowser=s("UCBrowser"):/ Phoebe\/\d/.test(t)?r.Phoebe=s("Phoebe"):r.Chrome=(a=>a[0]?a:r.Chromium)(s("Chrome"))):/ AppleWebKit\/\d/.test(t)?(r.WebKit=s("AppleWebKit"),/ CriOS \d/.test(t)?r.Chrome=s("CriOS"):/ FxiOS \d/.test(t)?r.Firefox=s("FxiOS"):/ EdgiOS\/\d/.test(t)?r.Edge=s("EdgiOS"):/ Version\/\d/.test(t)&&(r.Safari=s("Version"))):/ Trident\/\d/.test(t)&&(r.Trident=s("Trident"),r.InternetExplorer=(a=>a[0]?a:s("MSIE"))(s("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(r.Facebook=s("FBAV")),/ Line\/\d/.test(t)&&(r.LINE=s("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,o)=>{for(const a in o)o[a]&&r.push(a);return r},[])}}},ml=class extends er{get iOSRequest(){const e=Zs(),t=Qs();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(t)||e&&/^iPad(OS)?$/.test(e.platform)?"mobile":"desktop"}};const bi=new er;new ml;const wi=":~:text=";function Sl(n){if(!n)return;const e=n.indexOf(wi);if(e===-1)return;const t=n.slice(e+wi.length).split("&")[0];if(t)try{let i=t.split(",");const s={textStart:""};return i.length>1&&i[0].endsWith("-")&&(s.prefix=decodeURIComponent(i[0].slice(0,-1)),i=i.slice(1)),i.length>1&&i[i.length-1].startsWith("-")&&(s.suffix=decodeURIComponent(i[i.length-1].slice(1)),i=i.slice(0,-1)),i.length===0||i[0]===""?void 0:(s.textStart=decodeURIComponent(i[0]),i.length>1&&(s.textEnd=decodeURIComponent(i[1])),s)}catch{return}}const tr=["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","BR","DETAILS","DIALOG","DD","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","LI","MAIN","NAV","OL","P","PRE","SECTION","TABLE","UL","TR","TH","TD","COLGROUP","COL","CAPTION","THEAD","TBODY","TFOOT"],Be=/[\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,yl=/[^\t-\r -#%-\*,-\/:;\?@\[-\]_\{\}\x85\xA0\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/u,nr=(n,e,t)=>{const i=[],s=e.createRange();for(s.selectNodeContents(t??e);!s.collapsed&&i.length<2;){let r;if(n.prefix){const o=Ue(n.prefix,s);if(o==null)break;ot(s,o.startContainer,o.startOffset);const a=e.createRange();if(a.setStart(o.endContainer,o.endOffset),a.setEnd(s.endContainer,s.endOffset),ir(a),a.collapsed||(r=Ue(n.textStart,a),r==null))break;if(r.compareBoundaryPoints(Range.START_TO_START,a)!==0)continue}else{if(r=Ue(n.textStart,s),r==null)break;ot(s,r.startContainer,r.startOffset)}if(n.textEnd){const o=e.createRange();o.setStart(r.endContainer,r.endOffset),o.setEnd(s.endContainer,s.endOffset);let a=!1;for(;!o.collapsed&&i.length<2;){const l=Ue(n.textEnd,o);if(l==null)break;if(ot(o,l.startContainer,l.startOffset),r.setEnd(l.endContainer,l.endOffset),n.suffix){const c=xi(n.suffix,r,s,e);if(c===K.NO_SUFFIX_MATCH)break;if(c===K.SUFFIX_MATCH){a=!0,i.push(r.cloneRange());continue}else if(c===K.MISPLACED_SUFFIX)continue}else a=!0,i.push(r.cloneRange())}if(!a)break}else if(n.suffix){const o=xi(n.suffix,r,s,e);if(o===K.NO_SUFFIX_MATCH)break;if(o===K.SUFFIX_MATCH){i.push(r.cloneRange()),ot(s,s.startContainer,s.startOffset);continue}else if(o===K.MISPLACED_SUFFIX)continue}else i.push(r.cloneRange())}return i},K={NO_SUFFIX_MATCH:0,SUFFIX_MATCH:1,MISPLACED_SUFFIX:2},xi=(n,e,t,i)=>{const s=i.createRange();s.setStart(e.endContainer,e.endOffset),s.setEnd(t.endContainer,t.endOffset),ir(s);const r=Ue(n,s);return r==null?K.NO_SUFFIX_MATCH:r.compareBoundaryPoints(Range.START_TO_START,s)!==0?K.MISPLACED_SUFFIX:K.SUFFIX_MATCH},ot=(n,e,t)=>{try{n.setStart(e,t+1)}catch{n.setStartAfter(e)}},ir=n=>{const e=sr(n);let t=e.nextNode();for(;!n.collapsed&&t!=null;){if(t!==n.startContainer&&n.setStart(t,0),t.textContent.length>n.startOffset&&!t.textContent[n.startOffset].match(/\s/))return;try{n.setStart(t,n.startOffset+1)}catch{t=e.nextNode(),t==null?n.collapse():n.setStart(t,0)}}},sr=n=>(n.commonAncestorContainer.ownerDocument??n.commonAncestorContainer).createTreeWalker(n.commonAncestorContainer,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>bl(e,n)}),vl=n=>{if(n.hidden==="until-found")return!0;const e=n.attributes;return!!(e&&e.hidden&&e.hidden.value==="until-found")},Bn=n=>{let e=n;for(;e!=null&&!(e instanceof HTMLElement);)e=e.parentNode;const t=e?.ownerDocument?.defaultView;if(e!=null&&t!=null){if(vl(e))return!0;const i=t.getComputedStyle(e);if(i.visibility==="hidden"||i.display==="none"||parseInt(i.height,10)===0&&i.overflowY!="visible"||parseInt(i.width,10)===0&&i.overflowX!="visible"||parseInt(i.opacity,10)===0)return!1}return!0},rr=(n,e)=>e!=null&&!e.intersectsNode(n)?NodeFilter.FILTER_REJECT:Bn(n)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT,bl=(n,e)=>e!=null&&!e.intersectsNode(n)||!Bn(n)?NodeFilter.FILTER_REJECT:n.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,wl=(n,e)=>{const t=[];let i=[];const s=Array.from(El(n,r=>rr(r,e)));for(const r of s)r.nodeType===Node.TEXT_NODE?i.push(r):r instanceof HTMLElement&&tr.includes(r.tagName.toUpperCase())&&i.length>0&&(t.push(i),i=[]);return i.length>0&&t.push(i),t},xl=(n,e,t)=>{let i="";return n.length===1?i=n[0].textContent.substring(e,t):i=n[0].textContent.substring(e)+n.slice(1,-1).reduce((s,r)=>s+r.textContent,"")+n.slice(-1)[0].textContent.substring(0,t),i.replace(/[\t\n\r ]+/g," ")};function*El(n,e){const t=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e}),i=new Set;for(;ar(t,i)!==null;)yield t.currentNode}const Ue=(n,e)=>{const t=wl(e.commonAncestorContainer,e),i=or(e.commonAncestorContainer.ownerDocument??void 0);for(const s of t){const r=Cl(n,e,s,i);if(r!==void 0)return r}},Cl=(n,e,t,i)=>{if(!n||!e||!(t||[]).length)return;const s=t[0]===e.startContainer?e.startOffset:0,r=Y(xl(t,s,void 0)),o=Y(n);let a=0,l,c;for(;a<r.length;){const u=r.indexOf(o,a);if(u===-1)return;if(kl(r,u,o.length,i)){const h=Y(t[0].data.slice(0,s)).length;l=Ei(h+u,t,!1),c=Ei(h+u+o.length,t,!0)}if(l!=null&&c!=null){const h=new Range;if(h.setStart(l.node,l.offset),h.setEnd(c.node,c.offset),e.compareBoundaryPoints(Range.START_TO_START,h)<=0&&e.compareBoundaryPoints(Range.END_TO_END,h)>=0)return h}a=u+1}},Ei=(n,e,t)=>{let i=0,s;for(let r=0;r<e.length;r++){const o=e[r];s||(s=Y(o.data));let a=i+s.length;if(t&&(a+=1),a>n){const l=n-i;let c=Math.min(n-i,o.data.length);const u=t?s.substring(0,l):s.substring(l);let h=Y(t?o.data.substring(0,c):o.data.substring(c));const d=(t?-1:1)*(u.length>h.length?-1:1);for(;c>=0&&c<=o.data.length;){if(h.length===u.length)return{node:o,offset:c};c+=d,h=Y(t?o.data.substring(0,c):o.data.substring(c))}}if(i+=s.length,r+1<e.length){const l=Y(e[r+1].data);s.slice(-1)===" "&&l.slice(0,1)===" "&&(i-=1),s=l}}},kl=(n,e,t,i)=>{if(e<0||e>=n.length||t<=0||e+t>n.length)return!1;if(i){const s=i.segment(n),r=s.containing(e);if(!r||r.isWordLike&&r.index!=e)return!1;const o=e+t,a=s.containing(o);if(a&&a.isWordLike&&a.index!=o)return!1}else if(n[e].match(Be)&&(++e,--t,!t)||n[e+t-1].match(Be)&&(--t,!t)||e!==0&&!n[e-1].match(Be)||e+t!==n.length&&!n[e+t].match(Be))return!1;return!0},Y=n=>(n||"").normalize("NFKD").replace(/\s+/g," ").replace(/[\u0300-\u036f]/g,"").toLowerCase(),or=n=>{if(Intl.Segmenter){const e=n?.documentElement?.lang||n?.defaultView?.navigator?.language||void 0;return new Intl.Segmenter(e,{granularity:"word"})}},ar=(n,e)=>{if(!e.has(n.currentNode)){const s=n.firstChild();if(s!==null)return s}const t=n.nextSibling();if(t!==null)return t;const i=n.parentNode();return i!==null&&e.add(i),i},Rl=(n,e)=>{if(!e.has(n.currentNode)){const s=n.lastChild();if(s!==null)return s}const t=n.previousSibling();if(t!==null)return t;const i=n.parentNode();return i!==null&&e.add(i),i},k={BLOCK_ELEMENTS:tr,BOUNDARY_CHARS:Be,NON_BOUNDARY_CHARS:yl,acceptNodeIfVisibleInRange:rr,normalizeString:Y,makeNewSegmenter:or,forwardTraverse:ar,backwardTraverse:Rl,makeTextNodeWalker:sr,isNodeVisible:Bn},Al=300,lr=20,Ol=1,Ci=3,ki=1;let Tl=500,cr;class ur extends Error{constructor(){super(...arguments),this.isTimeout=!0}}const ie={SUCCESS:0,INVALID_SELECTION:1,AMBIGUOUS:2,TIMEOUT:3,EXECUTION_FAILED:4},Nl=(n,e=Date.now())=>{try{return Dl(n,e)}catch(t){return t instanceof ur?{status:ie.TIMEOUT}:{status:ie.EXECUTION_FAILED}}},Dl=(n,e)=>{Fl(e);const t=n.startContainer.ownerDocument,i=Pl(t);Ul(n),jl(n);const s=n.cloneRange();if(zl(n),n.collapsed)return{status:ie.INVALID_SELECTION};let r;if(Ll(n)){const h=k.normalizeString(n.toString()),d={textStart:h};if(h.length>=lr&&dr(d,t,i))return{status:ie.SUCCESS,fragment:d};r=new Gt(t,i).setExactTextMatch(h)}else{const h=Ri(n),d=Ai(n);h&&d?r=new Gt(t,i).setStartAndEndSearchSpace(h,d):r=new Gt(t,i).setSharedSearchSpace(n.toString().trim())}const o=t.createRange();o.selectNodeContents(i);const a=o.cloneRange();o.setEnd(s.startContainer,s.startOffset),a.setStart(s.endContainer,s.endOffset);const l=Ai(o),c=Ri(a);(l||c)&&r.setPrefixAndSuffixSearchSpace(l,c),r.useSegmenter(k.makeNewSegmenter(t));let u=!1;do{L(),u=r.embiggen();const h=r.tryToMakeUniqueFragment();if(h!=null)return{status:ie.SUCCESS,fragment:h}}while(u);return{status:ie.AMBIGUOUS}},Pl=n=>n.querySelector("body")??n.documentElement,L=()=>{const n=Date.now()-cr;if(n>Tl)throw new ur(`Fragment generation timed out after ${n} ms.`)},Fl=n=>{cr=n},Ri=n=>{let e=Ye(n);const t=ue(e,n.endContainer);if(!t)return;const i=new Set;n.startContainer.nodeType===Node.ELEMENT_NODE&&n.startOffset===n.startContainer.childNodes.length&&i.add(n.startContainer);const s=e,r=new hr(n,!0),o=n.cloneRange();for(;!o.collapsed&&e!=null;){if(L(),e.contains?.(s)?o.setStartAfter(e):o.setStartBefore(e),r.appendNode(e),r.textInBlock!==null)return r.textInBlock;e=k.forwardTraverse(t,i)}},Ai=n=>{let e=$t(n);const t=ue(e,n.startContainer);if(!t)return;const i=new Set;n.endContainer.nodeType===Node.ELEMENT_NODE&&n.endOffset===0&&i.add(n.endContainer);const s=e,r=new hr(n,!1),o=n.cloneRange();for(;!o.collapsed&&e!=null;){if(L(),e.contains?.(s)?o.setEnd(e,0):o.setEndAfter(e),r.appendNode(e),r.textInBlock!==null)return r.textInBlock;e=k.backwardTraverse(t,i)}},Il={ALL_PARTS:1,SHARED_START_AND_END:2,CONTEXT_ONLY:3};let Gt=class{constructor(e,t){this.Mode=Il,this.startOffset=null,this.endOffset=null,this.prefixOffset=null,this.suffixOffset=null,this.prefixSearchSpace="",this.backwardsPrefixSearchSpace="",this.suffixSearchSpace="",this.numIterations=0,this.doc=e,this.root=t}tryToMakeUniqueFragment(){let e;if(this.mode===this.Mode.CONTEXT_ONLY?e={textStart:this.exactTextMatch}:e={textStart:this.getStartSearchSpace().substring(0,this.startOffset).trim(),textEnd:this.getEndSearchSpace().substring(this.endOffset).trim()},this.prefixOffset!=null){const t=this.getPrefixSearchSpace().substring(this.prefixOffset).trim();t&&(e.prefix=t)}if(this.suffixOffset!=null){const t=this.getSuffixSearchSpace().substring(0,this.suffixOffset).trim();t&&(e.suffix=t)}return dr(e,this.doc,this.root)?e:void 0}embiggen(){let e=!0;if(this.mode===this.Mode.SHARED_START_AND_END?this.startOffset>=this.endOffset&&(e=!1):this.mode===this.Mode.ALL_PARTS?this.startOffset===this.getStartSearchSpace().length&&this.backwardsEndOffset()===this.getEndSearchSpace().length&&(e=!1):this.mode===this.Mode.CONTEXT_ONLY&&(e=!1),e){const i=this.getNumberOfRangeWordsToAdd();if(this.startOffset<this.getStartSearchSpace().length){let s=0;if(this.getStartSegments()!=null)for(;s<i&&this.startOffset<this.getStartSearchSpace().length;)this.startOffset=this.getNextOffsetForwards(this.getStartSegments(),this.startOffset,this.getStartSearchSpace()),s++;else{let r=this.startOffset;do{L();const o=this.getStartSearchSpace().substring(this.startOffset+1).search(k.BOUNDARY_CHARS);o===-1?this.startOffset=this.getStartSearchSpace().length:this.startOffset=this.startOffset+1+o,this.getStartSearchSpace().substring(r,this.startOffset).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.startOffset,s++)}while(this.startOffset<this.getStartSearchSpace().length&&s<i)}this.mode===this.Mode.SHARED_START_AND_END&&(this.startOffset=Math.min(this.startOffset,this.endOffset))}if(this.backwardsEndOffset()<this.getEndSearchSpace().length){let s=0;if(this.getEndSegments()!=null)for(;s<i&&this.endOffset>0;)this.endOffset=this.getNextOffsetBackwards(this.getEndSegments(),this.endOffset),s++;else{let r=this.backwardsEndOffset();do{L();const o=this.getBackwardsEndSearchSpace().substring(this.backwardsEndOffset()+1).search(k.BOUNDARY_CHARS);o===-1?this.setBackwardsEndOffset(this.getEndSearchSpace().length):this.setBackwardsEndOffset(this.backwardsEndOffset()+1+o),this.getBackwardsEndSearchSpace().substring(r,this.backwardsEndOffset()).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.backwardsEndOffset(),s++)}while(this.backwardsEndOffset()<this.getEndSearchSpace().length&&s<i)}this.mode===this.Mode.SHARED_START_AND_END&&(this.endOffset=Math.max(this.startOffset,this.endOffset))}}let t=!1;if((!e||this.startOffset+this.backwardsEndOffset()<lr||this.numIterations>=Ol)&&(this.backwardsPrefixOffset()!=null&&this.backwardsPrefixOffset()!==this.getPrefixSearchSpace().length||this.suffixOffset!=null&&this.suffixOffset!==this.getSuffixSearchSpace().length)&&(t=!0),t){const i=this.getNumberOfContextWordsToAdd();if(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length){let s=0;if(this.getPrefixSegments()!=null)for(;s<i&&this.prefixOffset>0;)this.prefixOffset=this.getNextOffsetBackwards(this.getPrefixSegments(),this.prefixOffset),s++;else{let r=this.backwardsPrefixOffset();do{L();const o=this.getBackwardsPrefixSearchSpace().substring(this.backwardsPrefixOffset()+1).search(k.BOUNDARY_CHARS);o===-1?this.setBackwardsPrefixOffset(this.getBackwardsPrefixSearchSpace().length):this.setBackwardsPrefixOffset(this.backwardsPrefixOffset()+1+o),this.getBackwardsPrefixSearchSpace().substring(r,this.backwardsPrefixOffset()).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.backwardsPrefixOffset(),s++)}while(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length&&s<i)}}if(this.suffixOffset<this.getSuffixSearchSpace().length){let s=0;if(this.getSuffixSegments()!=null)for(;s<i&&this.suffixOffset<this.getSuffixSearchSpace().length;)this.suffixOffset=this.getNextOffsetForwards(this.getSuffixSegments(),this.suffixOffset,this.getSuffixSearchSpace()),s++;else{let r=this.suffixOffset;do{L();const o=this.getSuffixSearchSpace().substring(this.suffixOffset+1).search(k.BOUNDARY_CHARS);o===-1?this.suffixOffset=this.getSuffixSearchSpace().length:this.suffixOffset=this.suffixOffset+1+o,this.getSuffixSearchSpace().substring(r,this.suffixOffset).search(k.NON_BOUNDARY_CHARS)!==-1&&(r=this.suffixOffset,s++)}while(this.suffixOffset<this.getSuffixSearchSpace().length&&s<i)}}}return this.numIterations++,e||t}setStartAndEndSearchSpace(e,t){return this.startSearchSpace=e,this.endSearchSpace=t,this.backwardsEndSearchSpace=gt(t),this.startOffset=0,this.endOffset=t.length,this.mode=this.Mode.ALL_PARTS,this}setSharedSearchSpace(e){return this.sharedSearchSpace=e,this.backwardsSharedSearchSpace=gt(e),this.startOffset=0,this.endOffset=e.length,this.mode=this.Mode.SHARED_START_AND_END,this}setExactTextMatch(e){return this.exactTextMatch=e,this.mode=this.Mode.CONTEXT_ONLY,this}setPrefixAndSuffixSearchSpace(e,t){return e&&(this.prefixSearchSpace=e,this.backwardsPrefixSearchSpace=gt(e),this.prefixOffset=e.length),t&&(this.suffixSearchSpace=t,this.suffixOffset=0),this}useSegmenter(e){return e==null?this:(this.mode===this.Mode.ALL_PARTS?(this.startSegments=e.segment(this.startSearchSpace),this.endSegments=e.segment(this.endSearchSpace)):this.mode===this.Mode.SHARED_START_AND_END&&(this.sharedSegments=e.segment(this.sharedSearchSpace)),this.prefixSearchSpace&&(this.prefixSegments=e.segment(this.prefixSearchSpace)),this.suffixSearchSpace&&(this.suffixSegments=e.segment(this.suffixSearchSpace)),this)}getNumberOfContextWordsToAdd(){return this.backwardsPrefixOffset()===0&&this.suffixOffset===0?Ci:ki}getNumberOfRangeWordsToAdd(){return this.startOffset===0&&this.backwardsEndOffset()===0?Ci:ki}getNextOffsetForwards(e,t,i){let s=e.containing(t);for(;s!=null;){L();const r=s.index+s.segment.length;if(s.isWordLike)return r;s=e.containing(r)}return i.length}getNextOffsetBackwards(e,t){let i=e.containing(t);for((!i||t==i.index)&&(i=e.containing(t-1));i!=null;){if(L(),i.isWordLike)return i.index;i=e.containing(i.index-1)}return 0}getStartSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.startSearchSpace}getStartSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.startSegments}getEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSearchSpace:this.endSearchSpace}getEndSegments(){return this.mode===this.Mode.SHARED_START_AND_END?this.sharedSegments:this.endSegments}getBackwardsEndSearchSpace(){return this.mode===this.Mode.SHARED_START_AND_END?this.backwardsSharedSearchSpace:this.backwardsEndSearchSpace}getPrefixSearchSpace(){return this.prefixSearchSpace}getPrefixSegments(){return this.prefixSegments}getBackwardsPrefixSearchSpace(){return this.backwardsPrefixSearchSpace}getSuffixSearchSpace(){return this.suffixSearchSpace}getSuffixSegments(){return this.suffixSegments}backwardsEndOffset(){return this.getEndSearchSpace().length-this.endOffset}setBackwardsEndOffset(e){this.endOffset=this.getEndSearchSpace().length-e}backwardsPrefixOffset(){return this.prefixOffset==null?null:this.getPrefixSearchSpace().length-this.prefixOffset}setBackwardsPrefixOffset(e){this.prefixOffset!=null&&(this.prefixOffset=this.getPrefixSearchSpace().length-e)}};class hr{constructor(e,t){this.textFound=!1,this.textNodes=[],this.textInBlock=null,this.searchRange=e,this.isForwardTraversal=t}appendNode(e){if(this.textInBlock!==null)return;if(Z(e)){this.textFound?(this.isForwardTraversal||this.textNodes.reverse(),this.textInBlock=this.textNodes.map(i=>i.textContent).join("").trim()):this.textNodes=[];return}if(!Un(e))return;const t=this.getNodeIntersectionWithRange(e);this.textFound=this.textFound||(t.textContent??"").trim()!=="",this.textNodes.push(t)}getNodeIntersectionWithRange(e){let t=null,i=null;const s=(e.textContent??"").length;return e===this.searchRange.startContainer&&this.searchRange.startOffset!==0&&(t=this.searchRange.startOffset),e===this.searchRange.endContainer&&this.searchRange.endOffset!==s&&(i=this.searchRange.endOffset),t!==null||i!==null?{textContent:(e.textContent??"").substring(t??0,i??s)}:e}}const dr=(n,e,t)=>nr(n,e,t).length===1,gt=n=>[...n||""].reverse().join(""),Ll=n=>n.toString().length>Al?!1:!_l(n),Ye=n=>{let e=n.startContainer;return e.nodeType==Node.ELEMENT_NODE&&n.startOffset<e.childNodes.length&&(e=e.childNodes[n.startOffset]),e},$t=n=>{let e=n.endContainer;return e.nodeType==Node.ELEMENT_NODE&&n.endOffset>0&&(e=e.childNodes[n.endOffset-1]),e},$l=n=>{const e=Ye(n);if(Un(e)&&k.isNodeVisible(e))return e;const t=k.makeTextNodeWalker(n);return t.currentNode=e,t.nextNode()},Ml=n=>{const e=$t(n);if(Un(e)&&k.isNodeVisible(e))return e;const t=k.makeTextNodeWalker(n);return t.currentNode=e,k.backwardTraverse(t,new Set)},_l=n=>{const e=n.cloneRange();let t=Ye(e);const i=ue(t);if(!i)return!1;const s=new Set;for(;!e.collapsed&&t!=null;){if(Z(t))return!0;t!=null&&e.setStartAfter(t),t=k.forwardTraverse(i,s),L()}return!1},Oi=(n,e)=>{if(n.nodeType!==Node.TEXT_NODE)return-1;const t=n,i=e??t.data.length;if(i<t.data.length&&k.BOUNDARY_CHARS.test(t.data[i]))return i;const s=t.data.substring(0,i),r=gt(s).search(k.BOUNDARY_CHARS);return r!==-1?i-r:-1},Bl=(n,e)=>{if(n.nodeType!==Node.TEXT_NODE)return-1;const t=n,i=e??0;if(i<t.data.length&&i>0&&k.BOUNDARY_CHARS.test(t.data[i-1]))return i;const s=t.data.substring(i).search(k.BOUNDARY_CHARS);return s!==-1?i+s:-1},ue=(n,e)=>{if(!n)return;let t=n;const i=e??n;for(;!t.contains?.(i)||!Z(t);)t.parentNode&&(t=t.parentNode);const s=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:r=>k.acceptNodeIfVisibleInRange(r)});return s.currentNode=n,s},Ul=n=>{const e=k.makeNewSegmenter(n.startContainer.ownerDocument??void 0);if(e){const t=Ye(n);t!==n.startContainer&&n.setStartBefore(t),fr(e,!1,n)}else{const t=Oi(n.startContainer,n.startOffset);if(t!==-1){n.setStart(n.startContainer,t);return}if(Z(n.startContainer)&&n.startOffset===0)return;const i=ue(n.startContainer);if(!i)return;const s=new Set;let r=k.backwardTraverse(i,s);for(;r!=null;){const o=Oi(r);if(o!==-1){n.setStart(r,o);return}if(Z(r)){r.contains?.(n.startContainer)?n.setStart(r,0):n.setStartAfter(r);return}r=k.backwardTraverse(i,s),n.collapse()}}},zl=n=>{const e=$l(n);if(e==null){n.collapse();return}Ye(n)!==e&&n.setStart(e,0);const t=$t(n),i=Ml(n);t!==i&&n.setEnd(i,(i.textContent??"").length)},fr=(n,e,t)=>{const i=e?{node:t.endContainer,offset:t.endOffset}:{node:t.startContainer,offset:t.startOffset},s=Vl(i.node);if(!s)return;const r=s.preNodes.reduce((g,p)=>g.concat(p.textContent??""),""),o=s.innerNodes.reduce((g,p)=>g.concat(p.textContent??""),"");let a=r.length;i.node.nodeType===Node.TEXT_NODE?a+=i.offset:e&&(a+=o.length);const l=s.postNodes.reduce((g,p)=>g.concat(p.textContent??""),""),c=[...s.preNodes,...s.innerNodes,...s.postNodes];if(c.length==0)return;const u=r.concat(o,l),h=n.segment(u).containing(a);if(!h){e?t.setEndAfter(c[c.length-1]):t.setEndBefore(c[0]);return}if(!h.isWordLike||a===h.index||a===h.index+h.segment.length)return;const d=e?h.index+h.segment.length:h.index;let f=0;for(const g of c){const p=(g.textContent??"").length;if(f<=d&&d<f+p){const m=d-f;e?m>=p?t.setEndAfter(g):t.setEnd(g,m):m>=p?t.setStartAfter(g):t.setStart(g,m);return}f+=p}e?t.setEndAfter(c[c.length-1]):t.setStartBefore(c[0])},Vl=n=>{const e=[],t=ue(n);if(!t)return;const i=new Set;let s=k.backwardTraverse(t,i);for(;s!=null&&!Z(s);)L(),s.nodeType===Node.TEXT_NODE&&e.push(s),s=k.backwardTraverse(t,i);e.reverse();const r=[];if(n.nodeType===Node.TEXT_NODE)r.push(n);else{const u=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>k.acceptNodeIfVisibleInRange(d)});u.currentNode=n;let h=u.nextNode();for(;h!=null;)L(),h.nodeType===Node.TEXT_NODE&&r.push(h),h=u.nextNode()}const o=[],a=ue(n);if(!a)return;const l=new Set([n]);let c=k.forwardTraverse(a,l);for(;c!=null&&!Z(c);)L(),c.nodeType===Node.TEXT_NODE&&o.push(c),c=k.forwardTraverse(a,l);return{preNodes:e,innerNodes:r,postNodes:o}},jl=n=>{const e=k.makeNewSegmenter(n.endContainer.ownerDocument??void 0);if(e){const t=$t(n);t!==n.endContainer&&n.setEndAfter(t),fr(e,!0,n)}else{let t=n.endOffset,i=n.endContainer;i.nodeType===Node.ELEMENT_NODE&&n.endOffset<i.childNodes.length&&(i=i.childNodes[n.endOffset]);const s=ue(i);if(!s)return;const r=new Set([i]);for(;i!=null;){L();const o=Bl(i,t);if(t=null,o!==-1){n.setEnd(i,o);return}if(Z(i)){i.contains?.(n.endContainer)?n.setEnd(i,i.childNodes.length):n.setEndBefore(i);return}i=k.forwardTraverse(s,r)}n.collapse()}},Z=n=>n.nodeType===Node.ELEMENT_NODE&&(k.BLOCK_ELEMENTS.includes(n.tagName.toUpperCase())||n.tagName.toUpperCase()==="HTML"||n.tagName.toUpperCase()==="BODY"),Un=n=>n.nodeType===Node.TEXT_NODE;function hn(n){return n.otherLocations?.get("cssSelector")}function Hl(n){return Xs.deserialize(n.otherLocations?.get("domRange"))}function ql(n){for(const e of n.fragments){const t=Sl(e);if(t)return t}}let te=class gr{constructor(e){this.fragments=e.fragments?e.fragments:new Array,this.progression=e.progression,this.totalProgression=e.totalProgression,this.position=e.position,this.otherLocations=e.otherLocations}static deserialize(e){if(!e)return;const t=ft(e.progression),i=ft(e.totalProgression),s=ft(e.position),r=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,l])=>{o.has(a)||r.set(a,l)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,l)=>r.set(l,a)),new gr({fragments:ul(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:s!==void 0&&s>0?s:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,i)=>e[i]=t),e}},zn=class pr{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new pr({after:e.after,before:e.before,highlight:e.highlight})}serialize(){const e={};return this.after!==void 0&&(e.after=this.after),this.before!==void 0&&(e.before=this.before),this.highlight!==void 0&&(e.highlight=this.highlight),e}},Vn=class dn{constructor(e){const t=e.href.indexOf("#"),i=t>=0?e.href.slice(t+1):void 0;this.href=t>=0?e.href.slice(0,t):e.href,this.type=e.type,this.title=e.title;const s=e.locations?.fragments,r=i&&(!s||s.length===0);this.locations=e.locations?r?new te({...e.locations,fragments:[i]}):e.locations:i?new te({fragments:[i]}):new te({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new dn({href:e.href,type:e.type,title:e.title,locations:te.deserialize(e.locations),text:zn.deserialize(e.text)})}serialize(){const e={href:this.href,type:this.type};return this.title!==void 0&&(e.title=this.title),this.locations&&(e.locations=this.locations.serialize()),this.text&&(e.text=this.text.serialize()),e}copyWithLocations(e){return new dn({href:this.href,type:this.type,title:this.title,text:this.text,locations:new te({...this.locations,...e})})}};function Ti(n){return n.split("").reverse().join("")}function Wl(n,e,t){const i=Ti(e);return t.map(s=>{const r=Math.max(0,s.end-e.length-s.errors),o=Ti(n.slice(r,s.end));return{start:mr(o,i,s.errors).reduce((a,l)=>s.end-l.end<a?s.end-l.end:a,s.end),end:s.end,errors:s.errors}})}function Xt(n){return(n|-n)>>31&1}function Ni(n,e,t,i){let s=n.P[t],r=n.M[t];const o=i>>>31,a=e[t]|o,l=a|r,c=(a&s)+s^s|a;let u=r|~(c|s),h=s&c;const d=Xt(u&n.lastRowMask[t])-Xt(h&n.lastRowMask[t]);return u<<=1,h<<=1,h|=o,u|=Xt(i)-o,s=h|~(l|u),r=u&l,n.P[t]=s,n.M[t]=r,d}function mr(n,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const i=[],s=32,r=Math.ceil(e.length/s)-1,o={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};o.lastRowMask.fill(1<<31),o.lastRowMask[r]=1<<(e.length-1)%s;const a=new Uint32Array(r+1),l=new Map,c=[];for(let d=0;d<256;d++)c.push(a);for(let d=0;d<e.length;d+=1){const f=e.charCodeAt(d);if(l.has(f))continue;const g=new Uint32Array(r+1);l.set(f,g),f<c.length&&(c[f]=g);for(let p=0;p<=r;p+=1){g[p]=0;for(let m=0;m<s;m+=1){const v=p*s+m;v>=e.length||e.charCodeAt(v)===f&&(g[p]|=1<<m)}}}let u=Math.max(0,Math.ceil(t/s)-1);const h=new Uint32Array(r+1);for(let d=0;d<=u;d+=1)h[d]=(d+1)*s;h[r]=e.length;for(let d=0;d<=u;d+=1)o.P[d]=-1,o.M[d]=0;for(let d=0;d<n.length;d+=1){const f=n.charCodeAt(d);let g;f<c.length?g=c[f]:(g=l.get(f),typeof g>"u"&&(g=a));let p=0;for(let m=0;m<=u;m+=1)p=Ni(o,g,m,p),h[m]+=p;if(h[u]-p<=t&&u<r&&(g[u+1]&1||p<0)){u+=1,o.P[u]=-1,o.M[u]=0;let m;if(u===r){const v=e.length%s;m=v===0?s:v}else m=s;h[u]=h[u-1]+m-p+Ni(o,g,u,p)}else for(;u>0&&h[u]>=t+s;)u-=1;u===r&&h[u]<=t&&(h[u]<t&&i.splice(0,i.length),i.push({start:-1,end:d+1,errors:h[u]}),t=h[u])}return i}function Kl(n,e,t){const i=mr(n,e,t);return Wl(n,e,i)}function Sr(n,e,t){let i=0;const s=[];for(;i!==-1;)i=n.indexOf(e,i),i!==-1&&(s.push({start:i,end:i+e.length,errors:0}),i+=1);return s.length>0?s:Kl(n,e,t)}function Di(n,e){return e.length===0||n.length===0?0:1-Sr(n,e,e.length)[0].errors/e.length}function Gl(n,e,t={}){if(e.length===0)return null;const i=Math.min(256,e.length/2),s=Sr(n,e,i);if(s.length===0)return null;const r=a=>{const l=1-a.errors/e.length,c=t.prefix?Di(n.slice(Math.max(0,a.start-t.prefix.length),a.start),t.prefix):1,u=t.suffix?Di(n.slice(a.end,a.end+t.suffix.length),t.suffix):1;let h=1;return typeof t.hint=="number"&&(h=1-Math.abs(a.start-t.hint)/n.length),(50*l+20*c+20*u+2*h)/92},o=s.map(a=>({start:a.start,end:a.end,score:r(a)}));return o.sort((a,l)=>l.score-a.score),o[0]}function fn(n,e,t){const i=t===1?e:e-1;if(n.charAt(i).trim()!=="")return e;let s,r;if(t===2?(s=n.substring(0,e),r=s.trimEnd()):(s=n.substring(e),r=s.trimStart()),!r.length)return-1;const o=s.length-r.length;return t===2?e-o:e+o}function Pi(n,e){const t=n.commonAncestorContainer.ownerDocument.createNodeIterator(n.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=e===1?n.startContainer:n.endContainer,s=e===1?n.endContainer:n.startContainer;let r=t.nextNode();for(;r&&r!==i;)r=t.nextNode();e===2&&(r=t.previousNode());let o=-1;const a=()=>{if(r=e===1?t.nextNode():t.previousNode(),r){const l=r.textContent,c=e===1?0:l.length;o=fn(l,c,e)}};for(;r&&o===-1&&r!==s;)a();if(r&&o>=0)return{node:r,offset:o};throw new RangeError("No text nodes with non-whitespace text found in range")}function Xl(n){if(!n.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(n.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(n.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=n.cloneRange();let t=!1,i=!1;const s={start:fn(n.startContainer.textContent,n.startOffset,1),end:fn(n.endContainer.textContent,n.endOffset,2)};if(s.start>=0&&(e.setStart(n.startContainer,s.start),t=!0),s.end>0&&(e.setEnd(n.endContainer,s.end),i=!0),t&&i)return e;if(!t){const{node:r,offset:o}=Pi(e,1);r&&o>=0&&e.setStart(r,o)}if(!i){const{node:r,offset:o}=Pi(e,2);r&&o>0&&e.setEnd(r,o)}return e}function yr(n){switch(n.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return n.textContent?.length??0;default:return 0}}function Fi(n){let e=n.previousSibling,t=0;for(;e;)t+=yr(e),e=e.previousSibling;return t}function vr(n,...e){let t=e.shift();const i=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),s=[];let r=i.nextNode(),o,a=0;for(;t!==void 0&&r;)o=r,a+o.data.length>t?(s.push({node:o,offset:t-a}),t=e.shift()):(r=i.nextNode(),a+=o.data.length);for(;t!==void 0&&o&&a===t;)s.push({node:o,offset:o.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return s}let at=class me{constructor(e,t){if(t<0)throw new Error("Offset is invalid");this.element=e,this.offset=t}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let t=this.element,i=this.offset;for(;t!==e;)i+=Fi(t),t=t.parentElement;return new me(t,i)}resolve(e={}){try{return vr(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const s=e.direction===1,r=s?i.nextNode():i.previousNode();if(!r)throw t;return{node:r,offset:s?0:r.data.length}}else throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return me.fromPoint(e,t);case Node.ELEMENT_NODE:return new me(e,t);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,t){switch(e.nodeType){case Node.TEXT_NODE:{if(t<0||t>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent");const i=Fi(e)+t;return new me(e.parentElement,i)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let s=0;s<t;s++)i+=yr(e.childNodes[s]);return new me(e,i)}default:throw new Error("Point is not in an element or text node")}}},gn=class ze{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new ze(this.start.relativeTo(e),this.end.relativeTo(e))}toRange(){let e,t;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[e,t]=vr(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const i=new Range;return i.setStart(e.node,e.offset),i.setEnd(t.node,t.offset),i}static fromRange(e){const t=at.fromPoint(e.startContainer,e.startOffset),i=at.fromPoint(e.endContainer,e.endOffset);return new ze(t,i)}static fromOffsets(e,t,i){return new ze(new at(e,t),new at(e,i))}static trimmedRange(e){return Xl(ze.fromRange(e).toRange())}},Jl=class pn{constructor(e,t,i){this.root=e,this.start=t,this.end=i}static fromRange(e,t){const i=gn.fromRange(t).relativeTo(e);return new pn(e,i.start.offset,i.end.offset)}static fromSelector(e,t){return new pn(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return gn.fromOffsets(this.root,this.start,this.end).toRange()}},Yl=class mn{constructor(e,t,i={}){this.root=e,this.exact=t,this.context=i}static fromRange(e,t){const i=e.textContent,s=gn.fromRange(t).relativeTo(e),r=s.start.offset,o=s.end.offset,a=32;return new mn(e,i.slice(r,o),{prefix:i.slice(Math.max(0,r-a),r),suffix:i.slice(o,Math.min(i.length,o+a))})}static fromSelector(e,t){const{prefix:i,suffix:s}=t;return new mn(e,t.exact,{prefix:i,suffix:s})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const t=this.root.textContent,i=Gl(t,this.exact,{...this.context,hint:e.hint});if(!i)throw new Error("Quote not found");return new Jl(this.root,i.start,i.end)}};function Ql(n){const e=n.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Ii(n,e){const t=e&&hn(e);let i=null;if(t)try{i=n.querySelector(t)}catch(s){console.warn(`Invalid cssSelector: ${t}`,s)}return i??n.body??n.documentElement}function Li(n,e){let t;try{t=n.querySelector(e.cssSelector)}catch(s){return console.error(`Invalid domRange cssSelector: ${e.cssSelector}`,s),null}if(!t)return console.error(`Can't resolve domRange cssSelector: ${e.cssSelector}`),null;let i=0;for(const s of t.childNodes)if(s.nodeType===Node.TEXT_NODE){if(i===e.textNodeIndex)return{node:s,offset:e.charOffset};i++}return console.error(`Can't resolve domRange textNodeIndex ${e.textNodeIndex} for selector: ${e.cssSelector}`),null}function Zl(n,e){try{const t=e.locations,i=e.text;if(t){const s=Hl(t);if(s){const r=Li(n,s.start),o=s.end?Li(n,s.end):r;if(r&&o)try{const a=n.createRange();return r.offset!==void 0?a.setStart(r.node,r.offset):a.setStartBefore(r.node),o.offset!==void 0?a.setEnd(o.node,o.offset):a.setEndBefore(o.node),a}catch(a){console.warn("Invalid domRange, falling back:",a)}}}if(t){const s=ql(t);if(s){const r=Ii(n,t),o=nr(s,n,r);if(o.length>0)return o[0]}}if(i&&i.highlight){const s=Ii(n,t),r=new Yl(s,i.highlight,{prefix:i.before,suffix:i.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(t){let s=null;if(!s&&hn(t)&&(s=n.querySelector(hn(t))),!s&&t.fragments){for(const r of t.fragments)if(s=n.getElementById(r),s)break}if(s){const r=n.createRange();return s.childNodes.length===0||Ql(s)?(r.selectNode(s),r):(r.setStartBefore(s),r.setEndAfter(s),r)}}}catch(t){console.error(t)}return null}function ec(n,e){const t=e.map(l=>l.toUpperCase()),i=[],s=n.commonAncestorContainer,r=s.nodeType===Node.TEXT_NODE?s.parentNode:s,o=n.startContainer.ownerDocument.createTreeWalker(r,NodeFilter.SHOW_TEXT);let a=o.nextNode();for(;a;){if(n.intersectsNode(a)){let l=a.parentNode,c=!1;for(;l;){if(l.nodeType===Node.ELEMENT_NODE&&t.includes(l.tagName.toUpperCase())){c=!0;break}l=l.parentNode}if(!c){const u=n.cloneRange();u.selectNode(a),u.compareBoundaryPoints(Range.START_TO_START,n)<0&&u.setStart(n.startContainer,n.startOffset),u.compareBoundaryPoints(Range.END_TO_END,n)>0&&u.setEnd(n.endContainer,n.endOffset);for(const h of u.getClientRects())i.push({left:h.left,right:h.right,top:h.top,bottom:h.bottom,width:h.width,height:h.height})}}a=o.nextNode()}return i}function $e(n,e,t=!1,i=0){let s;if(Array.isArray(n))s=n;else{let c=n.getClientRects();c.length||n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(c=n.commonAncestorContainer.getClientRects()),s=[];for(const u of c)s.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.width})}if(i)for(const c of s)c.left-=i,c.top-=i,c.right+=i,c.bottom+=i,c.width+=i*2,c.height+=i*2;const r=br(s,1,e,t),o=nc(r,1),a=wr(o),l=4;for(let c=a.length-1;c>=0;c--){const u=a[c];if(!(u.width*u.height>l))if(a.length>1)a.splice(c,1);else break}return a}function br(n,e,t,i=!1){for(let s=0;s<n.length;s++)for(let r=s+1;r<n.length;r++){const o=n[s],a=n[r];if(o===a)continue;const l=B(o.top,a.top,e)&&B(o.bottom,a.bottom,e),c=B(o.left,a.left,e)&&B(o.right,a.right,e);if((c&&!t&&!i||l&&!c)&&xr(o,a,e)){const u=n.filter(d=>d!==o&&d!==a),h=tc(o,a);return u.push(h),br(u,e,t,i)}}return n}function tc(n,e){const t=Math.min(n.left,e.left),i=Math.max(n.right,e.right),s=Math.min(n.top,e.top),r=Math.max(n.bottom,e.bottom);return{bottom:r,height:r-s,left:t,right:i,top:s,width:i-t}}function nc(n,e){const t=new Set(n);for(const i of n){if(!(i.width>1&&i.height>1)){t.delete(i);continue}for(const s of n)if(i!==s&&t.has(s)&&ic(s,i,e)){t.delete(i);break}}return Array.from(t)}function ic(n,e,t){return Q(n,e.left,e.top,t)&&Q(n,e.right,e.top,t)&&Q(n,e.left,e.bottom,t)&&Q(n,e.right,e.bottom,t)}function Q(n,e,t,i){return(n.left<e||B(n.left,e,i))&&(n.right>e||B(n.right,e,i))&&(n.top<t||B(n.top,t,i))&&(n.bottom>t||B(n.bottom,t,i))}function wr(n){for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){const i=n[e],s=n[t];if(i!==s&&xr(i,s,-1)){let r=[],o;const a=$i(i,s);if(a.length===1)r=a,o=i;else{const c=$i(s,i);a.length<c.length?(r=a,o=i):(r=c,o=s)}const l=n.filter(c=>c!==o);return Array.prototype.push.apply(l,r),wr(l)}}return n}function $i(n,e){const t=sc(e,n);if(t.height===0||t.width===0)return[n];const i=[];{const s={bottom:n.bottom,height:0,left:n.left,right:t.left,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:t.top,height:0,left:t.left,right:t.right,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:n.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}{const s={bottom:n.bottom,height:0,left:t.right,right:n.right,top:n.top,width:0};s.width=s.right-s.left,s.height=s.bottom-s.top,s.height!==0&&s.width!==0&&i.push(s)}return i}function sc(n,e){const t=Math.max(n.left,e.left),i=Math.min(n.right,e.right),s=Math.max(n.top,e.top),r=Math.min(n.bottom,e.bottom);return{bottom:r,height:Math.max(0,r-s),left:t,right:i,top:s,width:Math.max(0,i-t)}}function xr(n,e,t){return(n.left<e.right||t>=0&&B(n.left,e.right,t))&&(e.left<n.right||t>=0&&B(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&B(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&B(e.top,n.bottom,t))}function B(n,e,t){return Math.abs(n-e)<=t}const Mi=["div","span","p","br","hr","b","i","em","strong","s","u","mark","small","sub","sup","abbr","cite","code","data","dfn","kbd","q","samp","time","var","blockquote","pre","svg","g","path","circle","ellipse","rect","line","polygon","polyline","text","tspan","defs","use"],rc=/^on/i,oc=new Set(["href","src","action","formaction","xlink:href"]),ac=/^\s*(javascript|data):/i;function lc(n,e){const t=n.document.createElement("div");if("Sanitizer"in n&&typeof t.setHTML=="function")try{const s=new n.Sanitizer({allowElements:Mi});return t.setHTML(e,{sanitizer:s}),t.firstElementChild}catch{}const i=n.document.implementation.createHTMLDocument("");for(i.body.innerHTML=e,cc(i.body,new Set(Mi));i.body.firstChild;)t.appendChild(n.document.adoptNode(i.body.firstChild));return t.firstElementChild}function cc(n,e){const t=Array.from(n.querySelectorAll("*")).reverse();for(const i of t){if(!e.has(i.localName)){i.replaceWith(...Array.from(i.childNodes));continue}for(const{name:s,value:r}of Array.from(i.attributes))(rc.test(s)||oc.has(s)&&ac.test(r))&&i.removeAttribute(s)}}function Jt(n){switch(n){case E.Mask:return"rgba(255, 255, 255, 0.5)";case E.Highlight:case E.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const E={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var Er=(n=>(n.Wrap="wrap",n.Viewport="viewport",n.Bounds="bounds",n.Page="page",n))(Er||{}),Cr=(n=>(n.Boxes="boxes",n.Bounds="bounds",n))(Cr||{});const uc=()=>"Highlight"in window,_i=["IMG","IMAGE","AUDIO","VIDEO","SVG"],hc=new Set(["SUP","SUB","SMALL","CODE"]);class dc{constructor(e,t,i,s){this.wnd=e,this.comms=t,this.id=i,this.name=s,this.items=[],this.lastItemId=0,this.container=void 0,this._activatable=!1,this._hoverable=!1,this.hoveredItem=void 0,this.experimentalHighlights=!1,this._tintSubKeys=new Map,this._subKeyCounter=0,this.pendingWebkitReflow=null,this.maskSvg=void 0,this.shadowHost=void 0,this.shadowRoot=void 0,this.currentRender=0,uc()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map),this.activationHandler=this.handleActivation.bind(this),this.wnd.document.addEventListener("pointerup",this.activationHandler),this.hoverHandler=this.handleHover.bind(this),this.wnd.document.addEventListener("pointermove",this.hoverHandler)}get activatable(){return this._activatable}set activatable(e){this._activatable=e}get hoverable(){return this._hoverable}get hasOverlayItems(){return!this.experimentalHighlights||(this.notTextFlag?.size??0)>0}set hoverable(e){if(this._hoverable=e,!e&&this.hoveredItem){const t=this.hoveredItem.range.getBoundingClientRect(),i=this.wnd.devicePixelRatio;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:{top:t.top*i,left:t.left*i,width:t.width*i,height:t.height*i}}),this.hoveredItem=void 0}}add(e){const t=`${this.id}-${this.lastItemId++}`,i=Zl(this.wnd.document,e.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",e);return}const s=i.commonAncestorContainer;if(s.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(_i.includes(s.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),i.cloneContents().querySelector(_i.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(s.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0)),this.experimentalHighlights&&!this.notTextFlag?.has(t)){const o=a=>{for(;a&&a.nodeType===Node.ELEMENT_NODE;){if(a.namespaceURI?.includes("svg"))return!0;a=a.parentNode}return!1};(o(i.startContainer)||o(i.endContainer))&&this.notTextFlag?.set(t,!0)}if(this.experimentalHighlights){const{type:o}=e.style,{layout:a,width:l,expand:c}=e.style;o!==E.TextColor&&(o===E.Outline||o===E.Template||o===E.Mask||a!==void 0&&a!=="boxes"||l!==void 0&&l!=="wrap"||c)&&this.notTextFlag?.set(t,!0)}const r={decoration:e,id:t,range:i,hitRects:[],clickableElements:void 0,container:void 0};this.items.push(r),this.layout(r),r.hitRects=this.clientRectsToDocCoords($e(r.range,!1,!1,(r.decoration.style.expand??0)+this.hitGap())),this.renderLayout([r])}remove(e){const t=this.items.findIndex(r=>r.decoration.id===e);if(t<0)return;const i=this.items[t],s=i.decoration.style?.type===E.Mask;if(this.items.splice(t,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&i.highlightSubKey){const r=this.wnd.CSS.highlights;r.get(i.highlightSubKey)?.delete(i.range),this.items.some(a=>a.highlightSubKey===i.highlightSubKey)||r.delete(i.highlightSubKey);const o=this.wnd.document.getElementById(`${this.id}-style`);o&&this._rebuildHighlightStylesheet(o),this.scheduleWebkitRepaintFix([i])}this.notTextFlag?.delete(i.id),this.hoveredItem===i&&(this.hoveredItem=void 0),s&&this.updateSharedMask()}update(e){this.remove(e.id),this.add(e)}clear(){this.experimentalHighlights&&this.scheduleWebkitRepaintFix(this.items),this.clearContainer(),this.items.length=0,this.notTextFlag?.clear(),this.hoveredItem=void 0,this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&(this.shadowHost.remove(),this.shadowHost=void 0,this.shadowRoot=void 0)}destroy(){this.clear(),this.wnd.document.removeEventListener("pointerup",this.activationHandler),this.wnd.document.removeEventListener("pointermove",this.hoverHandler)}isWebkitRepaintProne(e){const t=this.wnd.getComputedStyle(e);if(hc.has(e.tagName.toUpperCase())||t.display==="inline-block"||t.verticalAlign!=="baseline")return!0;const i=e.parentElement?this.wnd.getComputedStyle(e.parentElement):null;return!!i&&parseFloat(t.fontSize)!==parseFloat(i.fontSize)}findWebkitRepaintProneElement(e){let t=e.startContainer.nodeType===Node.ELEMENT_NODE?e.startContainer:e.startContainer.parentElement;for(;t;){if(this.isWebkitRepaintProne(t))return t;if(this.wnd.getComputedStyle(t).display!=="inline")break;t=t.parentElement}const i=e.commonAncestorContainer,s=i.nodeType===Node.ELEMENT_NODE?i:i.parentElement;if(!s)return null;const r=this.wnd.document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,o=>e.intersectsNode(o)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT);for(let o=r.nextNode();o;o=r.nextNode())if(this.isWebkitRepaintProne(o))return o;return null}forceWebkitBlockReflow(e){let t=e;for(;t;){const o=this.wnd.getComputedStyle(t).display;if(o!=="inline"&&o!=="inline-block")break;t=t.parentElement}if(!t||!t.isConnected)return;const i=t,s=i.style.getPropertyValue("transform"),r=i.style.getPropertyPriority("transform");i.style.setProperty("transform","translateZ(0.001px)","important"),i.offsetHeight,i.style.setProperty("transform","translateZ(0px)","important"),i.offsetHeight,s?i.style.setProperty("transform",s,r):i.style.removeProperty("transform")}scheduleWebkitRepaintFix(e){if(bi.UA.WebKit)for(const t of e){if(this.notTextFlag?.has(t.id)||!t.highlightSubKey)continue;const i=this.findWebkitRepaintProneElement(t.range);i&&this.queueWebkitReflow(i)}}queueWebkitReflow(e){this.pendingWebkitReflow||(this.pendingWebkitReflow=new Set,this.wnd.requestAnimationFrame(()=>{const t=this.pendingWebkitReflow;this.pendingWebkitReflow=null,t?.forEach(i=>this.forceWebkitBlockReflow(i))})),this.pendingWebkitReflow.add(e)}clientRectsToDocCoords(e,t=de(this.wnd)){const i=t.xDocOffset,s=t.yDocOffset;return i===0&&s===0?e:e.map(r=>({left:r.left+i,top:r.top+s,right:r.right+i,bottom:r.bottom+s,width:r.width,height:r.height}))}pointerToDocCoords(e){const t=de(this.wnd);return{docX:e.clientX+t.xDocOffset,docY:e.clientY+t.yDocOffset}}effectiveZoom(){if(!bi.UA.Blink)return 1;const e=parseFloat(this.wnd.getComputedStyle(this.wnd.document.documentElement).zoom),t=parseFloat(this.wnd.getComputedStyle(this.wnd.document.body).zoom);return(e||1)*(t||1)}hitGap(){return 2*this.effectiveZoom()}handleActivation(e){if(!this._activatable)return;const{docX:t,docY:i}=this.pointerToDocCoords(e),s=this.wnd.devicePixelRatio;for(const r of this.items){let o;if(r.decoration.style.type===E.Template)for(const a of r.clickableElements??[]){const l=a.getBoundingClientRect();if(Q(l,e.clientX,e.clientY,0)){o=l;break}}else for(const a of r.hitRects)if(Q(a,t,i,0)){o=r.range.getBoundingClientRect();break}if(o){this.comms.send("decoration_activated",{decorationId:r.decoration.id,group:this.name,rect:{top:o.top*s,left:o.left*s,width:o.width*s,height:o.height*s},point:{x:e.clientX*s,y:e.clientY*s}});return}}}handleHover(e){if(!this._hoverable)return;const{docX:t,docY:i}=this.pointerToDocCoords(e),s=this.wnd.devicePixelRatio;let r,o;for(const a of this.items){if(a.decoration.style.type===E.Template)for(const l of a.clickableElements??[]){const c=l.getBoundingClientRect();if(Q(c,e.clientX,e.clientY,0)){r=a,o=c;break}}else for(const l of a.hitRects)if(Q(l,t,i,0)){r=a,o=a.range.getBoundingClientRect();break}if(r)break}if(r!==this.hoveredItem){if(this.hoveredItem){const a=this.hoveredItem.range.commonAncestorContainer.isConnected?this.hoveredItem.range.getBoundingClientRect():null;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:a?{top:a.top*s,left:a.left*s,width:a.width*s,height:a.height*s}:void 0,point:{x:e.clientX*s,y:e.clientY*s}})}this.hoveredItem=r,r&&o&&this.comms.send("decoration_pointer_enter",{decorationId:r.decoration.id,group:this.name,rect:{top:o.top*s,left:o.left*s,width:o.width*s,height:o.height*s},point:{x:e.clientX*s,y:e.clientY*s}})}}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.wnd.document.fonts.ready.then(()=>{this.currentRender=this.wnd.requestAnimationFrame(()=>{this.items.forEach(e=>{this.layout(e),e.hitRects=this.clientRectsToDocCoords($e(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}repositionOverlays(){let e=!1;const t=[],i=de(this.wnd);this.items.forEach(s=>{if(!(this.experimentalHighlights&&!this.notTextFlag?.has(s.id))){if(s.decoration.style?.type===E.Mask){e=!0;return}this.repositionItem(s,i)||(s.container?.remove(),this.layout(s),t.push(s)),s.hitRects=this.clientRectsToDocCoords($e(s.range,!1,!1,(s.decoration.style.expand??0)+this.hitGap()),i)}}),t.length&&this.renderLayout(t),e&&this.updateSharedMask()}experimentalLayout(e){const t=this.requireContainer(!0),i=this.wnd.CSS.highlights,s=e.decoration.style,r=s.type??E.Highlight,o=s.tint??Jt(r),a=s.width,l=s.layout,c=this._getSubKey(r,o);e.highlightSubKey&&(i.get(e.highlightSubKey)?.delete(e.range),e.highlightSubKey!==c&&!this.items.some(p=>p!==e&&p.highlightSubKey===e.highlightSubKey)&&i.delete(e.highlightSubKey)),e.highlightSubKey=c;let u;i.has(c)?u=i.get(c):(u=new this.wnd.Highlight,i.set(c,u));const h=(p,m)=>this.wnd.document.caretPositionFromPoint?.(p,m)??null;if(r===E.TextColor&&(l==="bounds"||a==="bounds"||a==="page")){const p=de(this.wnd);if(p.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),u.add(e.range);else{const m=e.range.getBoundingClientRect();let v,w;a==="page"?(v=Math.floor(p.inlineStart(m)/p.pageInlineSize)*p.pageInlineSize,w=p.pageInlineSize):(v=p.inlineStart(m),w=p.inlineSize(m));const S=h(v,p.blockStart(m)+1),y=h(v+w,p.blockStart(m)+p.blockSize(m)-1);if(S&&y){const b=this.wnd.document.createRange();b.setStart(S.offsetNode,S.offset),b.setEnd(y.offsetNode,y.offset),u.add(b),e.range=b}else u.add(e.range)}}else u.add(e.range);const d=this.getBackgroundColor(),f=s.enforceContrast!==!1?ge(o,d):o;let g;switch(r){case E.Underline:g=`::highlight(${c}) {
|
|
2
2
|
text-decoration: underline;
|
|
3
3
|
text-decoration-color: ${f};
|
|
4
4
|
text-decoration-thickness: 0.1em;
|
|
@@ -11,14 +11,14 @@
|
|
|
11
11
|
outline-offset: 1px;
|
|
12
12
|
}`;break;case E.TextColor:g=`::highlight(${c}) {
|
|
13
13
|
color: ${f};
|
|
14
|
-
}`;break;case E.HighlightUnderline:{const{r:p,g:m,b:
|
|
15
|
-
color: ${
|
|
14
|
+
}`;break;case E.HighlightUnderline:{const{r:p,g:m,b:v}=ce(f),w=`rgba(${p}, ${m}, ${v}, 0.3)`;g=`::highlight(${c}) {
|
|
15
|
+
color: ${vi(f,d)};
|
|
16
16
|
background-color: ${w};
|
|
17
17
|
text-decoration: underline;
|
|
18
18
|
text-decoration-color: ${f};
|
|
19
19
|
text-decoration-thickness: 0.1em;
|
|
20
20
|
}`;break}case E.Highlight:default:g=`::highlight(${c}) {
|
|
21
|
-
color: ${
|
|
21
|
+
color: ${vi(f,d)};
|
|
22
22
|
background-color: ${f};
|
|
23
23
|
}`}e.highlightCSS=g,this._rebuildHighlightStylesheet(t)}_getSubKey(e,t){const i=`${e}::${t}`;let s=this._tintSubKeys.get(i);return s||(s=`${this.id}--${this._subKeyCounter++}`,this._tintSubKeys.set(i,s)),s}_rebuildHighlightStylesheet(e){const t=new Set,i=[];for(const s of this.items)s.highlightSubKey&&s.highlightCSS&&!t.has(s.highlightSubKey)&&(t.add(s.highlightSubKey),i.push(s.highlightCSS));e.innerHTML=i.join(`
|
|
24
|
-
`)}positionElement(e,t,i,s,r,o,a=0){const l=e.decoration?.style?.width,c=r;switch(l){case"viewport":{const u=Math.floor(t.inlineStart(c)/t.viewportInlineSize)*t.viewportInlineSize;t.applyPosition(s,u+t.inlineScrollOffset+a,t.blockStart(c)+t.blockScrollOffset,t.viewportInlineSize-2*a,t.blockSize(c),i);break}case"page":{const u=Math.floor(t.inlineStart(c)/t.pageInlineSize)*t.pageInlineSize;t.applyPosition(s,u+t.inlineScrollOffset+a,t.blockStart(c)+t.blockScrollOffset,t.pageInlineSize-2*a,t.blockSize(c),i);break}case"bounds":{t.applyPosition(s,t.inlineStart(o)+t.inlineScrollOffset,t.blockStart(c)+t.blockScrollOffset,t.inlineSize(o),t.blockSize(c),i);break}default:t.applyPosition(s,t.inlineStart(c)+t.inlineScrollOffset,t.blockStart(c)+t.blockScrollOffset,t.inlineSize(c),t.blockSize(c),i)}}computeOverlayRects(e,t,i,s){if(e.decoration?.style?.layout==="bounds")return[s?{left:i.left-s,right:i.right+s,top:i.top-s,bottom:i.bottom+s,width:i.width+s*2,height:i.height+s*2}:i];const r=e.decoration.style.type,o=r===E.Underline||r===E.Strikethrough,a=r===E.Strikethrough,l=o?ec(e.range,["rt","rp"]):e.range;let c=$e(l,!0,t.isVertical,o?0:s);return c=c.sort((u,h)=>t.isVertical?(t.isVertLR?1:-1)*(u.left-h.left):u.top-h.top),c.map(u=>{let h=u;if(a){const d=t.blockSize(u)*.1,f=t.blockStart(u)+t.blockSize(u)/2-d/2;h=t.isVertical?{left:f,right:f+d,top:u.top,bottom:u.bottom,width:d,height:u.height}:{top:f,bottom:f+d,left:u.left,right:u.right,height:d,width:u.width}}return s&&o&&(h=t.isVertical?{...h,top:h.top-s,bottom:h.bottom+s,height:h.height+s*2}:{...h,left:h.left-s,right:h.right+s,width:h.width+s*2}),h})}repositionItem(e,t){if(!e.container)return!0;const i=e.decoration.style;if(i.type!==E.Template){const u=i.type??E.Highlight;if(u===E.TextColor||u===E.Mask)return!0}const s=1/this.effectiveZoom(),r=i.expand??0,o=e.range.getBoundingClientRect(),a=(()=>{if(i.type!==E.Outline)return 0;const u=i.width;return u==="page"||u==="viewport"?3:0})(),l=this.computeOverlayRects(e,t,o,r),c=Array.from(e.container.children);return c.length!==l.length?!1:(c.forEach((u,h)=>this.positionElement(e,t,s,u,l[h],o,a)),!0)}layout(e){if(this.experimentalHighlights&&!this.notTextFlag?.has(e.id))return this.experimentalLayout(e);const t=this.wnd.document.createElement("div");t.setAttribute("id",e.id),t.dataset.highlightId=e.decoration.id,t.style.setProperty("pointer-events","none");const i=de(this.wnd),s=1/this.effectiveZoom(),r=e.decoration.style.expand??0,o=e.range.getBoundingClientRect(),a=e.decoration.style,l=(()=>{if(a.type!==E.Outline)return 0;const h=a.width;return h==="page"||h==="viewport"?3:0})();let c;if(a.type===E.Template){a.stylesheet&&this.injectCustomStylesheet(a.stylesheet);const h=lc(this.wnd,a.element);if(!h){e.container=t,e.clickableElements=[];return}h.style.setProperty("pointer-events","none"),c=h}else{const h=a,d=h.type??E.Highlight,f=h.tint??Jt(d);if(d===E.TextColor){e.container=t,e.clickableElements=[];return}if(d===E.Mask){e.container=t,e.clickableElements=[],this.updateSharedMask();return}const g=this.getCurrentDarkMode(),p=this.getBackgroundColor(),m=h.enforceContrast!==!1,y=(()=>{switch(d){case E.Underline:{const S=m?ge(f,p):f,v=h.layout==="bounds",[b,C]=i.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[v?`${C}: 0.1em solid ${S} !important`:null,`${b}: 0.1em solid ${S} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case E.Strikethrough:{const S=m?ge(f,p):f;return h.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${S} 19px, ${S} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${S} !important`,"box-sizing: border-box !important"].join("; ")}case E.Outline:return[`outline: 2px solid ${m?ge(f,p):f} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case E.HighlightUnderline:{const S=m?ge(f,p):f,{r:v,g:b,b:C}=ce(S),R=`rgba(${v}, ${b}, ${C}, 0.3)`,A=h.layout==="bounds",[N,O]=i.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${R} !important`,A?`${O}: 0.1em solid ${S} !important`:null,`${N}: 0.1em solid ${S} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case E.Highlight:default:return[`background-color: ${m?ge(f,p):f} !important`,`mix-blend-mode: ${g?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important","transform: translateZ(0) !important"].join("; ")}})(),w=this.wnd.document.createElement("template");w.innerHTML=`<div data-readium="true" class="readium-${d}" style="${y}"></div>`.trim(),c=w.content.firstElementChild}const u=this.computeOverlayRects(e,i,o,r);for(const h of u){const d=c.cloneNode(!0);d.style.setProperty("pointer-events","none"),this.positionElement(e,i,s,d,h,o,l),t.append(d)}e.container=t,e.clickableElements=Array.from(t.querySelectorAll("[data-activable='1']")),e.clickableElements.length||(e.clickableElements=Array.from(t.children))}renderLayout(e){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{e=e.filter(t=>!this.experimentalHighlights||!!this.notTextFlag?.has(t.id)),!(!e||e.length===0)&&this.requireContainer().append(...e.map(t=>t.container).filter(t=>!!t))})}requireContainer(e=!1){if(e){let t;return this.wnd.document.getElementById(`${this.id}-style`)?t=this.wnd.document.getElementById(`${this.id}-style`):(t=this.wnd.document.createElement("style"),t.dataset.readium="true",t.id=`${this.id}-style`,this.wnd.document.head.appendChild(t)),t}return this.container||(this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.shadowRoot.appendChild(this.container)),this.container}getCurrentDarkMode(){return vi(this.wnd,"--USER__appearance")==="readium-night-on"||Js(this.getBackgroundColor())}getBackgroundColor(){return vi(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(d=>d.decoration.style?.type===E.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&!this.container&&(this.shadowHost.remove(),this.shadowRoot=void 0,this.shadowHost=void 0);return}const t=de(this.wnd),i=1/this.effectiveZoom(),s=this.wnd.document.documentElement,r=s.scrollWidth,o=s.scrollHeight,a=[];for(const d of e){const f=d.decoration.style,g=f.layout??"boxes",p=f.width??"wrap",m=f.expand??0,y=d.range.getBoundingClientRect(),w=g==="bounds"?[m?{left:y.left-m,top:y.top-m,right:y.right+m,bottom:y.bottom+m,width:y.width+m*2,height:y.height+m*2}:y]:$e(d.range,!1,!1,m);for(const S of w){let v;switch(p){case"viewport":{const b=Math.floor(t.inlineStart(S)/t.viewportInlineSize)*t.viewportInlineSize;v=t.toRect(b,t.blockStart(S),t.viewportInlineSize,t.blockSize(S));break}case"page":{const b=Math.floor(t.inlineStart(S)/t.pageInlineSize)*t.pageInlineSize;v=t.toRect(b,t.blockStart(S),t.pageInlineSize,t.blockSize(S));break}case"bounds":{v=t.toRect(t.inlineStart(y),t.blockStart(S),t.inlineSize(y),t.blockSize(S));break}default:v=t.toRect(t.inlineStart(S),t.blockStart(S),t.inlineSize(S),t.blockSize(S))}a.push(v)}}const l=[`M0 0 H${r} V${o} H0 Z`,...a.map(d=>{const f=(d.left+t.xDocOffset)*i,g=(d.top+t.yDocOffset)*i,p=(d.right+t.xDocOffset)*i,m=(d.bottom+t.yDocOffset)*i;return`M${f} ${g} H${p} V${m} H${f} Z`})].join(" "),c="http://www.w3.org/2000/svg";if(!this.maskSvg){this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.maskSvg=this.wnd.document.createElementNS(c,"svg"),this.maskSvg.style.cssText=`position:absolute;top:0;left:0;width:${r}px;height:${o}px;pointer-events:none;z-index:2147483647`,this.maskSvg.dataset.readium="true";const d=this.wnd.document.createElementNS(c,"defs"),f=this.wnd.document.createElementNS(c,"clipPath"),g=`${this.id}-mask-clip`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","userSpaceOnUse");const p=this.wnd.document.createElementNS(c,"path");p.setAttribute("clip-rule","evenodd"),f.appendChild(p),d.appendChild(f),this.maskSvg.appendChild(d);const m=this.wnd.document.createElementNS(c,"rect");m.setAttribute("id",`${this.id}-mask-rect`),m.setAttribute("clip-path",`url(#${g})`),m.style.pointerEvents="none",this.maskSvg.appendChild(m),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${r}px`,this.maskSvg.style.height=`${o}px`;const u=this.maskSvg.querySelector("path");u&&u.setAttribute("d",l);const h=this.maskSvg.querySelector("rect");if(h){const d=e[0].decoration.style.tint,f=d??this.getBackgroundColor()??Jt(E.Mask),g=d?"1":"0.5";h.setAttribute("x","0"),h.setAttribute("y","0"),h.setAttribute("width",String(r)),h.setAttribute("height",String(o)),h.setAttribute("fill",f),h.setAttribute("fill-opacity",g)}}injectCustomStylesheet(e){const t=`${this.id}-custom-style`;let i=this.wnd.document.getElementById(t);i||(i=this.wnd.document.createElement("style"),i.id=t,i.dataset.readium="true",this.wnd.document.head.appendChild(i)),i.innerHTML=e}clearContainer(){if(this.experimentalHighlights){const e=this.wnd.CSS.highlights;for(const t of this._tintSubKeys.values())e.delete(t);this._tintSubKeys.clear(),this._subKeyCounter=0}this.wnd.document.getElementById(`${this.id}-custom-style`)?.remove(),this.container&&(this.container.remove(),this.container=void 0)}}const Cr=class Se extends rl{constructor(){super(...arguments),this.observedResizeTargets=new Map,this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this),this.scrollScheduled=!1,this.handleScroller=this.handleScroll.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear(),this.observedResizeTargets.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>e.requestLayout())},50)}handleScroll(){this.scrollScheduled||(this.scrollScheduled=!0,this.wnd.requestAnimationFrame(()=>{this.scrollScheduled=!1,this.groups.forEach(e=>{e.hasOverlayItems&&e.repositionOverlays()})}))}mount(e,t){return this.wnd=e,t.register("decorate",Se.moduleName,(i,s)=>{const r=i;(r.action==="add"||r.action==="update")&&r.decoration.locator&&(r.decoration.locator=Vn.deserialize(r.decoration.locator)),this.groups.has(r.group)||this.groups.set(r.group,new hc(e,t,`readium-decoration-${this.lastGroupId++}`,r.group));const o=this.groups.get(r.group);switch(r.action){case"add":o?.add(r.decoration);break;case"remove":o?.remove(r.decoration.id);break;case"clear":o?.clear();break;case"update":o?.update(r.decoration);break}s(!0)}),t.register("decoration_resize",Se.moduleName,(i,s)=>{const r=i;r.action==="watch"?this.addDecorationResizeTarget(r.selector):this.removeDecorationResizeTarget(r.selector),s(!0)}),t.register("decoration_activatable",Se.moduleName,(i,s)=>{const r=i,o=this.groups.get(r.group);o&&(o.activatable=r.activatable),s(!0)}),t.register("decoration_hoverable",Se.moduleName,(i,s)=>{const r=i,o=this.groups.get(r.group);o&&(o.hoverable=r.hoverable),s(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.documentElement),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),e.addEventListener("scroll",this.handleScroller,{passive:!0,capture:!0}),this.styleObserver=new MutationObserver(i=>{i.some(s=>s.type==="attributes"&&s.attributeName==="style"&&s.oldValue!==s.target.getAttribute("style"))&&this.updateHighlightStyles()}),this.styleObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0}),t.log("Decorator Mounted"),!0}unmount(e,t){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),e.removeEventListener("scroll",this.handleScroller,{capture:!0}),t.unregisterAll(Se.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}addDecorationResizeTarget(e){const t=this.observedResizeTargets.get(e);t&&this.resizeObserver.unobserve(t);const i=this.wnd.document.querySelector(e);i?(this.resizeObserver.observe(i),this.observedResizeTargets.set(e,i)):this.observedResizeTargets.delete(e)}removeDecorationResizeTarget(e){const t=this.observedResizeTargets.get(e);t&&(this.resizeObserver.unobserve(t),this.observedResizeTargets.delete(e))}};Cr.moduleName="decorator";let kr=Cr;const Rr=new Set(Object.values(E));function Ar(n,e){return n===E.TextColor?typeof window<"u"&&"Highlight"in window:Rr.has(n)?!0:!!e?.[n]}function Sn(n,e){const{style:t}=n;if(t.type===E.Template){const i=t;return{...n,style:{...i,element:_i(i,n)}}}if(t.type&&e?.[t.type]){const i=e[t.type];return{...n,style:{type:E.Template,layout:i.layout,width:i.width,stylesheet:i.stylesheet,element:_i(i,n)}}}return n}function _i(n,e){return typeof n.element=="function"?n.element(e):n.element}function dc(n,e){if(n.type!==e.type)return!1;if(n.type===E.Template){const s=n,r=e;return s.layout===r.layout&&s.width===r.width&&s.stylesheet===r.stylesheet}const t=n,i=e;return t.tint===i.tint&&t.layout===i.layout&&t.width===i.width&&(t.enforceContrast??!0)===(i.enforceContrast??!0)&&(t.expand??0)===(i.expand??0)}function Or(n,e){return n.locator.href===e.locator.href&&JSON.stringify(n.locator.locations?.serialize?.()??n.locator.locations)===JSON.stringify(e.locator.locations?.serialize?.()??e.locator.locations)&&JSON.stringify(n.locator.text??null)===JSON.stringify(e.locator.text??null)&&dc(n.style,e.style)&&JSON.stringify(n.extras??null)===JSON.stringify(e.extras??null)}class Tr{constructor(){this.queue=[],this.channel=typeof MessageChannel<"u"?new MessageChannel:void 0,this.channel&&(this.channel.port1.onmessage=()=>this.flush())}push(e){const t=this.queue.length===0;this.queue.push(e),t&&(this.channel?this.channel.port2.postMessage(null):setTimeout(()=>this.flush(),0))}flush(){const e=this.queue;this.queue=[],e.forEach(t=>t())}clear(){this.queue=[]}}class Nr{constructor(){this.frame=new Dr(this),this.host=new Pr(this)}}class Dr{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new Tr,this.ready=!0}register(e,t,i){(Array.isArray(e)?e:[e]).forEach(s=>{const r=this.registrar.get(s)??[];if(r.find(o=>o.module===t))throw new Error(`Duplicate callback for "${s}" in module "${t}"`);r.push({module:t,cb:i}),this.registrar.set(s,r)})}unregister(e,t){(Array.isArray(e)?e:[e]).forEach(i=>{const s=this.registrar.get(i);s&&this.registrar.set(i,s.filter(r=>r.module!==t))})}unregisterAll(e){this.registrar.forEach((t,i)=>{this.registrar.set(i,t.filter(s=>s.module!==e))})}_dispatch(e,t,i){const s=this.registrar.get(e);if(!s?.length){i(!1);return}s.forEach(r=>r.cb(t,i))}send(e,t){this.outbox.push(()=>this.channel.host._receive(e,t))}log(...e){this.outbox.push(()=>this.channel.host._receive("log",e))}destroy(){this.registrar.clear(),this.outbox.clear()}}class Pr{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new Tr,this.ready=!0}send(e,t,i){this.outbox.push(()=>this.channel.frame._dispatch(e,t,i??(()=>{})))}on(e,t){const i=this.listeners.get(e)??[];i.push(t),this.listeners.set(e,i)}off(e,t){const i=this.listeners.get(e);i&&this.listeners.set(e,i.filter(s=>s!==t))}_receive(e,t){this.listeners.get(e)?.forEach(i=>i(t))}}class Fr{constructor(e,t={}){this.host=e,this._decorations=new Map,this._activationState=new Map,this._hoverState=new Map,this._observers=new Map,this._hoveredDecorations=new Map,this._config=t,t.resizeWatchSelectors?.forEach(i=>this.addDecorationResizeTarget(i)),e.on("decoration_activated",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId);r&&this._observers.get(s.group)?.forEach(o=>o.onDecorationActivated?.({group:s.group,decoration:r,rect:s.rect,point:s.point}))}),e.on("decoration_pointer_enter",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId);r&&(this._hoveredDecorations.set(s.group,r),this._observers.get(s.group)?.forEach(o=>o.onDecorationPointerEnter?.({group:s.group,decoration:r,rect:s.rect,point:s.point})))}),e.on("decoration_pointer_leave",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId)??this._hoveredDecorations.get(s.group);this._hoveredDecorations.delete(s.group),r&&this._observers.get(s.group)?.forEach(o=>o.onDecorationPointerLeave?.({group:s.group,decoration:r,rect:s.rect,point:s.point}))})}addDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"watch",selector:e})}removeDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"unwatch",selector:e})}supportsDecorationStyle(e){return Ar(e,this._config.decorationTemplates)}applyDecorations(e,t){const i=this._decorations.get(t)??[],s=new Map(i.map(l=>[l.id,l])),r=new Map(e.map(l=>[l.id,l]));for(const[l,c]of s){const u=r.get(l);u?Or(c,u)||this.host.send("decorate",{group:t,action:"update",decoration:Sn(u,this._config.decorationTemplates)}):this.host.send("decorate",{group:t,action:"remove",decoration:{id:l}})}for(const[l,c]of r)s.has(l)||this.host.send("decorate",{group:t,action:"add",decoration:Sn(c,this._config.decorationTemplates)});this._decorations.set(t,e);const o=this._activationState.get(t);o!==void 0&&this.host.send("decoration_activatable",{group:t,activatable:o});const a=this._hoverState.get(t);a!==void 0&&this.host.send("decoration_hoverable",{group:t,hoverable:a})}registerDecorationObserver(e,t){this._observers.has(e)||this._observers.set(e,new Set),this._observers.get(e).add(t),t.onDecorationActivated&&(this._activationState.set(e,!0),this.host.send("decoration_activatable",{group:e,activatable:!0})),(t.onDecorationPointerEnter||t.onDecorationPointerLeave)&&(this._hoverState.set(e,!0),this.host.send("decoration_hoverable",{group:e,hoverable:!0}))}unregisterDecorationObserver(e){this._observers.forEach((t,i)=>{if(!t.has(e))return;t.delete(e);const s=[...t].some(o=>o.onDecorationActivated);this._activationState.has(i)&&!s&&(this._activationState.delete(i),this.host.send("decoration_activatable",{group:i,activatable:!1}));const r=[...t].some(o=>o.onDecorationPointerEnter||o.onDecorationPointerLeave);this._hoverState.has(i)&&!r&&(this._hoverState.delete(i),this.host.send("decoration_hoverable",{group:i,hoverable:!1}))})}destroy(){this._decorations.clear(),this._activationState.clear(),this._hoverState.clear(),this._observers.clear(),this._hoveredDecorations.clear()}}function fc(n){return new Gs({start:new St(n.start),end:n.end?new St(n.end):void 0})}function Ir(n,e=window){const{text:t,cssSelector:i,domRange:s,fragment:r}=n,o=t?new zn(t):void 0,a=i||s?new Map:void 0;a&&(i&&a.set("cssSelector",i),s&&a.set("domRange",fc(s).serialize()));const c=a!==void 0||r!==void 0?new te({fragments:r?[r]:void 0,otherLocations:a}):void 0;return new Vn({href:e.location.href,type:"text/html",text:o,locations:c})}class Lr extends Fr{constructor(e,t,i,s={}){super(e.host,s),this.channel=e,this.wnd=t,this.decorator=i}decorate(e,t){this.applyDecorations(e.map(({id:i,style:s,...r})=>({id:i,style:s,locator:Ir(r,this.wnd)})),t)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function gc(n=window,e={}){const t=new Nr,i=new kr;return i.mount(n,t.frame),new Lr(t,n,i,e)}class pc{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`A provider is already registered under id "${e.id}"`);this.providers.set(e.id,e)}unregister(e){this.providers.delete(e)}get(e){return this.providers.get(e)}list(){return[...this.providers.values()]}async getVoices(e){return this.require(e).getVoices()}async getAllVoices(){return Promise.all(this.list().map(async e=>({providerId:e.id,voices:await e.getVoices()})))}async createEngine(e,t){return this.require(e).createEngine(t)}async destroy(){await Promise.all(this.list().map(e=>e.destroy())),this.providers.clear()}require(e){const t=this.providers.get(e);if(!t)throw new Error(`No provider registered under id "${e}"`);return t}}const yt={range:[0,5e3],step:100},bt={range:[.1,10],step:.1},wt={range:[0,2],step:.1},xt={range:[0,1],step:.05},jn=["none","few","some","most","custom"],Hn=["none","block-level","always"],qn=["plain","ssml"],Wn=["none","utterance","block"],Kn=["structure","sentence"],Bi=["format","inlineContextualization","verbosity","skip","contextualize","language","segmentation"];function Gn(n){return n==null||typeof n=="boolean"?n:void 0}function z(n,e){return n==null||e.includes(n)?n:void 0}function J(n,e){if(n==null)return n;if(typeof n!="number"||Number.isNaN(n))return;const t=Math.min(...e),i=Math.max(...e);return n>=t&&n<=i?n:void 0}function We(n){return n==null||Array.isArray(n)&&n.every(e=>typeof e=="string")?n:void 0}class $r{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=z(e.format,qn)??"plain",this.inlineContextualization=Gn(e.inlineContextualization)??!1,this.verbosity=z(e.verbosity,jn)??"few",this.skip=We(e.skip)??[],this.contextualize=We(e.contextualize)??[],this.language=z(e.language,Hn)??"block-level",this.segmentation=z(e.segmentation,Kn)??"structure",this.pauseDuration=J(e.pauseDuration,yt.range)??300,this.autoPause=z(e.autoPause,Wn)??"none",this.rate=J(e.rate,bt.range)??1,this.pitch=J(e.pitch,wt.range)??1,this.volume=J(e.volume,xt.range)??1}}class Re{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=z(e.format,qn),this.inlineContextualization=Gn(e.inlineContextualization),this.verbosity=z(e.verbosity,jn),this.skip=We(e.skip),this.contextualize=We(e.contextualize),this.language=z(e.language,Hn),this.segmentation=z(e.segmentation,Kn),this.pauseDuration=J(e.pauseDuration,yt.range),this.autoPause=z(e.autoPause,Wn),this.rate=J(e.rate,bt.range),this.pitch=J(e.pitch,wt.range),this.volume=J(e.volume,xt.range)}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new Re(t)}}class Qe{_value;_effectiveValue;_isEffective;_onChange;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s}){this._value=e,this._effectiveValue=t,this._isEffective=i,this._onChange=s}set value(e){this._value=e,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null,this._onChange(this._value)}}class ve extends Qe{_supportedValues;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s,supportedValues:r}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:s}),this._supportedValues=r}set value(e){if(e!=null&&z(e,this._supportedValues)===void 0)throw new Error(`Value '${String(e)}' is not in the supported values for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedValues(){return this._supportedValues}}class Mr extends Qe{set value(e){if(e!=null&&Gn(e)===void 0)throw new Error(`Value '${String(e)}' is not a boolean.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class vn extends Qe{set value(e){if(e!=null&&We(e)===void 0)throw new Error(`Value '${String(e)}' is not an array of strings.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Ve extends Qe{_supportedRange;_step;_decimals;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s,supportedRange:r,step:o}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:s}),this._supportedRange=r,this._step=o,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e!=null&&J(e,this._supportedRange)===void 0)throw new Error(`Value '${String(e)}' is out of the supported range for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value!=null&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value!=null&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(e){return e.toString()}}class yn{preferences;settings;constructor(e,t){this.preferences=new Re({...e}),this.settings=t}clear(){this.preferences=new Re({format:null,inlineContextualization:null,verbosity:null,skip:null,contextualize:null,language:null,segmentation:null,pauseDuration:null,autoPause:null,rate:null,pitch:null,volume:null})}updatePreference(e,t){this.preferences[e]=t}get format(){return new ve({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:qn})}get inlineContextualization(){return new Mr({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new ve({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:jn})}get skip(){return new vn({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new vn({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new ve({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:Hn})}get segmentation(){return new ve({initialValue:this.preferences.segmentation,effectiveValue:this.settings.segmentation,isEffective:this.preferences.segmentation!=null,onChange:e=>this.updatePreference("segmentation",e??null),supportedValues:Kn})}get pauseDuration(){return new Ve({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:yt.range,step:yt.step})}get autoPause(){return new ve({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:Wn})}get rate(){return new Ve({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:bt.range,step:bt.step})}get pitch(){return new Ve({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:wt.range,step:wt.step})}get volume(){return new Ve({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:xt.range,step:xt.step})}}const _r=["audio","figure","image","math","table","video"],Br=[..._r,"blockquote","chapter","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],mc=[...Br,"abstract","acknowledgments","afterword","appendix","aside","backlink","bibliography","biblioref","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","glossref","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","noteref","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],Ur={none:new Set(["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"]),few:new Set(["aside","bibliography","biblioref","cell","columnheader","details","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","toc"]),some:new Set(["aside","bibliography","biblioref","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","toc"]),most:new Set(["landmarks","loa","loi","lot","lov","toc"])},zr={none:new Set,few:new Set(_r),some:new Set(Br),most:new Set(mc)},bn={table:{few:"inline",some:"block",most:"block"}};function lt(n){const e={};for(const t of Object.keys(bn))e[t]=bn[t]?.[n]??"inline";return e}const Vr={none:lt("none"),few:lt("few"),some:lt("some"),most:lt("most")},Sc=Object.keys(bn);function vc(n,e){const t=n==="custom"?{}:Vr[n];if(!e)return t;const i={...t};for(const s of Object.keys(e)){const r=e[s]?.[n];r&&(i[s]=r)}return i}class wn{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e,t){this.format=e.format??t.format,this.inlineContextualization=e.inlineContextualization??t.inlineContextualization,this.verbosity=e.verbosity??t.verbosity,this.verbosity==="custom"?(this.skip=e.skip??t.skip,this.contextualize=e.contextualize??t.contextualize):(this.skip=[...Ur[this.verbosity]],this.contextualize=[...zr[this.verbosity]]),this.language=e.language??t.language,this.segmentation=e.segmentation??t.segmentation,this.pauseDuration=e.pauseDuration??t.pauseDuration,this.autoPause=e.autoPause??t.autoPause,this.rate=e.rate??t.rate,this.pitch=e.pitch??t.pitch,this.volume=e.volume??t.volume}}const Ui=new WeakMap,jr=new WeakMap;function zi(n,e){jr.set(n,e)}const Hr=new WeakSet;function Vi(n){return Hr.add(n),n}function qr(n,e,t){const i=jr.get(n);if(i){const u=gi(i.map,e),h=gi(i.map,e+t);e=u,t=Math.max(0,h-u)}const s=n.offsets,r=!n.plain&&!!n.ssml,o=i?.plain??n.plain??(n.ssml?le(n.ssml):"");if(!s?.length||!o)return;const a=Ui.get(n),l=a!==void 0&&e>=a.cursor;let c=l?a.cursor:0;for(let u=l?a.pieceIndex:0;u<s.length;u++){const h=s[u],d=h.locate.text?.highlight,f=d?r?le(d):d:o.slice(c);if(!f)continue;const g=o.indexOf(f,c);if(g===-1)continue;const p=g+f.length;if(e>=g&&e<p){if(Hr.has(h.locate))return;Ui.set(n,{pieceIndex:u,cursor:c});const m=e-g,y=f.substring(m,Math.min(m+t,f.length));return{locate:{...h.locate,domRange:void 0,text:{highlight:y,before:f.substring(0,m),after:f.substring(m+y.length)}},word:y}}c=p}}function Wr(n,e){return e==="sentence"&&n.offsets?.length?n.offsets.map(t=>t.locate):n.locate?[n.locate]:[]}const x=n=>typeof n=="string",Me=()=>{let n,e;const t=new Promise((i,s)=>{n=i,e=s});return t.resolve=n,t.reject=e,t},ji=n=>n==null?"":String(n),yc=(n,e,t)=>{n.forEach(i=>{e[i]&&(t[i]=e[i])})},bc=/###/g,Hi=n=>n&&n.includes("###")?n.replace(bc,"."):n,qi=n=>!n||x(n),je=(n,e,t)=>{const i=x(e)?e.split("."):e;let s=0;for(;s<i.length-1;){if(qi(n))return{};const r=Hi(i[s]);!n[r]&&t&&(n[r]=new t),Object.prototype.hasOwnProperty.call(n,r)?n=n[r]:n={},++s}return qi(n)?{}:{obj:n,k:Hi(i[s])}},Wi=(n,e,t)=>{const{obj:i,k:s}=je(n,e,Object);if(i!==void 0||e.length===1){i[s]=t;return}let r=e[e.length-1],o=e.slice(0,e.length-1),a=je(n,o,Object);for(;a.obj===void 0&&o.length;)r=`${o[o.length-1]}.${r}`,o=o.slice(0,o.length-1),a=je(n,o,Object),a?.obj&&typeof a.obj[`${a.k}.${r}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${r}`]=t},wc=(n,e,t,i)=>{const{obj:s,k:r}=je(n,e,Object);s[r]=s[r]||[],s[r].push(t)},Et=(n,e)=>{const{obj:t,k:i}=je(n,e);if(t&&Object.prototype.hasOwnProperty.call(t,i))return t[i]},xc=(n,e,t)=>{const i=Et(n,t);return i!==void 0?i:Et(e,t)},Kr=(n,e,t)=>{for(const i in e)i!=="__proto__"&&i!=="constructor"&&(Object.prototype.hasOwnProperty.call(n,i)?x(n[i])||n[i]instanceof String||x(e[i])||e[i]instanceof String?t&&(n[i]=e[i]):Kr(n[i],e[i],t):n[i]=e[i]);return n},W=n=>n.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),Ec={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},Cc=n=>x(n)?n.replace(/[&<>"'\/]/g,e=>Ec[e]):n;class kc{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(t!==void 0)return t;const i=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,i),this.regExpQueue.push(e),i}}const Rc=[" ",",","?","!",";"],Ac=new kc(20),Oc=(n,e,t)=>{e=e||"",t=t||"";const i=Rc.filter(o=>!e.includes(o)&&!t.includes(o));if(i.length===0)return!0;const s=Ac.getRegExp(`(${i.map(o=>o==="?"?"\\?":o).join("|")})`);let r=!s.test(n);if(!r){const o=n.indexOf(t);o>0&&!s.test(n.substring(0,o))&&(r=!0)}return r},xn=(n,e,t=".")=>{if(!n)return;if(n[e])return Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0;const i=e.split(t);let s=n;for(let r=0;r<i.length;){if(!s||typeof s!="object")return;let o,a="";for(let l=r;l<i.length;++l)if(l!==r&&(a+=t),a+=i[l],o=s[a],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&l<i.length-1)continue;r+=l-r+1;break}s=o}return s},Ke=n=>n?.replace(/_/g,"-"),Tc={type:"logger",log(n){this.output("log",n)},warn(n){this.output("warn",n)},error(n){this.output("error",n)},output(n,e){console?.[n]?.apply?.(console,e)}};class Ct{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Tc,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,i,s){return s&&!this.debug?null:(e=e.map(r=>x(r)?r.replace(/[\r\n\x00-\x1F\x7F]/g," "):r),x(e[0])&&(e[0]=`${i}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Ct(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ct(this.logger,e)}}var q=new Ct;class Mt{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(i=>{this.observers[i]||(this.observers[i]=new Map);const s=this.observers[i].get(t)||0;this.observers[i].set(t,s+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}once(e,t){const i=(...s)=>{t(...s),this.off(e,i)};return this.on(e,i),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,r])=>{for(let o=0;o<r;o++)s(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,r])=>{for(let o=0;o<r;o++)s(e,...t)})}}class Ki extends Mt{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,i,s={}){const r=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,o=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.includes(".")?a=e.split("."):(a=[e,t],i&&(Array.isArray(i)?a.push(...i):x(i)&&r?a.push(...i.split(r)):a.push(i)));const l=Et(this.data,a);return!l&&!t&&!i&&e.includes(".")&&(e=a[0],t=a[1],i=a.slice(2).join(".")),l||!o||!x(i)?l:xn(this.data?.[e]?.[t],i,r)}addResource(e,t,i,s,r={silent:!1}){const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let a=[e,t];i&&(a=a.concat(o?i.split(o):i)),e.includes(".")&&(a=e.split("."),s=t,t=a[1]),this.addNamespaces(t),Wi(this.data,a,s),r.silent||this.emit("added",e,t,i,s)}addResources(e,t,i,s={silent:!1}){for(const r in i)(x(i[r])||Array.isArray(i[r]))&&this.addResource(e,t,r,i[r],{silent:!0});s.silent||this.emit("added",e,t,i)}addResourceBundle(e,t,i,s,r,o={silent:!1,skipCopy:!1}){let a=[e,t];e.includes(".")&&(a=e.split("."),s=i,i=t,t=a[1]),this.addNamespaces(t);let l=Et(this.data,a)||{};o.skipCopy||(i=JSON.parse(JSON.stringify(i))),s?Kr(l,i,r):l={...l,...i},Wi(this.data,a,l),o.silent||this.emit("added",e,t,i)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(s=>t[s]&&Object.keys(t[s]).length>0)}toJSON(){return this.data}}var Gr={processors:{},addPostProcessor(n){this.processors[n.name]=n},handle(n,e,t,i,s){return n.forEach(r=>{e=this.processors[r]?.process(e,t,i,s)??e}),e}};const Xr=Symbol("i18next/PATH_KEY");function Nc(){const n=[],e=Object.create(null);let t;return e.get=(i,s)=>(t?.revoke?.(),s===Xr?n:(n.push(s),t=Proxy.revocable(i,e),t.proxy)),Proxy.revocable(Object.create(null),e).proxy}function we(n,e){const{[Xr]:t}=n(Nc()),i=e?.keySeparator??".",s=e?.nsSeparator??":",r=e?.enableSelector==="strict";if(t.length>1&&s){const o=e?.ns,a=r?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(a&&(r?a:a.length>1?a.slice(1):[]).includes(t[0]))return`${t[0]}${s}${t.slice(1).join(i)}`}return t.join(i)}const Yt=n=>!x(n)&&typeof n!="boolean"&&typeof n!="number";class kt extends Mt{constructor(e,t={}){super(),yc(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=q.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const i={...t};if(e==null)return!1;const s=this.resolve(e,i);if(s?.res===void 0)return!1;const r=Yt(s.res);return!(i.returnObjects===!1&&r)}extractFromKey(e,t){let i=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;i===void 0&&(i=":");const s=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let r=t.ns||this.options.defaultNS||[];const o=i&&e.includes(i),a=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!Oc(e,i,s);if(o&&!a){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:x(r)?[r]:r};const c=e.split(i);(i!==s||i===s&&this.options.ns.includes(c[0]))&&(r=c.shift()),e=c.join(s)}return{key:e,namespaces:x(r)?[r]:r}}translate(e,t,i){let s=typeof t=="object"?{...t}:t;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=we(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(P=>typeof P=="function"?we(P,{...this.options,...s}):String(P));const r=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(e[e.length-1],s),c=l[l.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const h=s.lng||this.language,d=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return d?r?{res:`${c}${u}${a}`,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:`${c}${u}${a}`:r?{res:a,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:a;const f=this.resolve(e,s);let g=f?.res;const p=f?.usedKey||a,m=f?.exactUsedKey||a,y=["[object Number]","[object Function]","[object RegExp]"],w=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,v=s.count!==void 0&&!x(s.count),b=kt.hasDefaultValue(s),C=v?this.pluralResolver.getSuffix(h,s.count,s):"",R=s.ordinal&&v?this.pluralResolver.getSuffix(h,s.count,{ordinal:!1}):"",A=v&&!s.ordinal&&s.count===0,N=A&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${C}`]||s[`defaultValue${R}`]||s.defaultValue;let O=g;S&&!g&&b&&(O=N);const tt=Yt(O),he=Object.prototype.toString.apply(O);if(S&&O&&tt&&!y.includes(he)&&!(x(w)&&Array.isArray(O))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const P=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,O,{...s,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return r?(f.res=P,f.usedParams=this.getUsedParamsDetails(s),f):P}if(o){const P=Array.isArray(O),$=P?[]:{},De=P?m:p;for(const V in O)if(Object.prototype.hasOwnProperty.call(O,V)){const j=`${De}${o}${V}`;b&&!g?$[V]=this.translate(j,{...s,defaultValue:Yt(N)?N[V]:void 0,joinArrays:!1,ns:l}):$[V]=this.translate(j,{...s,joinArrays:!1,ns:l}),$[V]===j&&($[V]=O[V])}g=$}}else if(S&&x(w)&&Array.isArray(g))g=g.join(w),g&&(g=this.extendTranslation(g,e,s,i));else{let P=!1,$=!1;!this.isValidLookup(g)&&b&&(P=!0,g=N),this.isValidLookup(g)||($=!0,g=a);const V=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&$?void 0:g,j=b&&N!==g&&this.options.updateMissing;if($||P||j){if(this.logger.log(j?"updateKey":"missingKey",h,c,v&&!j?`${a}${this.pluralResolver.getSuffix(h,s.count,s)}`:a,j?N:g),o){const M=this.resolve(a,{...s,keySeparator:!1});M&&M.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Pe=[];const nt=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&nt&&nt[0])for(let M=0;M<nt.length;M++)Pe.push(nt[M]);else this.options.saveMissingTo==="all"?Pe=this.languageUtils.toResolveHierarchy(s.lng||this.language):Pe.push(s.lng||this.language);const ri=(M,ee,Fe)=>{const oi=b&&Fe!==g?Fe:V;this.options.missingKeyHandler?this.options.missingKeyHandler(M,c,ee,oi,j,s):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(M,c,ee,oi,j,s),this.emit("missingKey",M,c,ee,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&v?Pe.forEach(M=>{const ee=this.pluralResolver.getSuffixes(M,s);A&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!ee.includes(`${this.options.pluralSeparator}zero`)&&ee.push(`${this.options.pluralSeparator}zero`),ee.forEach(Fe=>{ri([M],a+Fe,s[`defaultValue${Fe}`]||N)})}):ri(Pe,a,N))}g=this.extendTranslation(g,e,s,f,i),$&&g===a&&this.options.appendNamespaceToMissingKey&&(g=`${c}${u}${a}`),($||P)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${u}${a}`:a,P?g:void 0,s))}return r?(f.res=g,f.usedParams=this.getUsedParamsDetails(s),f):g}extendTranslation(e,t,i,s,r){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...i},i.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!i.skipInterpolation){i.interpolation&&this.interpolator.init({...i,interpolation:{...this.options.interpolation,...i.interpolation}});const l=x(e)&&(i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(l){const h=e.match(this.interpolator.nestingRegexp);c=h&&h.length}let u=i.replace&&!x(i.replace)?i.replace:i;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,i.lng||this.language||s.usedLng,i),l){const h=e.match(this.interpolator.nestingRegexp),d=h&&h.length;c<d&&(i.nest=!1)}!i.lng&&s&&s.res&&(i.lng=this.language||s.usedLng),i.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>r?.[0]===h[0]&&!i.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${t[0]}`),null):this.translate(...h,t),i)),i.interpolation&&this.interpolator.reset()}const o=i.postProcess||this.options.postProcess,a=x(o)?[o]:o;return e!=null&&a?.length&&i.applyPostProcessor!==!1&&(e=Gr.handle(a,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(i)},...i}:i,this)),e}resolve(e,t={}){let i,s,r,o,a;return x(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?we(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(i))return;const c=this.extractFromKey(l,t),u=c.key;s=u;let h=c.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const d=t.count!==void 0&&!x(t.count),f=d&&!t.ordinal&&t.count===0,g=t.context!==void 0&&(x(t.context)||typeof t.context=="number")&&t.context!=="",p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);h.forEach(m=>{this.isValidLookup(i)||(a=m,!this.checkedLoadedFor[`${p[0]}-${m}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(this.checkedLoadedFor[`${p[0]}-${m}`]=!0,this.logger.warn(`key "${s}" for languages "${p.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),p.forEach(y=>{if(this.isValidLookup(i))return;o=y;const w=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,u,y,m,t);else{let v;d&&(v=this.pluralResolver.getSuffix(y,t.count,t));const b=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&v.startsWith(C)&&w.push(u+v.replace(C,this.options.pluralSeparator)),w.push(u+v),f&&w.push(u+b)),g){const R=`${u}${this.options.contextSeparator||"_"}${t.context}`;w.push(R),d&&(t.ordinal&&v.startsWith(C)&&w.push(R+v.replace(C,this.options.pluralSeparator)),w.push(R+v),f&&w.push(R+b))}}let S;for(;S=w.pop();)this.isValidLookup(i)||(r=S,i=this.getResource(y,m,S,t))}))})}),{res:i,usedKey:s,exactUsedKey:r,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,i,s={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,i,s):this.resourceStore.getResource(e,t,i,s)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],i=e.replace&&!x(e.replace);let s=i?e.replace:e;if(i&&typeof e.count<"u"&&(s={...s,count:e.count}),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!i){s={...s};for(const r of t)delete s[r]}return s}static hasDefaultValue(e){const t="defaultValue";for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&i.startsWith(t)&&e[i]!==void 0)return!0;return!1}}class Gi{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=q.create("languageUtils"),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=Ke(e),!e||!e.includes("-"))return null;const t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=Ke(e),!e||!e.includes("-"))return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(x(e)&&e.includes("-")){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(i=>{if(t)return;const s=this.formatLanguageCode(i);(!this.options.supportedLngs||this.isSupportedCode(s))&&(t=s)}),!t&&this.options.supportedLngs&&e.forEach(i=>{if(t)return;const s=this.getScriptPartFromCode(i);if(this.isSupportedCode(s))return t=s;const r=this.getLanguagePartFromCode(i);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(o=>o===r?!0:!o.includes("-")&&!r.includes("-")?!1:!!(o.includes("-")&&!r.includes("-")&&o.slice(0,o.indexOf("-"))===r||o.startsWith(r)&&r.length>1))}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),x(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let i=e[t];return i||(i=e[this.getScriptPartFromCode(t)]),i||(i=e[this.formatLanguageCode(t)]),i||(i=e[this.getLanguagePartFromCode(t)]),i||(i=e.default),i||[]}toResolveHierarchy(e,t){const i=this.options.fallbackLng,s=Array.isArray(i)?i.join("|"):i;s!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=s);const r=t===void 0||t===!1||x(t),o=t===void 0&&typeof this.options.fallbackLng=="function",a=x(e)&&r&&!o;let l=null;if(a){let d;t===void 0?d="undefined":t===!1?d="boolean:false":d=`string:${t}`,l=`${e.length}:${e}|${d}`}if(l!==null){const d=this.resolveHierarchyCache[l];if(d!==void 0)return d.slice()}const c=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),u=[],h=d=>{d&&(this.isSupportedCode(d)?u.push(d):this.logger.warn(`rejecting language code not found in supportedLngs: ${d}`))};return x(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&h(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&h(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&h(this.getLanguagePartFromCode(e))):x(e)&&h(this.formatLanguageCode(e)),c.forEach(d=>{u.includes(d)||h(this.formatLanguageCode(d))}),l!==null?(this.resolveHierarchyCache[l]=u,u.slice()):u}}const Xi={zero:0,one:1,two:2,few:3,many:4,other:5},Ji={select:n=>n===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Dc{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=q.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const i=Ke(e==="dev"?"en":e),s=t.ordinal?"ordinal":"cardinal",r=JSON.stringify({cleanedCode:i,type:s});if(r in this.pluralRulesCache)return this.pluralRulesCache[r];let o;try{o=new Intl.PluralRules(i,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Ji;if(!e.match(/-|_/))return Ji;const l=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(l,t)}return this.pluralRulesCache[r]=o,o}needsPlural(e,t={}){let i=this.getRule(e,t);return i||(i=this.getRule("dev",t)),i?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,i={}){return this.getSuffixes(e,i).map(s=>`${t}${s}`)}getSuffixes(e,t={}){let i=this.getRule(e,t);return i||(i=this.getRule("dev",t)),i?i.resolvedOptions().pluralCategories.sort((s,r)=>Xi[s]-Xi[r]).map(s=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,t,i={}){const s=this.getRule(e,i);return s?`${this.options.prepend}${i.ordinal?`ordinal${this.options.prepend}`:""}${s.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,i))}}const Yi=(n,e,t,i=".",s=!0)=>{let r=xc(n,e,t);return!r&&s&&x(t)&&(r=xn(n,t,i),r===void 0&&(r=xn(e,t,i))),r},Pc=n=>n.replace(/\$/g,"$$$$");class Qi{constructor(e={}){this.logger=q.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(t=>t),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:i,useRawValueToEscape:s,prefix:r,prefixEscaped:o,suffix:a,suffixEscaped:l,formatSeparator:c,unescapeSuffix:u,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:g,nestingSuffixEscaped:p,nestingOptionsSeparator:m,maxReplaces:y,alwaysFormat:w}=e.interpolation;this.escape=t!==void 0?t:Cc,this.escapeValue=i!==void 0?i:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=r?W(r):o||"{{",this.suffix=a?W(a):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=u?"":h?W(h):"-",this.unescapeSuffix=this.unescapePrefix?"":u?W(u):"",this.nestingPrefix=d?W(d):f||W("$t("),this.nestingSuffix=g?W(g):p||W(")"),this.nestingOptionsSeparator=m||",",this.maxReplaces=y||1e3,this.alwaysFormat=w!==void 0?w:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(t,i)=>t?.source===i?(t.lastIndex=0,t):new RegExp(i,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,i,s){let r,o,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=f=>{if(!f.includes(this.formatSeparator)){const y=Yi(t,l,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,i,{...s,...t,interpolationkey:f}):y}const g=f.split(this.formatSeparator),p=g.shift().trim(),m=g.join(this.formatSeparator).trim();return this.format(Yi(t,l,p,this.options.keySeparator,this.options.ignoreJSONStructure),m,i,{...s,...t,interpolationkey:p})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=s?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>f},{regex:this.regexp,safeValue:f=>this.escapeValue?this.escape(f):f}].forEach(f=>{for(a=0;r=f.regex.exec(e);){const g=r[1].trim();if(o=c(g),o===void 0)if(typeof u=="function"){const m=u(e,r,s);o=x(m)?m:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))o="";else if(h){o=r[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),o="";else!x(o)&&!this.useRawValueToEscape&&(o=ji(o));const p=f.safeValue(o);if(e=e.replace(r[0],Pc(p)),h?(f.regex.lastIndex+=p.length,f.regex.lastIndex-=r[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,t,i={}){let s,r,o;const a=(l,c)=>{const u=this.nestingOptionsSeparator;if(!l.includes(u))return l;const h=l.split(new RegExp(`${W(u)}[ ]*{`));let d=`{${h[1]}`;l=h[0],d=this.interpolate(d,o);const f=d.match(/'/g),g=d.match(/"/g);((f?.length??0)%2===0&&!g||(g?.length??0)%2!==0)&&(d=d.replace(/'/g,'"'));try{o=JSON.parse(d),c&&(o={...c,...o})}catch(p){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,p),`${l}${u}${d}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,l};for(;s=this.nestingRegexp.exec(e);){let l=[];o={...i},o=o.replace&&!x(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const c=/{.*}/s.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(c!==-1&&(l=s[1].slice(c).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,c)),r=t(a.call(this,s[1].trim(),o),o),r&&s[0]===e&&!x(r))return r;x(r)||(r=ji(r)),r||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),r=""),l.length&&(r=l.reduce((u,h)=>this.format(u,h,i.lng,{...i,interpolationkey:s[1].trim()}),r.trim())),e=e.replace(s[0],r),this.regexp.lastIndex=0}return e}}const Fc=n=>{let e=n.toLowerCase().trim();const t={};if(n.includes("(")){const i=n.split("(");e=i[0].toLowerCase().trim();const s=i[1].slice(0,-1);e==="currency"&&!s.includes(":")?t.currency||(t.currency=s.trim()):e==="relativetime"&&!s.includes(":")?t.range||(t.range=s.trim()):s.split(";").forEach(o=>{if(o){const[a,...l]=o.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();t[u]||(t[u]=c),c==="false"&&(t[u]=!1),c==="true"&&(t[u]=!0),isNaN(c)||(t[u]=parseInt(c,10))}})}return{formatName:e,formatOptions:t}},Zi=n=>{const e={};return(t,i,s)=>{let r=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(r={...r,[s.interpolationkey]:void 0});const o=i+JSON.stringify(r);let a=e[o];return a||(a=n(Ke(i),s),e[o]=a),a(t)}},Ic=n=>(e,t,i)=>n(Ke(t),i)(e);class Lc{constructor(e={}){this.logger=q.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const i=t.cacheInBuiltFormats?Zi:Ic;this.formats={number:i((s,r)=>{const o=new Intl.NumberFormat(s,{...r});return a=>o.format(a)}),currency:i((s,r)=>{const o=new Intl.NumberFormat(s,{...r,style:"currency"});return a=>o.format(a)}),datetime:i((s,r)=>{const o=new Intl.DateTimeFormat(s,{...r});return a=>o.format(a)}),relativetime:i((s,r)=>{const o=new Intl.RelativeTimeFormat(s,{...r});return a=>o.format(a,r.range||"day")}),list:i((s,r)=>{const o=new Intl.ListFormat(s,{...r});return a=>o.format(a)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Zi(t)}format(e,t,i,s={}){if(!t||e==null)return e;const r=t.split(this.formatSeparator),o=[];for(let l=0;l<r.length;l++){let c=r[l];for(;c.indexOf("(")>-1&&!c.includes(")")&&l+1<r.length;)c=`${c}${this.formatSeparator}${r[++l]}`;o.push(c)}return o.reduce((l,c)=>{const{formatName:u,formatOptions:h}=Fc(c);if(this.formats[u]){let d=l;try{const f=s?.formatParams?.[s.interpolationkey]||{},g=f.locale||f.lng||s.locale||s.lng||i;d=this.formats[u](l,g,{...h,...s,...f})}catch(f){this.logger.warn(f)}return d}else this.logger.warn(`there was no format function for ${u}`);return l},e)}}const $c=(n,e)=>{n.pending[e]!==void 0&&(delete n.pending[e],n.pendingCount--)};class Mc extends Mt{constructor(e,t,i,s={}){super(),this.backend=e,this.store=t,this.services=i,this.languageUtils=i.languageUtils,this.options=s,this.logger=q.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(i,s.backend,s)}queueLoad(e,t,i,s){const r={},o={},a={},l={};return e.forEach(c=>{let u=!0;t.forEach(h=>{const d=`${c}|${h}`;!i.reload&&this.store.hasResourceBundle(c,h)?this.state[d]=2:this.state[d]<0||(this.state[d]===1?o[d]===void 0&&(o[d]=!0):(this.state[d]=1,u=!1,o[d]===void 0&&(o[d]=!0),r[d]===void 0&&(r[d]=!0),l[h]===void 0&&(l[h]=!0)))}),u||(a[c]=!0)}),(Object.keys(r).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(r),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(l)}}loaded(e,t,i){const s=e.split("|"),r=s[0],o=s[1];t&&this.emit("failedLoading",r,o,t),!t&&i&&this.store.addResourceBundle(r,o,i,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&i&&(this.state[e]=0);const a={};this.queue.forEach(l=>{wc(l.loaded,[r],o),$c(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{a[c]||(a[c]={});const u=l.loaded[c];u.length&&u.forEach(h=>{a[c][h]===void 0&&(a[c][h]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(l=>!l.done)}read(e,t,i,s=0,r=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:i,tried:s,wait:r,callback:o});return}this.readingCalls++;const a=(c,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const h=this.waitingReads.shift();this.read(h.lng,h.ns,h.fcName,h.tried,h.wait,h.callback)}if(c&&u&&s<this.maxRetries){setTimeout(()=>{this.read(e,t,i,s+1,r*2,o)},r);return}o(c,u)},l=this.backend[i].bind(this.backend);if(l.length===2){try{const c=l(e,t);c&&typeof c.then=="function"?c.then(u=>a(null,u)).catch(a):a(null,c)}catch(c){a(c)}return}return l(e,t,a)}prepareLoading(e,t,i={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();x(e)&&(e=this.languageUtils.toResolveHierarchy(e)),x(t)&&(t=[t]);const r=this.queueLoad(e,t,i,s);if(!r.toLoad.length)return r.pending.length||s(),null;r.toLoad.forEach(o=>{this.loadOne(o)})}load(e,t,i){this.prepareLoading(e,t,{},i)}reload(e,t,i){this.prepareLoading(e,t,{reload:!0},i)}loadOne(e,t=""){const i=e.split("|"),s=i[0],r=i[1];this.read(s,r,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${t}loading namespace ${r} for language ${s} failed`,o),!o&&a&&this.logger.log(`${t}loaded namespace ${r} for language ${s}`,a),this.loaded(e,o,a)})}saveMissing(e,t,i,s,r,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${i}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(i==null||i==="")){if(this.backend?.create){const l={...o,isUpdate:r},c=this.backend.create.bind(this.backend);if(c.length<6)try{let u;c.length===5?u=c(e,t,i,s,l):u=c(e,t,i,s),u&&typeof u.then=="function"?u.then(h=>a(null,h)).catch(a):a(null,u)}catch(u){a(u)}else c(e,t,i,s,a,l)}!e||!e[0]||this.store.addResource(e[0],t,i,s)}}}const Qt=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:n=>{let e={};if(typeof n[1]=="object"&&(e=n[1]),x(n[1])&&(e.defaultValue=n[1]),x(n[2])&&(e.tDescription=n[2]),typeof n[2]=="object"||typeof n[3]=="object"){const t=n[3]||n[2];Object.keys(t).forEach(i=>{e[i]=t[i]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),es=n=>(x(n.ns)&&(n.ns=[n.ns]),x(n.fallbackLng)&&(n.fallbackLng=[n.fallbackLng]),x(n.fallbackNS)&&(n.fallbackNS=[n.fallbackNS]),n.supportedLngs&&!n.supportedLngs.includes("cimode")&&(n.supportedLngs=n.supportedLngs.concat(["cimode"])),n),ct=()=>{},_c=n=>{Object.getOwnPropertyNames(Object.getPrototypeOf(n)).forEach(t=>{typeof n[t]=="function"&&(n[t]=n[t].bind(n))})};class He extends Mt{constructor(e={},t){if(super(),this.options=es(e),this.services={},this.logger=q,this.modules={external:[]},_c(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e=="function"&&(t=e,e={}),e.defaultNS==null&&e.ns&&(x(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const i=Qt();this.options={...i,...this.options,...es(e)},this.options.interpolation={...i.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=i.overloadTranslationOptionHandler);const s=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?q.init(s(this.modules.logger),this.options):q.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=Lc;const u=new Gi(this.options);this.store=new Ki(this.options.resources,this.options);const h=this.services;h.logger=q,h.resourceStore=this.store,h.languageUtils=u,h.pluralResolver=new Dc(u,{prepend:this.options.pluralSeparator}),c&&(h.formatter=s(c),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new Qi(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new Mc(s(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.languageDetector&&(h.languageDetector=s(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=s(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new kt(this.services,this.options),this.translator.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,t||(t=ct),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...u)=>this.store[c](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...u)=>(this.store[c](...u),this)});const a=Me(),l=()=>{const c=(u,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(h),t(u,h)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),a}loadResources(e,t=ct){let i=t;const s=x(e)?e:this.language;if(typeof e=="function"&&(i=e),!this.options.resources||this.options.partialBundledLanguages){if(s?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return i();const r=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&(r.includes(c)||r.push(c))})};s?o(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>o(l)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(r,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),i(a)})}else i(null)}reloadResources(e,t,i){const s=Me();return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),i||(i=ct),this.services.backendConnector.reload(e,t,r=>{s.resolve(),i(r)}),s}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Gr.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let t=0;t<this.languages.length;t++){const i=this.languages[t];if(!["cimode","dev"].includes(i)&&this.store.hasLanguageSomeTranslations(i)){this.resolvedLanguage=i;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const i=Me();this.emit("languageChanging",e);const s=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},r=(a,l)=>{l?this.isLanguageChangingTo===e&&(s(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,i.resolve((...c)=>this.t(...c)),t&&t(a,(...c)=>this.t(...c))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const l=x(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(x(a)?[a]:a);c&&(this.language||s(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,u=>{r(u,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),i}getFixedT(e,t,i,s){const r=s?.scopeNs,o=(a,l,...c)=>{let u;typeof l!="object"?u=this.options.overloadTranslationOptionHandler([a,l].concat(c)):u={...l},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const h=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||i||o.keyPrefix);const d={...this.options,...u};Array.isArray(r)&&!h&&(d.ns=r),typeof u.keyPrefix=="function"&&(u.keyPrefix=we(u.keyPrefix,d));const f=this.options.keySeparator||".";let g;return u.keyPrefix&&Array.isArray(a)?g=a.map(p=>(typeof p=="function"&&(p=we(p,d)),`${u.keyPrefix}${f}${p}`)):(typeof a=="function"&&(a=we(a,d)),g=u.keyPrefix?`${u.keyPrefix}${f}${a}`:a),this.t(g,u)};return x(e)?o.lng=e:o.lngs=e,o.ns=t,o.keyPrefix=i,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const i=t.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,r=this.languages[this.languages.length-1];if(i.toLowerCase()==="cimode")return!0;const o=(a,l)=>{const c=this.services.backendConnector.state[`${a}|${l}`];return c===-1||c===0||c===2};if(t.precheck){const a=t.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(i,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(i,e)&&(!s||o(r,e)))}loadNamespaces(e,t){const i=Me();return this.options.ns?(x(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{i.resolve(),t&&t(s)}),i):(t&&t(),Promise.resolve())}loadLanguages(e,t){const i=Me();x(e)&&(e=[e]);const s=this.options.preload||[],r=e.filter(o=>!s.includes(o)&&this.services.languageUtils.isSupportedCode(o));return r.length?(this.options.preload=s.concat(r),this.loadResources(o=>{i.resolve(),t&&t(o)}),i):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const s=new Intl.Locale(e);if(s&&s.getTextInfo){const r=s.getTextInfo();if(r&&r.direction)return r.direction}}catch{}const t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],i=this.services?.languageUtils||new Gi(Qt());return e.toLowerCase().indexOf("-latn")>1?"ltr":t.includes(i.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const i=new He(e,t);return i.createInstance=He.createInstance,i}cloneInstance(e={},t=ct){const i=e.forkResourceStore;i&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},r=new He(s);if((e.debug!==void 0||e.prefix!==void 0)&&(r.logger=r.logger.clone(e)),["store","services","language"].forEach(a=>{r[a]=this[a]}),r.services={...this.services},r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},i){const a=Object.keys(this.store.data).reduce((l,c)=>(l[c]={...this.store.data[c]},l[c]=Object.keys(l[c]).reduce((u,h)=>(u[h]={...l[c][h]},u),l[c]),l),{});r.store=new Ki(a,s),r.services.resourceStore=r.store}if(e.interpolation){const l={...Qt().interpolation,...this.options.interpolation,...e.interpolation},c={...s,interpolation:l};r.services.interpolator=new Qi(c)}return r.translator=new kt(r.services,s),r.translator.on("*",(a,...l)=>{r.emit(a,...l)}),r.init(s,t),r.translator.options=s,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const I=He.createInstance();I.createInstance;I.dir;I.init;I.loadResources;I.reloadResources;I.use;I.changeLanguage;I.getFixedT;I.t;I.exists;I.setDefaultNamespace;I.hasLoadedNamespace;I.loadNamespaces;I.loadLanguages;function H(n){return{pattern:new RegExp(`(\\d+)\\s?u${n}\\b`,"g"),replace:(e,t)=>`${t}µ${n}`}}const Bc={"1/4":"¼","1/2":"½","3/4":"¾","1/7":"⅐","1/9":"⅑","1/10":"⅒","1/3":"⅓","2/3":"⅔","1/5":"⅕","2/5":"⅖","3/5":"⅗","4/5":"⅘","1/6":"⅙","5/6":"⅚","1/8":"⅛","3/8":"⅜","5/8":"⅝","7/8":"⅞","0/3":"↉"},Uc={...Bc,"(c)":{pattern:new RegExp("(?<!\\([ab]\\)\\s{0,3})\\(c\\)","g"),replace:"©"},"(C)":{pattern:new RegExp("(?<!\\([AB]\\)\\s{0,3})\\(C\\)","g"),replace:"©"},"(r)":"®","(R)":"®","(tm)":"™","(TM)":"™",deg:{pattern:/(\d+)\s?deg\b/g,replace:(n,e)=>`${e}°`},x:{pattern:/(\d+)\s?[xX]\s?(?=\d)/g,replace:(n,e)=>`${e}×`},ug:H("g"),um:H("m"),us:H("s"),uL:H("L"),uF:H("F"),uA:H("A"),uV:H("V"),uW:H("W"),uN:H("N"),umol:H("mol"),"->":"→","<-":"←","′":"'","″":'"'},zc={contextualizations:{abstract:{block:{start:"Start of the abstract.",end:"End of the abstract."}},acknowledgments:{block:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."}},afterword:{block:{start:"Start of the afterword.",end:"End of the afterword."}},appendix:{block:{start:"Start of the appendix.",end:"End of the appendix."}},aside:{block:{start:"Start of the aside.",end:"End of the aside."}},audio:{inline:{labelled:"Audio with a label: {{ description }}",unlabelled:"Audio with no label."}},bibliography:{block:{start:"Start of the bibliography.",end:"End of the bibliography."}},blockquote:{inline:"Blockquote."},cell:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},chapter:{block:{start:"Start of the chapter.",end:"End of the chapter."}},colophon:{inline:"Colophon."},complementary:{block:{start:"Start of the complementary content.",end:"End of the complementary content."}},conclusion:{block:{start:"Start of the conclusion.",end:"End of the conclusion."}},cover:{inline:{labelled:"Cover with a label: {{ description }}",unlabelled:"Cover with no label."}},credit:{inline:"Credit."},credits:{block:{start:"Start of the credits.",end:"End of the credits."}},dedication:{inline:"Dedication."},definition:{inline:"Definition."},details:{block:{start:"Start of the disclosure.",end:"End of the disclosure."}},endnotes:{block:{start:"Start of the endnotes.",end:"End of the endnotes."}},epigraph:{inline:"Epigraph."},epilogue:{block:{start:"Start of the epilogue.",end:"End of the epilogue."}},errata:{block:{start:"Start of the errata.",end:"End of the errata."}},example:{block:{start:"Start of the example.",end:"End of the example."}},figure:{inline:"Figure: {{ description }}"},footnote:{block:{start:"Start of the footnote.",end:"End of the footnote."}},foreword:{block:{start:"Start of the foreword.",end:"End of the foreword."}},glossary:{block:{start:"Start of the glossary.",end:"End of the glossary."}},heading1:{inline:"Heading level 1."},heading2:{inline:"Heading level 2."},heading3:{inline:"Heading level 3."},heading4:{inline:"Heading level 4."},heading5:{inline:"Heading level 5."},heading6:{inline:"Heading level 6."},image:{inline:{labelled:"Image with a label: {{ description }}",unlabelled:"Image with no label."}},index:{block:{start:"Start of the index.",end:"End of the index."}},introduction:{block:{start:"Start of the introduction.",end:"End of the introduction."}},list:{block:{start:"Start of the list.",end:"End of the list."}},listItem:{inline:"List item."},math:{inline:{labelled:"{{ description }}",unlabelled:"Math formula with no label."}},notice:{inline:"Notice."},pagebreak:{inline:"Pagebreak."},pagelist:{block:{start:"Start of the page list.",end:"End of the page list."}},part:{inline:"Part."},preface:{block:{start:"Start of the preface.",end:"End of the preface."}},prologue:{block:{start:"Start of the prologue.",end:"End of the prologue."}},pullquote:{inline:"Pullquote."},qna:{block:{start:"Start of the questions and answers.",end:"End of the questions and answers."}},row:{inline:"Row: {{ count }}"},rowheader:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},separator:{inline:"Separator."},subtitle:{inline:"Subtitle."},summary:{inline:"Summary."},table:{block:{end:"End of the table.",start:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."}},inline:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."},parts:{columns_one:"1 column",columns_other:"{{ count }} columns",lines_one:"1 line",lines_other:"{{ count }} lines"}},term:{inline:"Term."},tip:{inline:"Tip."},video:{inline:{labelled:"Video with a label: {{ description }}",unlabelled:"Video with no label."}}}},Vc={speech:zc},Xn=Vc.speech.contextualizations,ts={en:Xn},jc={};async function Hc(n){const e=ts[n];if(e)return e;const t=jc[n];if(!t)return Xn;const i=(await t()).speech.contextualizations;return ts[n]=i,i}const ns={de:["A.","A.M.","Abs.","Abt.","Abw.","Adj.","Adr.","Akt.","Allg.","Alt.","App.","Apr.","Art.","Aug.","Ausg.","Ausschl.","B.","Bed.","Ben.","Ber.","Best.","Bibl.","C.","Ca.","Chin.","Chr.","Co.","D.","D. h.","Dat.","Dez.","Di.","Dim.","Dipl.-Ing.","Dipl.-Kfm.","Dir.","Do.","Dr.","Dtzd.","Einh.","Erf.","Evtl.","F.","F.f.","Fa.","Fam.","Feb.","Fn.","Folg.","Forts. f.","Fr.","Frl.","G.","Gebr.","Gem.","Geograph.","Ges.","Gesch.","Ggf.","Hbf.","Hptst.","Hr.","Hrn.","Hrsg.","I.","Inc.","Ing.","Inh.","Int.","J.","J.D.","Jahrh.","Jan.","Jr.","Kap.","Kfm.","Kl.","Konv.","Kop.","L.","Ltd.","M.","Max.","Mi.","Min.","Mind.","Mio.","Mo.","Mod.","Mrd.","Msp.","N.","Nov.","Nr.","O.","Obj.","Okt.","Op.","P.","P.M.","PIN.","Pfd.","Phys.","Port.","Prot.","Proz.","Qu.","R.","Rd.","Reg.","Reg.-Bez.","Rel.","Rep.","S.A.","Sa.","Schr.","Sek.","Sep.","Sept.","So.","Spezif.","St.","StR.","Std.","Str.","T.","Tel.","Temp.","Test.","Trans.","Tägl.","U.","U. U.","U.S.","U.S.A.","U.U.","Urspr.","Ursprüngl.","Verf.","Vgl.","W.","Wg.","Y.","Z.","Z. B.","Z. Zt.","Ztr.","a.D.","a.M.","a.Rh.","a.a.O.","a.a.S.","am.","amtl.","b.","beil.","d.J.","d.Ä.","e.V.","e.Wz.","e.h.","ehem.","eigtl.","einschl.","entspr.","erw.","ev.","evtl.","exkl.","frz.","geb.","gedr.","gek.","gesch.","gest.","ggf.","ggfs.","hpts.","i.A.","i.B.","i.H.","i.J.","i.R.","i.V.","inkl.","jew.","jhrl.","k. u. k.","k.u.k.","kath.","kfm.","kgl.","led.","m.E.","m.W.","mtl.","möbl.","n. Chr.","n.u.Z.","näml.","o.A.","o.B.","o.g.","od.","p.Adr.","r.","röm.","röm.-kath.","s.","s.a.","schles.","schweiz.","schwäb.","sog.","südd.","tägl.","u.","u. Z.","u.A.w.g.","u.U.","u.a.","u.v.a.","u.Ä.","u.ä.","v. Chr.","v. H.","v. u. Z.","v.Chr.","v.H.","v.R.w.","v.T.","v.u.Z.","verh.","verw.","vgl.","z.","z.B.","z.Hd.","z.Z.","zzgl.","österr."],en:["A.D.","A.I.","A.M.","A.S.","AA.","AB.","Abs.","Adj.","Adv.","Alt.","Approx.","Aug.","B.V.","C.F.","C.O.D.","Capt.","Col.","Comm.","Conn.","Cont.","D.A.","D.C.","DC.","DR.","Dec.","Def.","Dept.","Diff.","Dr.","E.G.","E.g.","Ed.","Est.","Etc.","Ex.","Exec.","Feb.","Fn.","Fri.","Hon.B.A.","I.","I.D.","I.T.","I.e.","J.B.","J.D.","J.K.","Jan.","Jun.","K.R.","L.A.","L.P.","Lev.","Lib.","Lt.","Lt.Cdr.","M.","M.I.T.","M.R.","M.T.","MR.","Maj.","Mar.","Mart.","Mb.","Md.","Mgr.","Min.","Misc.","Mr.","Mrs.","Ms.","Mt.","N.V.","N.Y.","Nov.","Nr.","Num.","Op.","Org.","P.M.","P.O.","P.V.","PP.","Ph.D.","Phys.","Prof.","Pvt.","R.L.","R.T.","Rep.","Rev.","S.A.","S.A.R.","S.E.","S.p.A.","Sep.","Sept.","Sgt.","Sq.","St.","U.S.","U.S.A.","U.S.C.","VS.","Yr.","a.m.","d.","dr.","exec.","pp.","vs."],es:["A.C.","AA.","All.","Ant.","Av.","Avda.","Bien.","C.","C.P.","C.S.","C.V.","CA.","Col.","Comm.","Corp.","Cía.","D.","DC.","Da.","Desc.","Desv.","Dr.","Dra.","Drs.","Dto.","Dª.","Dña.","Em.","Emm.","Exc.","Excma.","Excmas.","Excmo.","Excmos.","Exma.","Exmas.","Exmo.","Exmos.","FF.CC.","Fabric.","Fr.","H.P.","Id.","Ilma.","Ilmas.","Ilmo.","Ilmos.","Inc.","JJ.OO.","K.","Kit.","Korn.","L.","Lcda.","Lcdo.","Lda.","Ldo.","Lic.","Ltd.","Ltda.","Ltdo.","M.","MM.","Mons.","Mr.","Mrs.","O.M.","PP.","R.D.","R.U.","RAM.","RR.HH.","Rdo.","Rdos.","Reg.","Rev.","Rol.","Rvdmo.","Rvdmos.","Rvdo.","Rvdos.","SA.","SS.AA.","SS.MM.","Sdad.","Seg.","Sol.","Sr.","Sra.","Sras.","Sres.","Srta.","Srtas.","Sta.","Sto.","Trab.","U.S.","U.S.A.","Var.","Vda.","a. C.","a. e. c.","abr.","afma.","afmas.","afmo.","afmos.","ago.","bco.","bol.","c/c.","cap.","cf.","cfr.","col.","d. C.","depto.","deptos.","dic.","doc.","dom.","dpto.","dptos.","dtor.","e. c.","e.g.","ed.","ej.","ene.","feb.","fig.","figs.","fund.","hnos.","jue.","jul.","jun.","licda.","licdo.","lun.","mar.","may.","mié.","ms.","mss.","mtro.","nov.","ntra.","ntro.","oct.","p.ej.","prof.","prov.","sept.","sras.","sres.","srs.","ss.","sáb.","trad.","v.gr.","vid.","vie.","vs."],fr:["All.","C.","Comm.","D.","DC.","Desc.","Inc.","Jr.","L.","M.","MM.","Mart.","Op.","P.","P.-D. G.","P.O.","Prof.","S.A.","S.M.A.R.T.","U.","U.S.","U.S.A.","Var.","W.","acoust.","adr.","anc.","ann.","anon.","ap. J.-C.","append.","aux.","av. J.-C.","avr.","broch.","bull.","cam.","categ.","coll.","collab.","config.","dest.","dict.","dim.","dir.","doc.","déc.","encycl.","exempl.","fig.","févr.","gouv.","graph.","hôp.","ill.","illustr.","imm.","imprim.","indus.","janv.","jeu.","juil.","lun.","mar.","mer.","niv.","nov.","oct.","quart.","réf.","sam.","sept.","symb.","synth.","syst.","trav. publ.","ven.","voit.","éd.","édit.","équiv.","éval."],it:["C.P.","Cfr.","D.","DC.","Geom.","Ing.","L.","Liv.","Ltd.","Mod.","N.B.","N.d.A.","N.d.E.","N.d.T.","O.d.G.","S.A.R.","S.M.A.R.T.","S.p.A.","Sig.","U.S.","U.S.A.","a.C.","ag.","all.","arch.","avv.","c.c.p.","d.C.","d.p.R.","div.","dott.","dr.","fig.","int.","mitt.","on.","p.","p.i.","pag.","rag.","sez.","tab.","tav.","ver.","vol."],pt:["A.C.","Alm.","Av.","Dir.","Dr.","Dra.","Dras.","Drs.","E.","Est.","Exma.","Exmo.","Fr.","Ilma.","Ilmo.","Jr.","Ltd.","Ltda.","Mar.","N.Sra.","N.T.","P.M.","Pe.","Ph.D.","R.","S.","S.A.","Sta.","Sto.","V.T.","W.C.","a.C.","a.m.","abr.","abrev.","adm.","aer.","ago.","agric.","anat.","ap.","apart.","apt.","arit.","arqueol.","arquit.","astron.","autom.","aux.","biogr.","bras.","cap.","caps.","cat.","cel.","cf.","col.","com.","comp.","compl.","cont.","contab.","créd.","cx.","círc.","cód.","d.C.","des.","desc.","dez.","dipl.","dir.","div.","doc.","déb.","ed.","educ.","elem.","eletr.","eletrôn.","end.","eng.","esp.","ex.","f.","fac.","fasc.","fem.","fev.","ff.","fig.","fil.","filos.","fisiol.","fl.","fot.","fr.","fís.","geom.","gram.","gên.","hist.","ind.","ingl.","jan.","jul.","jun.","jur.","l.","lat.","lin.","lit.","liter.","long.","mai.","mar.","mat.","matem.","mov.","máq.","méd.","mús.","neol.","nov.","náut.","obs.","odont.","odontol.","org.","organiz.","out.","p.","p. ex.","p.m.","pal.","pol.","port.","pp.","pq.","prod.","prof.","profa.","pron.","próx.","psicol.","pág.","quím.","r.s.v.p.","ref.","rel.","relat.","rep.","res.","rod.","set.","sociol.","sup.","séc.","símb.","tec.","tecnol.","tel.","trad.","transp.","univ.","vol.","vs.","álg.","índ."],ru:["авг.","апр.","дек.","до н. э.","кв.","н. э.","н.э.","нояб.","окт.","отд.","проф.","руб.","сент.","тел.","тыс.","ул.","февр.","янв."],th:["ค.ศ."]};function Zt(n,e,t){let i=t;for(;i>e&&/\s/.test(n[i-1]);)i--;return i}const qc=/[\s([{"'“‘]/;function Wc(n,e){for(const t of e){if(n.length<t.length||!n.endsWith(t))continue;const i=n.length-t.length-1;if(i<0||qc.test(n[i]))return!0}return!1}function Kc(n){let e=0;for(const t of n)if(new RegExp("\\p{L}","u").test(t)&&e++,e>=2)return!0;return!1}function Gc(n){return/\.{3,}$/.test(n)}function Xc(n,e,t,i){if(i==="“")return!0;if(i!=='"')return!1;let s=0;for(let r=e;r<t;r++)n[r]==='"'&&s++;return s%2===1}const Jc=new RegExp(`[.!?][”"'’)\\]]*\\s+—\\s+(?=\\p{Lu})`,"gu");function Yc(n,e){const t=[...n.matchAll(Jc)].map(s=>s.index+s[0].length);if(t.length===0)return e;const i=[];for(const s of e){let r=s.start;for(const o of t)o>r&&o<s.end&&(i.push({start:r,end:o}),r=o);i.push({start:r,end:s.end})}return i}function Qc(n,e,t){const i=Yc(n,e).map(r=>({...r}));for(let r=0;r<i.length-1;r++){const o=Zt(n,i[r].start,i[r].end);if(o!==i[r].end||o<=i[r].start)continue;const a=n[o-1];Xc(n,i[r].start,o,a)&&(i[r].end-=1,i[r+1].start-=1)}const s=[];for(const r of i){let o=r;for(;s.length>0;){const a=s[s.length-1],l=Zt(n,a.start,a.end),c=n.slice(a.start,l);if(!Wc(c,t)&&Kc(c)&&!Gc(c))break;s.pop(),o={start:a.start,end:o.end}}s.push(o)}return s.map(r=>{const o=Zt(n,r.start,r.end);return{text:n.slice(r.start,o),start:r.start,end:r.end,contentEnd:o}})}const is=new Map;function Zc(n){let e=is.get(n);return e||(e=new Intl.Segmenter(n,{granularity:"sentence"}),is.set(n,e)),e}async function eu(n,e,t){if(e==="")return[];const s=[...Zc(n).segment(e)].map(o=>({start:o.index,end:o.index+o.segment.length})),r=t?[...ns[n]??[],...t]:ns[n]??[];return Qc(e,s,r)}const tu=["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"],Jr=["heading1","heading2","heading3","heading4","heading5","heading6","paragraph","blockquote","preformatted","pullquote","list","listItem","table","row","cell","columnheader","rowheader","audio","video","figure","image","math","abstract","acknowledgments","afterword","appendix","article","aside","bibliography","chapter","colophon","conclusion","dedication","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","index","introduction","notice","part","preface","prologue","qna","section","summary","tip"],nu={footnote:{drops:["aside"],unconditional:!0},cover:{drops:["image"]},pullquote:{drops:["blockquote","aside"]},epigraph:{drops:["blockquote"]}},iu=["noteref","pagebreak"],su=["audio","video","image","figure","math","table","cover"],ru=["cell","rowheader"],ou=["separator"],ss=new Set(Jr),au=new Set(iu),lu=new Set(su),Yr=new Set(ru),cu=new Set(ou);function uu(n,e){const t=I.createInstance();return t.init({lng:n,resources:{[n]:{translation:e}},interpolation:{escapeValue:!1}}),t}function hu(n,e,t){if(!e)return n;const i={...n};for(const s of Object.keys(e))i[s]=t(n[s],e[s]);return i}function Qr(n,e){if(typeof e=="string"||typeof n!="object")return e;const t={...n};for(const i of Object.keys(e))t[i]=Qr(n[i],e[i]);return t}function du(n,e){return hu(n,e,Qr)}function Zr(n,e=[],t=new Map){for(const i of n)t.set(i,e),i.children&&Zr(i.children,[i,...e],t);return t}async function eo(n,e){const t=e.contextualizationLocale??"en",i=du(await Hc(t),e.contextualization?.contextualizations);return{i18n:uu(t,i),skip:new Set(e.skip??[]),contextualize:new Set(e.contextualize??[]),contextualizationShapes:e.contextualization?.shapes??{},contextualizationParams:e.contextualization?.params,format:e.format??"plain",inlineContextualization:e.inlineContextualization??!1,language:e.language??"block-level",segmentation:e.segmentation?.mode??"structure",segmentationSuppressions:e.segmentation?.suppressions??{},segmenter:e.segmentation?.segmenter??eu,substitutions:{...Uc,...e.substitutions},blockStarts:new Set,tableRowNumbers:new Map,tableCellHeaders:new Map,synthetic:new Set,ancestorChains:Zr(n),pendingRange:new Map,edgeSubstitutedLocate:new WeakMap}}const fu=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function to(n){return n.replace(fu,"$1")}const En="#css(",Cn=")";function no(n){return`${En}${encodeURIComponent(n)}${Cn}`}function io(n){if(!(!n||!n.startsWith(En)||!n.endsWith(Cn)))return decodeURIComponent(n.slice(En.length,-Cn.length))}const kn="#domrange(",Rn=")";function so(n){return`${kn}${encodeURIComponent(JSON.stringify(n))}${Rn}`}function ro(n){if(!(!n||!n.startsWith(kn)||!n.endsWith(Rn)))try{const e=JSON.parse(decodeURIComponent(n.slice(kn.length,-Rn.length)));return!e?.start?.cssSelector||typeof e.start.textNodeIndex!="number"?void 0:e}catch{return}}const An=":~:text=";function ut(n){return encodeURIComponent(n).replace(/-/g,"%2D")}function oo(n){let e="";return n.prefix&&(e+=`${ut(n.prefix)}-,`),e+=ut(n.textStart),n.textEnd&&(e+=`,${ut(n.textEnd)}`),n.suffix&&(e+=`,-${ut(n.suffix)}`),`${An}${e}`}function gu(n){if(!n)return;const e=n.indexOf(An);if(e===-1)return;const t=n.slice(e+An.length).split("&")[0];if(t)try{let i=t.split(",");const s={textStart:""};return i[0].endsWith("-")&&(s.prefix=decodeURIComponent(i[0].slice(0,-1)),i=i.slice(1)),i.length>0&&i[i.length-1].startsWith("-")&&(s.suffix=decodeURIComponent(i[i.length-1].slice(1)),i=i.slice(0,-1)),i.length===0||i[0]===""?void 0:(s.textStart=decodeURIComponent(i[0]),i.length>1&&(s.textEnd=decodeURIComponent(i[1])),s)}catch{return}}function pu(n,e){if(!n.domRange||!e.domRange)return;const t={start:n.domRange.start,end:e.domRange.end??e.domRange.start};return n.domRange.container!==void 0&&(t.container=n.domRange.container),{domRange:t,cssSelector:t.container??t.start.cssSelector}}function On(n){const e=n?.textref;if(!e)return;const t=e.indexOf(":~:"),i=t===-1?e:e.slice(0,t);let s,r;const o=ro(i);if(o)r=o,s=o.container??o.start.cssSelector;else{const c=io(i);c!==void 0?s=c:n?.id&&i===`#${CSS.escape(n.id)}`&&(s=i)}const a=gu(e);if(s===void 0&&r===void 0&&a===void 0)return;const l={};return s!==void 0&&(l.cssSelector=s),r!==void 0&&(l.domRange=r),a?.textEnd!==void 0?l.fragment=oo(a):a&&(l.text={highlight:a.textStart},a.prefix!==void 0&&(l.text.before=a.prefix),a.suffix!==void 0&&(l.text.after=a.suffix)),l}function Te(n,e){const t=n.cssSelector??n.domRange?.start.cssSelector;return t?{cssSelector:t,text:{highlight:e}}:{...n,text:{highlight:e}}}function _(n,e){const t=On(n);if(t)return{own:!0,ref:t};for(const i of e.get(n)??[]){const s=On(i);if(s)return{own:!1,ref:s}}}function Jn(n,e){if(n)return n.own?n.ref:Te(n.ref,e)}function Yn(n,e,t){return(n&&e?pu(n.ref,e.ref):void 0)??t}function ao(n,e,t){const{ancestorChains:i}=t,s=new Map;for(const r of e)r&&!Array.isArray(r)&&s.set(r,(s.get(r)??0)+1);return n.map((r,o)=>{if(r.offsets)return r;const a=e[o],l=r.plain??r.ssml??"";if(Array.isArray(a)){const[d,f]=a,g=_(d,i),p=_(f,i),m=Yn(g,p,Jn(g,l));return m?{...r,locate:m}:r}const c=a,u=c?_(c,i):void 0;if(!u)return r;const h={...r,locate:u.ref};if(!t.synthetic.has(r)){const d=t.pendingRange.get(r),f=d!==void 0||c&&(s.get(c)??0)>1;h.locate=u.own&&!f?u.ref:Te(u.ref,l),h.offsets=[{start:d?.start??0,end:d?.end??l.length,locate:h.locate}]}return h})}function Qn(n){const e=Pn(n.text);return e?e.plain??(e.ssml?le(e.ssml):""):""}function mu(n){const e=new Map,t=new Map;let i=0,s;return n.forEach((r,o)=>{e.set(r,o+1);const a=r.children??[];if(i=Math.max(i,a.length),a.some(l=>l.role?.includes("columnheader"))){s=a.map(Qn);return}s&&a.forEach((l,c)=>{const u=l.role??[];if(!u.includes("cell")&&!u.includes("rowheader"))return;const h=s[c];h&&t.set(l,h)})}),{lines:n.length,columns:i,rowNumbers:e,cellHeaders:t}}function se(n,e){const t=e.format==="ssml"?{ssml:X(n)}:{plain:n};return e.synthetic.add(t),t}function re(n,e,t,i){n.push(...i);for(let s=0;s<i.length;s++)e.push(t)}function lo(n,e,t,i,s,r,o){o?(s.some(a=>t.blockStarts.has(a))&&t.blockStarts.add(o),re(n,e,r[0]??i,[o])):(n.push(...s),e.push(...r))}function Ge(n,e,t,i){const s=t?`${e}.${t}`:void 0;if(s&&n.i18n.exists(s))return n.i18n.t(s,i);if(n.i18n.exists(e))return n.i18n.t(e,i)}function Zn(n,e){return Yr.has(n)?!0:e.contextualize.has(n)}function Su(n,e,t){return e.some(i=>{const s=nu[i];return s?.drops.includes(n)?s.unconditional||Zn(i,t):!1})}function Rt(n,e,t,i,s){const r=e.lastIndexOf(t);if(r===-1)return;const o=_(i,s.ancestorChains);if(!o)return;const a=Te(o.ref,t);n.offsets=[{start:r,end:r+t.length,locate:a}],n.locate=o.own?o.ref:a}function rs(n,e,t,i,s,r){const o=r?.value;if(o!==void 0&&o===Qn(t)){if(i.language!=="none"){const l=typeof t.text=="object"?t.text.language:void 0;l&&(n.language=l)}i.synthetic.delete(n),Rt(n,e,o,t,i);return}const a=r?.description;a!==void 0&&a===t.description&&(s==="figure"||s==="table")&&Rt(n,e,a,t,i)}function os(n,e,t,i,s,r,o,a){if(!Zn(s,i))return;if((i.i18n.exists(`${s}.block.start`)||i.i18n.exists(`${s}.block.end`))&&i.contextualizationShapes[s]!=="inline"){const c=r==="before"?`${s}.block.start`:`${s}.block.end`,u=Ge(i,c,o,a);if(u){const h=se(u,i);rs(h,u,t,i,s,a),re(n,e,t,[h])}return}if(r==="before"){const c=Ge(i,`${s}.inline`,o,a);if(c){const u=se(c,i);rs(u,c,t,i,s,a),re(n,e,t,[u])}}}function as(n,e,t,i){const s=`${e}.parts.${t}`;return n.i18n.exists(s,{count:i})?n.i18n.t(s,{count:i}):String(i)}function vu(n){return n.description===void 0?{variantKey:"unlabelled"}:{variantKey:"labelled",params:{description:n.description}}}function ls(n,e){const t=e.tableCellHeaders.get(n);return{variantKey:t!==void 0?"withHeader":"withoutHeader",params:{header:t??"",value:Qn(n)}}}const yu={table:(n,e)=>{const t=(n.children??[]).filter(s=>s.role?.includes("row")),i=mu(t);for(const[s,r]of i.rowNumbers)e.tableRowNumbers.set(s,r);for(const[s,r]of i.cellHeaders)e.tableCellHeaders.set(s,r);return{params:{lines:as(e,"table","lines",i.lines),columns:as(e,"table","columns",i.columns)}}},row:(n,e)=>({params:{count:String(e.tableRowNumbers.get(n)??"")}}),cell:ls,rowheader:ls};function cs(n,e,t){const i=vu(e);let s=i.variantKey,r=i.params;const o=yu[n]?.(e,t);o&&(o.variantKey&&(s=o.variantKey),r={...r,...o.params});const a=t.contextualizationParams?.(n,e);return a&&(r={...r,...a}),{variantKey:s,params:r}}const bu=["math","separator"],ei=new WeakSet,Ne=new WeakSet,co=new WeakMap,uo=new WeakMap;function Tn(n){return n.role?.some(e=>bu.includes(e))?!1:!n.audioref&&!n.imgref&&!n.textref&&!n.videoref&&(!n.text||Je(n.text))&&!(n.children&&n.children.length>0)&&!n.description}function wu(n){return!n.audioref&&!n.imgref&&!n.textref&&!n.videoref&&(!n.text||Je(n.text))&&!!(n.children&&n.children.length>0)&&!(n.role&&n.role.length>0)&&!n.id}function xu(n){return!(n.role&&n.role.length>0)&&!n.id&&!n.textref&&!n.imgref&&!n.audioref&&!n.videoref}class ht{el;object={};children=[];noText=!1;finalize(){const e=this.object,t=[];for(const i of this.children){const s=i.finalize();if(!Tn(s)){if(wu(s)){t.push(...s.children??[]);continue}t.push(s)}}if(t.length>0&&(e.children=t),e.role?.length&&e.children?.length===1&&!e.role.includes("presentation")){const i=e.children[0];i.role?.length&&e.role.every(s=>i.role.includes(s))&&delete e.role}if((!e.text||Je(e.text))&&e.children?.length===1){const i=e.children[0];xu(i)&&(i.text&&(e.text=i.text),e.children=i.children)}return e}}function Nn(n){const e={};n.id&&(e.id=n.id),n.textref&&(e.textref=n.textref),n.imgref&&(e.imgref=n.imgref),n.audioref&&(e.audioref=n.audioref),n.videoref&&(e.videoref=n.videoref);const t=xa(n.text);t!==void 0&&(e.text=t),n.role&&n.role.length>0&&(e.role=n.role),n.children&&n.children.length>0&&(e.children=n.children.map(Nn)),n.description&&(e.description=n.description),ei.has(n)&&Ne.add(e);const i=co.get(n);return i&&uo.set(e,i),e}function ho(n){const e={};return n.id&&(e.id=n.id),n.textref&&(e.textref=n.textref),n.imgref&&(e.imgref=n.imgref),n.audioref&&(e.audioref=n.audioref),n.videoref&&(e.videoref=n.videoref),n.role&&(e.role=n.role),n.description&&(e.description=n.description),typeof n.text=="string"?e.text={plain:n.text,ssml:"",language:""}:n.text&&(e.text={plain:n.text.plain??"",ssml:n.text.ssml??"",language:n.text.language}),n.children&&(e.children=n.children.map(ho)),e}function At(n){let e="";const t=[];for(const i of n){if(i.length===1&&ba(i)&&e.endsWith(i)){t.push({start:e.length,end:e.length});continue}e&&!Oe(i)&&!/\s$/.test(e)&&!/^\s/.test(i)&&(e+=" ");const s=e.length;e+=i,t.push({start:s,end:e.length})}return{joined:e,ranges:t}}function _t(n,e){const t=uo.get(n);if(t)return Vi({cssSelector:t});const i=_(n,e.ancestorChains)?.ref;return i&&Vi(i)}function Eu(n,e,t){const i=[];return n.forEach((s,r)=>{if(s.offsets){i.push(...s.offsets);return}if(t.synthetic.has(s))return;const o=e[r];if(!o||Array.isArray(o))return;const a=_(o,t.ancestorChains);if(!a)return;const l=t.format==="ssml"?s.ssml:s.plain;if(!l)return;const c=t.pendingRange.get(s),u=Ne.has(o)?_t(o,t)??a.ref:Te(a.ref,l);i.push({start:c?.start??0,end:c?.end??l.length,locate:u})}),i}function us(n,e,t,i){const s=i.edgeSubstitutedLocate.get(n);if(s)return s[t];if(!(!e||Array.isArray(e)||!Ne.has(e)))return _t(e,i)}function Cu(n,e,t){const i=n.map((l,c)=>{if(l.locate)return l.locate;if(t.synthetic.has(l))return;const u=e[c];if(!u||Array.isArray(u))return;const h=t.format==="ssml"?l.ssml:l.plain;if(h)return Ne.has(u)?_t(u,t):Jn(_(u,t.ancestorChains),h)}),s=i.findIndex(l=>l!==void 0);if(s===-1)return;let r=i.length-1;for(;i[r]===void 0;)r--;if(s===r)return i[s];const o=e[s],a=e[r];if(o&&a&&!Array.isArray(o)&&!Array.isArray(a)){const l=_(o,t.ancestorChains),c=_(a,t.ancestorChains);return Yn(l,c,i[s])}return i[s]}function ti(n,e,t){let i,s=!1;const r=[],o=[],a=[];for(let g=0;g<n.length;g++){const p=n[g],m=t.format==="ssml"?p.ssml:p.plain;if(m&&(r.push(m),o.push(p),a.push(e[g]),p.language!==void 0)){if(s&&p.language!==i)return;i=p.language,s=!0}}if(r.length===0)return;const{joined:l}=At(r),c=t.format==="ssml"?{ssml:l}:{plain:l};i&&(c.language=i),n.some(g=>t.synthetic.has(g))&&t.synthetic.add(c);const u=Eu(o,a,t);u.length>0&&(c.offsets=u);const h=Cu(o,a,t);h&&(c.locate=h);const d=us(o[0],a[0],"leading",t),f=us(o[o.length-1],a[o.length-1],"trailing",t);return(d||f)&&t.edgeSubstitutedLocate.set(c,{leading:d,trailing:f}),c}function fo(n,e,t,i){if(e==="plain"&&t!=="block-level"&&t!=="none"&&n.ssml&&Is(n.ssml))return Ls(n.ssml,n.language).map(r=>{const o={plain:r.plain};return r.language&&(o.language=r.language),i.pendingRange.set(o,{start:r.start,end:r.end}),o});const s={};return n.language&&(s.language=n.language),e==="ssml"?s.ssml=n.ssml??X(n.plain??""):s.plain=n.plain??le(n.ssml??""),(t==="block-level"||t==="none")&&(s.ssml&&(s.ssml=to(s.ssml)),t==="none"&&delete s.language),[s]}function Ze(n,e){return e!=="ssml"?n:n.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function hs(n,e){return e.size>0&&n.some(t=>e.has(t))}function ku(n,e){const t=Pn(n.text),i=t?fo(t,e.format,e.language,e):[];if(!e.contextualize.has("pagebreak"))return i;const s=e.i18n.exists("pagebreak.block.start")?"pagebreak.block.start":"pagebreak.inline",r=Ge(e,s);if(r===void 0)return i;const o=se(r,e);if(i.length===0)return[o];const a=ti([o,...i],[void 0,...i.map(()=>n)],e);return a?(a.plain!==void 0&&(a.plain+="."),a.ssml!==void 0&&(a.ssml+="."),[a]):[o,...i]}function Ru(n){return(n.role??[]).some(e=>au.has(e))}function Au(n,e,t,i,s,r){const o=typeof n.text=="object"?n.text.language:void 0,a=new Map((n.children??[]).map(d=>[d.id,d])),l=[],c=[],u=[];for(const d of za(e)){if(d.placeholderId!==void 0){const g=a.get(d.placeholderId);if(!g)continue;s.inlineContextualization||!Ru(g)?go(g,l,c,s,r):u.push(g);continue}if(!d.ssml)continue;if(s.format==="plain"&&s.language!=="block-level"&&s.language!=="none"&&Is(d.ssml)){for(const g of Ls(d.ssml,o)){const p={plain:g.plain};g.language&&(p.language=g.language),l.push(p),c.push(n)}continue}const f={};o&&(f.language=o),s.format==="ssml"?f.ssml=d.ssml:f.plain=le(d.ssml),(s.language==="block-level"||s.language==="none")&&(f.ssml&&(f.ssml=to(f.ssml)),s.language==="none"&&delete f.language),l.push(f),c.push(n)}const h=l.length>1?ti(l,c,s):void 0;return lo(t,i,s,n,l,c,h),u}function go(n,e,t,i,s){const r=n.role??[];if(hs(r,i.skip))return;const o=r.some(d=>ss.has(d)),a=o&&!s,l=e.length,c=r.filter(d=>d!=="footnote"&&d!=="pagebreak"&&!Su(d,r,i)),u=r.some(d=>lu.has(d)&&i.contextualize.has(d)),h=r.includes("table")&&n.description!==void 0&&!u;if(h){const d=se(n.description,i);Rt(d,n.description,n.description,n,i),re(e,t,n,[d])}for(const d of c){if(d==="figure"&&n.description===void 0)continue;const{variantKey:f,params:g}=cs(d,n,i);os(e,t,n,i,d,"before",f,g)}if(r.includes("noteref"))for(const d of n.children??[]){const f=d.role??[];if(!hs(f,i.skip))if(f.includes("footnote")){const g=i.contextualize.has("footnote"),p=i.i18n.exists("footnote.block.start")||i.i18n.exists("footnote.block.end"),m=f.some(A=>ss.has(A))&&!s&&!i.inlineContextualization,y=g?Ge(i,p?"footnote.block.start":"footnote.inline"):void 0,w=g&&(y!==void 0||p),S=[],v=[];y!==void 0&&(S.push(se(y,i)),v.push(d));const b=[],C=[];if(ne([d],b,C,i,s||m),m&&b.length>0&&i.blockStarts.add(b[0]),S.push(...b),v.push(...C),w&&p){const A=Ge(i,"footnote.block.end");A!==void 0&&(S.push(se(A,i)),v.push(d))}const R=w&&S.length>1?ti(S,v,i):void 0;lo(e,t,i,d,S,v,R)}else ne([d],e,t,i,s)}else if(!r.some(d=>cu.has(d))){const d=typeof n.text=="object"?n.text.ssml:void 0;if(d&&Ua(d)){const f=Au(n,d,e,t,i,s);if(f.length>0){const g=s||o&&e.length>l;ne(f,e,t,i,g)}}else if(r.includes("pagebreak")){if(re(e,t,n,ku(n,i)),n.children){const f=s||o&&e.length>l;ne(n.children,e,t,i,f)}}else{const g=r.some(p=>Yr.has(p)&&Zn(p,i))?void 0:Pn(n.text);if(g&&re(e,t,n,fo(g,i.format,i.language,i)),n.children){const p=s||o&&e.length>l;ne(n.children,e,t,i,p)}}}if(a&&e.length>l&&i.blockStarts.add(e[l]),n.description!==void 0&&!u&&!h){const d=se(n.description,i);r.includes("figure")&&Rt(d,n.description,n.description,n,i),re(e,t,n,[d])}for(const d of c){if(d==="figure"&&n.description===void 0)continue;const{variantKey:f,params:g}=cs(d,n,i);os(e,t,n,i,d,"after",f,g)}}function ne(n,e,t,i,s){n.forEach((r,o)=>go(r,e,t,i,o===0?s:!1))}const Ou=Ps;async function po(n,e,t,i){const s=Ou(n);let r="";const o=[];for(const d of s)o.push(r.length),d.kind==="text"?r+=d.text:d.kind==="paired"&&(r+=d.innerText);if(!r)return;const a=await t(e,r,i);if(a.length<=1)return;const l=[];let c="",u=0;function h(d,f,g){let p=f;const m=f+d.length;for(;p<m;){const y=a[u],w=Math.min(m,y.end),S=w>=y.end&&u<a.length-1;let v=d.slice(p-f,w-f);S&&(v=v.replace(/[ \t\r\n]+$/,""));const b=X(v);c+=g?g(b):b,p=w,S&&(l.push(c),c="",u++)}}return s.forEach((d,f)=>{if(d.kind==="selfClosing")c+=d.raw;else if(d.kind==="text")h(d.text,o[f]);else{const g=`<${d.tag}${d.attrs}>`,p=`</${d.tag}>`;d.innerText?h(d.innerText,o[f],m=>`${g}${m}${p}`):c+=g+p}}),c&&l.push(c.replace(/[ \t\r\n]+$/,"")),l}async function Tu(n,e){const t=n.language??"en",i=e.segmentationSuppressions[t],s=e.format==="ssml"?n.ssml:n.plain;if(!s)return;const r=await e.segmenter(t,Ze(s,e.format),i);if(r.length<=1)return;if(e.format!=="ssml")return r.map(a=>({text:a.text,start:a.start,end:a.contentEnd}));const o=await po(s,t,e.segmenter,i);if(o)return r.map((a,l)=>({text:o[l],start:a.start,end:a.contentEnd}))}const ds=new Set(["cell","rowheader","columnheader","row","table","list","listItem","heading1","heading2","heading3","heading4","heading5","heading6"]);function fs(n){return n?(Array.isArray(n)?n[1]:n).role??[]:[]}function gs(n,e,t,i){return i.edgeSubstitutedLocate.get(e)?.[t]?!0:!!n&&!Array.isArray(n)&&Ne.has(n)}function Nu(n,e,t,i,s){if(s.synthetic.has(n)||s.synthetic.has(t)||!e||!i)return!1;const r=s.format==="ssml"?n.ssml:n.plain,o=s.format==="ssml"?t.ssml:t.plain;return!(!r||!o||(n.language??"en")!==(t.language??"en")||fs(e).some(a=>ds.has(a))||fs(i).some(a=>ds.has(a))||gs(e,n,"trailing",s)||gs(i,t,"leading",s))}async function ps(n,e,t,i,s){const r=t.synthetic.has(n)?void 0:await Tu(n,t);if(!r){i.push(n),s.push(e);return}const o=t.blockStarts.has(n);o&&t.blockStarts.delete(n);const a=Array.isArray(e)?void 0:e,l=a?_(a,t.ancestorChains):void 0,c=a&&Ne.has(a)?_t(a,t):void 0,u=t.edgeSubstitutedLocate.get(n);r.forEach(({text:h,start:d,end:f},g)=>{const p={...n,[t.format]:h},m=(g===0?u?.leading:void 0)??(g===r.length-1?u?.trailing:void 0)??c;if(m)p.locate=m,p.offsets=[{start:d,end:f,locate:m}];else if(l){const y=t.format==="ssml"?Ze(h,t.format):h,w=Te(l.ref,y);p.locate=w,p.offsets=[{start:d,end:f,locate:w}]}o&&g===0&&t.blockStarts.add(p),i.push(p),s.push(e)})}function Ot(n,e){let t=0;for(;t<n.length-1&&n[t+1].start<=e;)t++;return t}async function Du(n,e,t,i){const s=n.map(c=>Ze(e.format==="ssml"?c.ssml:c.plain,e.format)),{joined:r,ranges:o}=At(s),a=await e.segmenter(t,r,i),l=new Array(n.length-1).fill(!1);for(const c of a){const u=Ot(o,c.start),h=c.end>c.start?Ot(o,c.end-1):u;for(let d=u;d<h;d++)l[d]=!0}return l}function Pu(n,e,t,i,s,r,o){const a=[];for(let l=s;l<=r;l++){const c=_(e[l],o.ancestorChains);if(!c)continue;const u=t[l],h=Math.max(u.start,i.start),d=Math.min(u.end,l===r?i.contentEnd:i.end);if(d<=h)continue;const f=h-u.start,g=d-u.start,p=Ze(o.format==="ssml"?n[l].ssml:n[l].plain,o.format),m=Te(c.ref,p.slice(f,g));a.push({start:f,end:g,locate:m})}return a}async function Fu(n,e,t,i,s){const r=n[0].language??"en",o=t.segmentationSuppressions[r],a=n.map(g=>Ze(t.format==="ssml"?g.ssml:g.plain,t.format)),{joined:l,ranges:c}=At(a),u=await t.segmenter(r,l,o);let h,d;t.format==="ssml"&&(d=At(n.map(g=>g.ssml)).joined,h=u.length>1?await po(d,r,t.segmenter,o):void 0),(u.length>0?u:[{text:l,start:0,end:l.length,contentEnd:l.length}]).forEach((g,p)=>{const m=Ot(c,g.start),y=g.end>g.start?Ot(c,g.end-1):m,w=t.format==="ssml"?h?h[p]:d:g.text,S={[t.format]:w};r&&(S.language=r),n.slice(m,y+1).some(N=>t.blockStarts.has(N))&&t.blockStarts.add(S);const b=Pu(n,e,c,g,m,y,t);b.length>0&&(S.offsets=b);const C=_(e[m],t.ancestorChains),R=Jn(C,w),A=m!==y?Yn(C,_(e[y],t.ancestorChains),R):R;A&&(S.locate=A),i.push(S),s.push(m===y?e[m]:[e[m],e[y]])})}async function mo(n,e,t){if(t.segmentation!=="sentence")return{out:n,sources:e};const i=[],s=[];let r=0;for(;r<n.length;){let o=r;for(;o+1<n.length&&Nu(n[o],e[o],n[o+1],e[o+1],t);)o++;if(o===r){await ps(n[r],e[r],t,i,s),r=o+1;continue}const a=n.slice(r,o+1),l=e.slice(r,o+1),c=a[0].language??"en",u=await Du(a,t,c,t.segmentationSuppressions[c]);let h=0;for(let d=0;d<a.length;d++)d<a.length-1&&u[d]||(h===d?await ps(a[h],l[h],t,i,s):await Fu(a.slice(h,d+1),l.slice(h,d+1),t,i,s),h=d+1);r=o+1}return{out:i,sources:s}}function So(n,e){return Object.keys(e.substitutions).length===0?n:n.map(t=>{if(t.ssml){const{ssml:a,plain:l,map:c}=La(t.ssml,e.substitutions);if(a===t.ssml)return t;const u={...t,ssml:a};return zi(u,{plain:l,map:c}),u}const i=t.plain;if(!i)return t;const{text:s,map:r}=Fa(i,e.substitutions);if(s===i)return t;const o={...t,plain:s};return zi(o,{plain:i,map:r}),o})}async function Iu(n,e){const t=[],i=[],s=await eo(n,e);ne(n,t,i,s,!1);const r=await mo(t,i,s);return So(ao(r.out,r.sources,s),s)}async function Lu(n,e){const t=[],i=[],s=await eo(n,e);ne(n,t,i,s,!1);const r=await mo(t,i,s),o=r.out.map(l=>s.blockStarts.has(l)),a=ao(r.out,r.sources,s);return{utterances:So(a,s),sources:r.sources,blockStarts:o}}class $u{engine;contentQueue=[];events=new Lt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;contextualizationOverrides;segmentationOverrides;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,t={}){this.engine=e,this._defaults=new $r(t.defaults),this._preferences=new Re(t.preferences),this._settings=new wn(this._preferences,this._defaults),this.contextualizationOverrides=t.contextualizationOverrides,this.segmentationOverrides=t.segmentationOverrides,this.setupEngineListeners(),this.applyEngineParameters(),this.initializeEngine()}applyEngineParameters(){this.engine.setRate(this._settings.rate),this.engine.setPitch(this._settings.pitch),this.engine.setVolume(this._settings.volume)}async initializeEngine(){try{await this.engine.initialize?.()}catch(e){console.warn("Failed to initialize speech engine:",e)}}setupEngineListeners(){this.engine.on("start",()=>{this.setNavigatorState("playing");const e=this.getCurrentContent();e&&this.emitUtteranceBoundary(e),this.emitEvent({type:"start"})}),this.engine.on("end",()=>{const e=this.engine.getCurrentUtteranceIndex(),t=this.engine.getUtteranceCount();if(e<t-1){const i=this._settings.autoPause==="utterance"||this.contentBlockStarts[e+1]===!0;this._settings.autoPause!=="none"&&i?(this.pendingAutoPauseIndex=e+1,this.setNavigatorState("paused"),this.emitEvent({type:"pause"})):this.pendingAdvanceTimeout=setTimeout(()=>{this.pendingAdvanceTimeout=null,this.engine.speak(e+1)},this._settings.pauseDuration)}else this.engine.setCurrentUtteranceIndex(0),this.setNavigatorState("idle");this.emitEvent({type:"end"})}),this.engine.on("pause",()=>{this.setNavigatorState("paused"),this.emitEvent({type:"pause"})}),this.engine.on("resume",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"resume"})}),this.engine.on("stop",()=>{this.setNavigatorState("idle"),this.emitEvent({type:"stop"})}),this.engine.on("error",e=>{this.setNavigatorState("idle"),this.emitEvent(e)}),this.engine.on("ready",()=>{if(this.contentQueue.length===0)return;const e=this.pendingResumeIndex,t=this.pendingResumeState;if(this.pendingResumeIndex=null,this.pendingResumeState=null,this.navigatorState==="loading"){if(t==="playing"){this.setNavigatorState("playing"),this.engine.speak(e??0);return}if(t==="paused"){const i=e??0;i>0?this.engine.setCurrentUtteranceIndex(i,()=>this.setNavigatorState("paused")):this.setNavigatorState("paused");return}this.setNavigatorState("ready"),this.emitEvent({type:"ready"})}}),this.engine.on("boundary",e=>{const{charIndex:t,charLength:i}=e.detail??{},s=this.getCurrentContent(),r=s&&typeof t=="number"&&typeof i=="number"?qr(s,t,i):void 0;this.emitEvent(r?{...e,detail:{...e.detail,...r}}:e)}),this.engine.on("mark",e=>{this.emitEvent(e)}),this.engine.on("voiceschanged",()=>{this.emitEvent({type:"voiceschanged"})}),this.engine.on("languagefallback",e=>{this.emitEvent(e)}),this.engine.on("enginefallback",e=>{this.emitEvent(e)}),this.engine.on("enginerecovered",e=>{this.emitEvent(e)})}setNavigatorState(e){this.navigatorState=e}async getVoices(){return this.engine.getAvailableVoices()}setVoice(e){this.engine.setVoice(e)}getCurrentVoice(){return this.engine.getCurrentVoice()}setSpeakInContentLanguage(e){this.engine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.engine.getSpeakInContentLanguage()}loadContent(e){if(this.source)throw new Error("loadContent() cannot be used after loadGndContent() — the two are exclusive. Create a new navigator instance to switch content sources.");this.setContentQueue(e)}async loadGndContent(e){this.source=e,await this.reextract()}setContentQueue(e,t=null,i=null){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,(this.navigatorState==="playing"||this.navigatorState==="paused")&&this.engine.stop();const s=Array.isArray(e)?e:[e];this.contentQueue=[...s],this.pendingResumeIndex=t,this.pendingResumeState=i,this.setNavigatorState("loading"),this.emitEvent({type:"loading"}),this.engine.loadUtterances(s,t??void 0),this.emitContentChangeEvent({content:s})}async reextract(){if(!this.source)return;const e=this.navigatorState==="playing"||this.navigatorState==="paused"?this.navigatorState:null,t=this.contentSources,i=this.getCurrentUtteranceIndex(),{utterances:s,sources:r,blockStarts:o}=await Lu(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,contextualization:{contextualizations:this.contextualizationOverrides?.contextualizations,shapes:vc(this._settings.verbosity,this.contextualizationOverrides?.shapes),params:this.contextualizationOverrides?.params},language:this._settings.language,segmentation:{mode:this._settings.segmentation,suppressions:this.segmentationOverrides?.suppressions,segmenter:this.segmentationOverrides?.segmenter}});this.contentSources=r,this.contentBlockStarts=o;const a=e?this.resolveResumeIndex(t,i,r):null;this.setContentQueue(s,a,e)}resolveResumeIndex(e,t,i){for(let s=Math.min(t,e.length-1);s>=0;s--){const r=e[s];if(r===void 0||Array.isArray(r))continue;const o=i.indexOf(r);if(o!==-1)return o}return null}getCurrentContent(){const e=this.getCurrentUtteranceIndex();return e<this.contentQueue.length?this.contentQueue[e]:null}getContentQueue(){return[...this.contentQueue]}getCurrentUtteranceIndex(){return this.engine.getCurrentUtteranceIndex()}play(){if(this.navigatorState==="paused")if(this.setNavigatorState("playing"),this.pendingAutoPauseIndex!==null){const e=this.pendingAutoPauseIndex;this.pendingAutoPauseIndex=null,this.engine.speak(e)}else this.engine.resume();else if(this.navigatorState==="ready"||this.navigatorState==="idle")this.setNavigatorState("playing"),this.engine.speak();else if(this.navigatorState==="playing")return}pause(){this.navigatorState==="playing"&&(this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("paused"),this.engine.pause())}stop(){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("idle"),this.engine.stop(),this.emitEvent({type:"stop"})}clearPendingAdvance(){this.pendingAdvanceTimeout!==null&&(clearTimeout(this.pendingAdvanceTimeout),this.pendingAdvanceTimeout=null)}skipToPosition(e,t=!1){const i=this.getCurrentUtteranceIndex();return e<0||e>=this.contentQueue.length?!1:(e===i||(this.clearPendingAdvance(),this.navigatorState==="paused"&&!t?(this.pendingAutoPauseIndex!==null&&(this.pendingAutoPauseIndex=e),this.engine.setCurrentUtteranceIndex(e,s=>{if(s){const r=this.getCurrentContent();r&&this.emitUtteranceBoundary(r),this.emitEvent({type:"skip",detail:{position:e}})}})):(this.pendingAutoPauseIndex=null,this.setNavigatorState("playing"),this.engine.speak(e))),!0)}next(e=!1){const t=this.getCurrentUtteranceIndex();return this.skipToPosition(t+1,e)}previous(e=!1){const t=this.getCurrentUtteranceIndex();return this.skipToPosition(t-1,e)}jumpTo(e,t=!1){return this.skipToPosition(e,t)}getState(){return this.navigatorState}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}emitUtteranceBoundary(e){const t=this._settings.segmentation,i=Wr(e,t);if(!i.length)return;const s=t==="sentence"?"sentence":"structure";this.emitEvent({type:"boundary",detail:{name:s,charIndex:0,charLength:(e.plain??"").length,locate:i}})}emitContentChangeEvent(e){this.events.emit("contentchange",{type:"contentchange",detail:e})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new yn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){!this.source&&Bi.some(t=>e[t]!==void 0)&&console.warn("submitPreferences(): extraction-affecting preferences (format, inlineContextualization, verbosity, skip, contextualize, language, segmentation) have no effect on content loaded via loadContent() — use loadGndContent() to re-extract on submission."),this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new wn(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new yn(this._preferences,this._settings)),Bi.some(t=>!this.sameSettingValue(e[t],this._settings[t]))&&await this.reextract()}sameSettingValue(e,t){return Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(i=>t.includes(i)):e===t}async destroy(){this.clearPendingAdvance(),this.events.clear(),await this.engine.destroy()}}const Mu=["heading1","heading2","heading3","heading4","heading5","heading6"],ms={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",grid:"table",gridcell:"cell",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},_u={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},Bu={article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"},Uu=new Set(["table","tr","td","th"]),zu=new Set(["table","row","cell","columnheader","rowheader"]);function Vu(n){const e=n.getAttribute("role");if(!e)return!1;const t=e.split(/\s+/).filter(Boolean);return t.includes("presentation")||t.includes("none")}function ju(n){for(let e=n.parentElement;e;e=e.parentElement)if(Vu(e))return!0;return!1}function Hu(n,e,t){return Uu.has(e)||t.some(i=>zu.has(i))}function pt(n,e){const t=n.getAttribute("role");return t?t.split(/\s+/).filter(Boolean).includes(e):!1}function qu(n){return n.tagName.toLowerCase()==="table"||pt(n,"table")||pt(n,"grid")||pt(n,"treegrid")}function Wu(n){return n.tagName.toLowerCase()==="tr"||pt(n,"row")}function Ku(n){let e=null;for(let i=n.parentElement;i;i=i.parentElement)if(qu(i)){e=i;break}return e?e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>Wu(i)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===n:!1}function vo(n){const e=[];let t=!1;const i=n.getAttribute("role");if(i)for(const r of i.split(/\s+/).filter(Boolean))if((r==="presentation"||r==="none")&&(t=!0),r==="heading"){let o=2;const a=parseInt(n.getAttribute("aria-level")??"",10);Number.isFinite(a)&&a>=1&&(o=Math.min(a,6)),e.push(Mu[o-1])}else ms[r]&&e.push(ms[r]);const s=n.getAttribute("epub:type");if(s)for(const r of s.split(/\s+/).filter(Boolean)){const o=_u[r];o&&e.push(o)}return{attrRoles:e,presentational:t}}function yo(n){const{attrRoles:e,presentational:t}=vo(n);return e.length>0||t}function qe(n){const e=[],t=o=>{e.includes(o)||e.push(o)},{attrRoles:i,presentational:s}=vo(n),r=n.tagName.toLowerCase();if(s)return["presentation"];if(Hu(n,r,i)&&ju(n))return["presentation"];if(r==="body")t("body");else if(r==="th")switch(n.getAttribute("scope")){case"col":t("columnheader");break;case"row":t("rowheader");break;default:{const o=n.parentElement;o&&Ku(o)?t("columnheader"):n.previousElementSibling===null?t("rowheader"):t("cell")}}else{const o=Bu[r];o&&t(o)}for(const o of i)t(o);return e}function Ss(n){return!!(n.getAttribute("aria-hidden")==="true"||n.hasAttribute("hidden"))}function Gu(n){let e="";const t=i=>{i.nodeType===3&&(e+=i.nodeValue??"");for(let s=i.firstChild;s;s=s.nextSibling)t(s)};return t(n),e}function Bt(n){return Ce(Gu(n),!0).trim()}function Dn(n){let e="";const t=(i,s)=>{if(i.nodeType===3){e+=i.nodeValue??"";return}if(!(i.nodeType===1&&!s&&yo(i)))for(let r=i.firstChild;r;r=r.nextSibling)t(r,!1)};return t(n,!0),e}function vs(n){return Ce(Dn(n),!0).trim()}function Xu(n){if(Ss(n))return[null,!1];const e=(n.getAttribute("aria-labelledby")??"").trim();if(e){const r=[...new Set(e.split(/\s+/).filter(Boolean))],o=n.ownerDocument,a=r.map(l=>o.getElementById(l)).filter(l=>l!==null);if(a.length>0){let l="";a.forEach((u,h)=>{if(Ss(u))return;const d=u.getAttribute("aria-label");l+=d||Dn(u),h<a.length-1&&(l+=" ")});const c=Ce(l,!0).trim();if(c!=="")return[{language:"",plain:c},!0]}}const t=(n.getAttribute("aria-label")??"").trim();if(t)return[{language:"",plain:t},!0];const i=(n.getAttribute("aria-describedby")??"").trim();if(i){const o=[...new Set(i.split(/\s+/).filter(Boolean))].map(a=>n.ownerDocument.getElementById(a)).filter(a=>a!==null);if(o.length>0){const a=o.map(c=>Dn(c)).join(" "),l=Ce(a,!0).trim();if(l!=="")return[{language:"",plain:l},!0]}}const s=n.tagName.toLowerCase();if(s==="img"){const r=(n.getAttribute("alt")??"").trim();if(r)return[{language:"",plain:r},!0];const o=(n.getAttribute("title")??"").trim();if(o)return[{language:"",plain:o},!0]}else if(s==="svg"){const r=n.querySelector(":scope > title");if(r){const o=Bt(r);if(o)return[{language:"",plain:o},!0]}}else if(s==="math"){const r=(n.getAttribute("alttext")??"").trim();if(r)return[{language:"",plain:r},!0]}return[null,!0]}const Ju={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Yu(n){return Ju[n]??["",void 0]}const Qu=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]),Zu=1;function ys(n){for(let e=n;e;e=e.parentElement){const t=e.getAttribute("xml:lang");if(t)return t;const i=e.getAttribute("lang");if(i)return i}return""}function eh(n){for(let e=n.firstChild;e;e=e.nextSibling)if(e.nodeType===Zu)return!0;return!1}function bo(n,e){for(let t=e;t;t=t.parentElement)if(t===n)return!0;return!1}const th=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]);function nh(n){return th.has(n)}function ih(n){const e=n.slice(0,500);return/<\?xml\b/.test(e)||/xmlns:epub=/.test(e)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(e)?"application/xhtml+xml":"text/html"}function wo(n){return typeof n=="object"&&n!==null&&n.nodeType===Node.ELEMENT_NODE}const Xe={NONE:"",DESCENDANT:" ",CHILD:" > "},D={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"};function sh(n,e){return Object.values(n).includes(e)}const rh="CssSelectorGenerator";function Tt(n="unknown problem",...e){console.warn(`${rh}: ${n}`,...e)}const oh={selectors:[D.id,D.class,D.tag,D.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1,ignoreGeneratedClassNames:!1};function _e(n){return!!n}function ah(n){return Array.isArray(n)?n.filter(e=>sh(D,e)):[]}function xo(n){return n instanceof RegExp}function lh(n){return["string","function"].includes(typeof n)||xo(n)}function bs(n){return Array.isArray(n)?n.filter(lh):[]}function ch(n){return n!=null&&typeof n=="object"&&"nodeType"in n&&typeof n.nodeType=="number"}function ws(n){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return ch(n)&&e.includes(n.nodeType)}function Eo(n,e){if(ws(n))return n.contains(e)||Tt("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element's real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will not work as intended."),n;const t=e.getRootNode({composed:!1});return ws(t)?(t.nodeType!==Node.DOCUMENT_NODE&&Tt("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),t):ii(e)}function en(n){return typeof n=="number"?n:Number.POSITIVE_INFINITY}function uh(n,e={}){const t=Object.assign(Object.assign({},oh),e);return{selectors:ah(t.selectors),whitelist:bs(t.whitelist),blacklist:bs(t.blacklist),root:Eo(t.root,n),combineWithinSelector:_e(t.combineWithinSelector),combineBetweenSelectors:_e(t.combineBetweenSelectors),includeTag:_e(t.includeTag),maxCombinations:en(t.maxCombinations),maxCandidates:en(t.maxCandidates),useScope:_e(t.useScope),maxResults:en(t.maxResults),ignoreGeneratedClassNames:_e(t.ignoreGeneratedClassNames)}}function et(n=[]){const[e=[],...t]=n;return t.length===0?e:t.reduce((i,s)=>{const r=new Set(s);return i.filter(o=>r.has(o))},e)}function hh(n){return[].concat(...n)}function dh(n){return n.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function Nt(n){const e=n.map(t=>{if(xo(t))return i=>t.test(i);if(typeof t=="function")return i=>{const s=t(i);return typeof s!="boolean"?(Tt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):s};if(typeof t=="string"){const i=new RegExp("^"+dh(t)+"$");return s=>i.test(s)}return Tt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1});return t=>e.some(i=>i(t))}function ni(n,e,t){const i=Eo(t,n[0]).querySelectorAll(e);if(i.length!==n.length)return!1;const s=new Set(i);return n.every(r=>s.has(r))}function Co(n,e){e=e??ii(n);const t=[];let i=n;for(;i&&i!==e;)wo(i)&&t.push(i),i=i.parentNode;return t}function fh(n,e){return et(n.map(t=>Co(t,e)))}function gh(n){return typeof n=="object"&&n!==null&&"nodeType"in n&&n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function ii(n){return n.ownerDocument.querySelector(":root")}const ko=", ",ph=new RegExp(["^$","\\s"].join("|")),mh=new RegExp(["^$"].join("|")),Ro=[D.nthoftype,D.tag,D.id,D.class,D.attribute,D.nthchild],Sh=Nt(["class","id","ng-*"]);function vh({name:n}){return`[${n}]`}function yh({name:n,value:e}){return`[${n}='${e}']`}function bh({nodeName:n,nodeValue:e},t){const i=t.tagName.toLowerCase();return["input","option"].includes(i)&&n==="value"||n==="src"&&e?.startsWith("data:")?!1:!Sh(n)}function wh({nodeName:n,nodeValue:e}){return{name:Ae(n),value:Ae(e??void 0)}}function Ao(n,e){const t=Array.from(n.attributes).filter(i=>bh(i,n)).map(wh);return[...t.map(vh),...t.map(yh)]}function xh(n,e){const t=n.map(i=>Ao(i));return et(t)}const Eh=/^[a-z_-]{3,}$/i,Ch=/[bcdfghjklmnpqrstvwxyz]{4,}/i;function kh(n){if(!Eh.test(n)||n.includes("_")&&!n.includes("__")||/^(css|sc|jsx|emotion|makeStyles|MuiButton|MuiBox)-/i.test(n))return!1;const e=n.split(new RegExp("--|__|[-]|(?<=[a-z])(?=[A-Z])")).filter(t=>t.length>0);if(e.length===0||e.length===1&&e[0].length<4)return!1;for(const t of e)if(t.length<=2||Ch.test(t))return!1;return!0}function Oo(n,e){var t;const i=((t=n.getAttribute("class"))!==null&&t!==void 0?t:"").trim().split(/\s+/).filter(r=>!mh.test(r));let s=i;if(e?.ignoreGeneratedClassNames){const r=Nt(e.whitelist);s=i.filter(o=>{const a=`.${Ae(o)}`;return r(a)?!0:kh(o)})}return s.map(r=>`.${Ae(r)}`)}function Rh(n,e){const t=n.map(i=>Oo(i,e));return et(t)}function To(n,e){var t;const i=(t=n.getAttribute("id"))!==null&&t!==void 0?t:"",s=`#${Ae(i)}`,r=n.getRootNode({composed:!1});return!ph.test(i)&&ni([n],s,r)?[s]:[]}function Ah(n,e){return n.length===0||n.length>1?[]:To(n[0])}function No(n,e){const t=n.parentNode,i=t&&"children"in t?t.children:null;if(i){for(let s=0;s<i.length;s++)if(i[s]===n)return[`:nth-child(${String(s+1)})`]}return[]}function Oh(n,e){return et(n.map(t=>No(t)))}function Do(n,e){return[Ae(n.tagName.toLowerCase())]}function Po(n,e){const t=[...new Set(hh(n.map(i=>Do(i))))];return t.length===0||t.length>1?[]:[t[0]]}function Fo(n,e){const t=Po([n])[0],i=n.parentNode,s=i&&"children"in i?i:null;if(s){const o=Array.from(s.children).filter(a=>a.tagName.toLowerCase()===t).indexOf(n);if(o>-1)return[`${t}:nth-of-type(${String(o+1)})`]}return[]}function Th(n,e){return et(n.map(t=>Fo(t)))}function*Io(n=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let t=0,i=Lo(1);for(;i.length<=n.length&&t<e;){t+=1;const s=new Array(i.length);for(let r=0;r<i.length;r++)s[r]=n[i[r]];yield s,i=Dh(i,n.length-1)}}function Nh(n=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(Io(n,{maxResults:e}))}function Dh(n=[],e=0){const t=n.length;if(t===0)return n;let i=t-1;for(;i>=0&&n[i]===e-(t-1-i);)i-=1;if(i<0)return Lo(t+1);n[i]+=1;for(let s=i+1;s<t;s++)n[s]=n[s-1]+1;return n}function Lo(n=1){const e=new Array(n);for(let t=0;t<n;t++)e[t]=t;return e}function*Ph(n={}){const e=Object.entries(n);if(e.length===0)return;const t=[{index:e.length-1,partial:{}}];for(;t.length>0;){const i=t.pop();if(!i)break;const{index:s,partial:r}=i;if(s<0){yield r;continue}const[o,a]=e[s];for(let l=a.length-1;l>=0;l--)t.push({index:s-1,partial:Object.assign(Object.assign({},r),{[o]:a[l]})})}}const Fh="3a".toUpperCase(),Ih=/[ !"#$%&'()[\]{|}<>*+,./;=?@^`~\\]/;function Ae(n=""){return CSS?CSS.escape(n):Lh(n)}function Lh(n=""){return n.split("").map(e=>e===":"?`\\${Fh} `:Ih.test(e)?`\\${e}`:escape(e).replace(/%/g,"\\")).join("")}const $h={tag:Po,id:Ah,class:Rh,attribute:xh,nthchild:Oh,nthoftype:Th},Mh={tag:Do,id:To,class:Oo,attribute:Ao,nthchild:No,nthoftype:Fo};function _h(n,e,t){return Mh[e](n,t)}function Bh(n,e,t){const i=$h[e];return i(n,t)}function Uh(n=[],e,t){return n.filter(i=>t(i)||!e(i))}function zh(n=[],e){return n.sort((t,i)=>{const s=e(t),r=e(i);return s&&!r?-1:!s&&r?1:0})}function Ut(){const n=new Map;let e;return(t,i)=>{if(t.length!==1)return e??(e=xs(t,i));const[s]=t;let r=n.get(s);return r||(r=xs(t,i),n.set(s,r)),r}}function*Vh(n,e,t=Ut()){const i=new Set,s=t(n,e);for(const r of Wh(s,e))i.has(r)||(i.add(r),yield r)}function xs(n,e){const{blacklist:t,whitelist:i,combineWithinSelector:s,maxCombinations:r}=e,o=Nt(t),a=Nt(i),l=(c,u)=>{const h=Bh(n,u,e),d=Uh(h,o,a),f=zh(d,a);return c[u]=s?Array.from(Io(f,{maxResults:r})):f.map(g=>[g]),c};return jh(e).reduce(l,{})}function jh(n){const{selectors:e,includeTag:t}=n,i=[...e];return t&&!i.includes("tag")&&i.push("tag"),i}function Hh(n){return n.includes(D.tag)||n.includes(D.nthoftype)?[...n]:[...n,D.tag]}function qh(n){const{selectors:e,combineBetweenSelectors:t,includeTag:i,maxCandidates:s}=n,r=t?Nh(e,{maxResults:s}):e.map(o=>[o]);return i?r.map(Hh):r}function*Wh(n,e){for(const t of qh(e))yield*Kh(t,n)}function*Kh(n,e){const t={};for(const i of n){const s=e[i];s&&s.length>0&&(t[i]=s)}for(const i of Ph(t))yield Xh(i)}function Gh(n,e){return e[n]?e[n].join(""):""}function Xh(n={}){const e=[...Ro];return n[D.tag]&&n[D.nthoftype]&&e.splice(e.indexOf(D.tag),1),e.map(t=>Gh(t,n)).join("")}function Jh(n,e){return[...n.map(t=>e+Xe.DESCENDANT+t),...n.map(t=>e+Xe.CHILD+t)]}function*Yh(n,e){if(e==="")yield*n;else for(const t of n)yield*Jh([t],e)}function*Qh(n,e,t="",i,s=Ut()){const r=Vh(n,i,s);for(const o of Yh(r,t))ni(n,o,e)&&(yield o)}function*Zh(n,e,t="",i,s=Ut()){if(n.length===0)return null;const r=[n.length>1?n:[],...fh(n,e).map(o=>[o])];for(const o of r)for(const a of Qh(o,e,t,i,s))yield{foundElements:o,selector:a}}function*ed({elements:n,root:e,rootSelector:t="",options:i}){let s=e,r=t,o=!0;const a=Ut();for(;o;){let l=!1;for(const c of Zh(n,s,r,i,a)){const{foundElements:u,selector:h}=c;if(l=!0,ni(n,h,e))yield h;else{s=u[0],r=h;break}}l||(o=!1)}}function td(n){(n instanceof NodeList||n instanceof HTMLCollection)&&(n=Array.from(n));const e=(Array.isArray(n)?n:[n]).filter(wo);return[...new Set(e)]}function nd(n){return{value:n,include:!1}}function id(n,e,t=Xe.NONE){const i={};return e.forEach(s=>{Reflect.set(i,s,_h(n,s).map(nd))}),{element:n,operator:t,selectors:i}}function sd({selectors:n,operator:e}){let t=[...Ro];n[D.tag]&&n[D.nthoftype]&&(t=t.filter(s=>s!==D.tag));let i="";return t.forEach(s=>{var r;((r=n[s])!==null&&r!==void 0?r:[]).forEach(({value:a,include:l})=>{l&&(i+=a)})}),e+i}function rd(n,e){const t=Co(n,e).reverse(),i=gh(e),s=t.map((o,a)=>{var l;const c=id(o,[D.nthchild],i&&a===0?Xe.NONE:Xe.CHILD);return((l=c.selectors.nthchild)!==null&&l!==void 0?l:[]).forEach(u=>{u.include=!0}),c});return[i?"":e?":scope":":root",...s.map(sd)].join("")}function od(n,e){return n.map(t=>rd(t,e)).join(ko)}var ad=function(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t};function $o(n,e={}){const t=Object.assign(Object.assign({},e),{maxResults:1});return ld(n,t).next().value}function*ld(n,e={}){var t;const i=td(n),s=uh(i[0],e),r=(t=s.root)!==null&&t!==void 0?t:ii(i[0]);let o=0;for(const l of ed({elements:i,options:s,root:r,rootSelector:""}))if(yield l,o++,o>=s.maxResults)return;if(i.length>1){const{maxResults:l}=e,c=ad(e,["maxResults"]);if(yield i.map(u=>$o(u,c)).join(ko),o++,o>=s.maxResults)return}const a=e.root!==void 0;yield od(i,s.useScope||a?r:void 0)}function si(n,e){return n.querySelectorAll(`#${CSS.escape(e)}`).length===1}function cd(n){const e=n.getAttribute("id");if(e&&si(n.ownerDocument,e))return`#${CSS.escape(e)}`;const t=n.parentElement,i=n.tagName.toLowerCase();if(!t)return i;const s=Array.from(t.children);for(const r of n.classList){const o=`.${CSS.escape(r)}`;if(s.filter(a=>a.matches(o)).length===1)return o}return s.filter(r=>r.tagName===n.tagName).length===1?i:`${i}:nth-child(${s.indexOf(n)+1})`}function Mo(n,e){const t=[];let i=n;for(;i&&i!==e;){const s=cd(i);if(t.unshift(s),s.startsWith("#"))return t;i=i.parentElement}return i===e?t:void 0}function ud(n){if(!n)return null;const e=n.getAttribute("id");if(e&&si(n.ownerDocument,e))return`#${CSS.escape(e)}`;const t=n.ownerDocument.documentElement,i=Mo(n,t)??[];return i.length>0&&i[0].startsWith("#")?i.join(" > "):[t.tagName.toLowerCase(),...i].join(" > ")}function zt(n,e,t){const i=n.getAttribute("id");if(i&&(!e||si(n.ownerDocument,i)))return`#${CSS.escape(i)}`;if(!e)return $o(n,{selectors:["id","class","tag","nthchild"]})??void 0;if(n===e)return t??void 0;const s=Mo(n,e);if(!(!s||s.length===0))return s[0].startsWith("#")?s.join(" > "):t?`${t} > ${s.join(" > ")}`:s.join(" > ")}function _o(n,e){if(!n)return;const t=e.getAttribute("id");return!!t&&n===`#${CSS.escape(t)}`?n:no(n)}const hd=3;function dd(n,e){let t=0;for(const i of Array.from(n.childNodes)){if(i===e)return t;i.nodeType===hd&&t++}return t}function Es(n,e,t,i,s){const r=n.parentElement;if(!r)return;const o=s&&r===s.el?s.selector:zt(r,t,i);if(o)return{cssSelector:o,textNodeIndex:dd(r,n),charOffset:e}}function fd(n,e,t,i){const s=Es(...n.first,e,t,i);if(!s)return;const r=Es(...n.last,e,t,i);return r?{start:s,end:r}:{start:s}}function gd(n){const e=Nl(n);return e.status===ie.SUCCESS?e.fragment:void 0}const Bo="leaf-text";function Cs(n){if(n===!0)return e=>e.length>0;if(Array.isArray(n)&&n.length>0){const e=new Set(n.filter(t=>t!==Bo));return t=>t.some(i=>e.has(i))}return null}function ks(n){return n===!0||Array.isArray(n)&&n.includes(Bo)}function pd(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function md(n){return pd(n)?{predicate:Cs(n.roles),leafText:ks(n.roles),domRange:!!n.domRange,textFragment:!!n.textFragment}:{predicate:Cs(n),leafText:ks(n),domRange:!1,textFragment:!1}}class Sd{claimed=new Set;counters=new Map;allocate(e,t){for(;;){const i=(this.counters.get(e)??0)+1;this.counters.set(e,i);const s=`${e}${i}`;if(!(t(s)||this.claimed.has(s)))return this.claimed.add(s),s}}claim(e){return this.claimed.has(e)?!1:(this.claimed.add(e),!0)}}function vd(n){for(let e=n.parentElement;e;e=e.parentElement)if(qe(e).includes("endnotes"))return!0;return!1}function yd(n,e,t){const i=[],s=(r,o)=>{const a=r.getAttribute("id");if(a&&!e.has(a)&&e.set(a,r),o=o||r.getAttribute("aria-hidden")==="true"||r.hasAttribute("hidden"),!o&&r.tagName.toLowerCase()==="a"&&qe(r).includes("noteref")){const c=r.getAttribute("href")??"";c.startsWith("#")&&i.push({id:c.slice(1),ref:r})}for(let l=r.firstElementChild;l;l=l.nextElementSibling)s(l,o)};s(n,!1);for(const r of i){const o=e.get(r.id);o&&(bo(o,r.ref)||vd(o)||t.add(o))}}function bd(n,e,t,i){const s={role:i},r=(e.getAttribute("title")??"").trim();r?s.text={plain:r,ssml:"",language:""}:t&&(s.text={plain:t.plain??"",ssml:t.ssml??"",language:t.language},ei.add(s));const o=!!(s.text&&!Je(s.text)),a=!n.xmlParsed&&(eh(e)||o&&e.firstChild!==null);if(!o&&!a){const u=Bt(e);u&&(s.text={plain:u,ssml:"",language:""})}const l=zt(e,n.selectorRoot,n.selectorRootAnchor),c=_o(l,e);return c&&(s.textref=c),n.placeholder(e,"pagebreak",s),a}function wd(n,e,t){const i={role:t},s=Bt(e);s&&(i.text={plain:s,ssml:"",language:""});const r=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&r.startsWith("#")&&(o=r.slice(1)),r.startsWith("#")){const a=r.slice(1),l=n.ids.get(a);if(l&&!bo(l,e)&&n.noterefDepth<3){const c=n.spawnChild(l);c.convert(l);const u=c.result();u.length>0&&(i.children=u.map(h=>{const d=ho(h);return delete d.id,d}))}}!i.children&&r&&(i.children=[{textref:r}]),n.placeholder(e,"noteref",i,o||void 0)}function xd(n,e,t,i){const s={};if(t.length>0&&(s.role=t),i){s.text={plain:i.plain??"",ssml:i.ssml??"",language:i.language},ei.add(s);const o=zt(e,n.selectorRoot,n.selectorRootAnchor);o&&co.set(s,o)}else{const o=Bt(e);o&&(s.text={plain:o,ssml:"",language:""})}const r=e.getAttribute("href");r&&(s.textref=r),n.placeholder(e,t[0]??"link",s)}const Ed=3,Cd=1,kd=new Set(["summary","dfn","span"]);function Rs(n,e){return kd.has(n)&&e.length>0?!0:!nh(n)}class Dt{xmlParsed;ids=new Map;suppressed=new Set;idAlloc=new Sd;noterefDepth=0;allowNode=null;selectorPredicate=null;domRangeEnabled=!1;textFragmentEnabled=!1;leafTextEnabled=!1;docRoot=null;selectorRoot=null;selectorRootAnchor=null;root=new ht;current=this.root;foldedCaptions=new Set;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];flowFirstNode=null;flowFirstOffset=0;flowLastNode=null;flowLastOffset=0;lastFlowRange=null;lastFlowText=null;constructor(e){this.xmlParsed=e}spawnChild(e,t=1){const i=new Dt(this.xmlParsed);return i.ids=this.ids,i.suppressed=this.suppressed,i.idAlloc=this.idAlloc,i.noterefDepth=this.noterefDepth+t,i.allowNode=e,i.docRoot=this.docRoot,i.selectorRoot=this.selectorRoot,i.selectorRootAnchor=this.selectorRootAnchor,i.selectorPredicate=this.selectorPredicate,i.domRangeEnabled=this.domRangeEnabled,i.textFragmentEnabled=this.textFragmentEnabled,i.leafTextEnabled=this.leafTextEnabled,i}prescan(e){yd(e,this.ids,this.suppressed)}convert(e){this.prescan(e),this.walk(e)}convertChildren(e){this.prescan(e);for(let t=e.firstChild;t;t=t.nextSibling)this.walk(t);this.flushText()}result(){const e=this.root.finalize();return!e.children||e.children.length===0?Tn(e)?[]:[Nn(e)]:e.children.map(Nn)}descend(e,t){const i=new ht;i.el=e,i.noText=this.foldedCaptions.has(e)||(!yo(e)||t.includes("caption"))&&this.current.noText,this.current.children.push(i),this.current=i}appendChild(e){e.noText=this.current.noText,this.current.children.push(e)}walk(e){if(e.nodeType===Ed){this.text(e);return}if(e.nodeType!==Cd)return;const t=e,i=this.current,s=this.head(t);if(!s)for(let r=t.firstChild;r;r=r.nextSibling)this.walk(r);this.tail(t,s,i)}head(e){const t=e.tagName.toLowerCase();if(Qu.has(t)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[i,s]=Xu(e);if(!s&&e!==this.allowNode)return!0;const r=qe(e);if((t==="img"||t==="svg")&&(r.includes("presentation")||i===null&&e.hasAttribute("alt")&&e.getAttribute("alt").trim()===""))return!0;if(t==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(r.includes("pagebreak"))return!bd(this,e,i,r);if(t==="a"&&r.includes("noteref")&&e.getAttribute("href"))return wd(this,e,r),!0;if(t==="a"&&e.getAttribute("href"))return xd(this,e,r,i),!0;if(t==="img"){const l={role:r},c=e.getAttribute("src");return c&&(l.imgref=c),i&&(l.description=i.plain),this.placeholder(e,"image",l),!0}if(t==="audio"||t==="video"){const l={role:r};let c=e.getAttribute("src");if(!c){const u=e.querySelector(":scope > source[src]");u&&(c=u.getAttribute("src"))}return t==="audio"?c&&(l.audioref=c):c&&(l.videoref=c),i&&(l.description=i.plain),this.placeholder(e,t,l),!0}if(r.includes("image")||r.includes("math")){const l={role:r};return i&&(l.description=i.plain),this.placeholder(e,r.includes("math")?"math":"image",l),!0}if(!Rs(t,r))return!1;this.flushText(),this.descend(e,r);const o=this.current.object;if(r.length>0&&(o.role=r),i)o.description=i.plain,r.includes("figure")&&(this.current.noText=!0);else if(r.includes("figure")){const l=this.implicitCaptionOf(e);if(l){const c=vs(l);c&&(o.description=c,this.current.noText=!0)}}else if(r.includes("table")){const l=this.implicitCaptionOf(e);if(l){const c=vs(l);c&&(o.description=c,this.foldedCaptions.add(l))}}const a=e.getAttribute("id");return a&&(o.id=a),!1}implicitCaptionOf(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling)if(qe(t).includes("caption")&&!t.getAttribute("aria-labelledby"))return t;return null}tail(e,t,i){if(t)return;const s=e.tagName.toLowerCase(),r=qe(e);if(Rs(s,r)){this.flushText();const o=this.leafTextEnabled&&r.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(r)||o)&&this.applyTextref(e),this.current=i}}applyTextref(e){const t=this.current.object,i=zt(e,this.selectorRoot,this.selectorRootAnchor);if(t.textref=_o(i,e),this.domRangeEnabled&&this.lastFlowRange){const s=i?{el:e,selector:i}:void 0,r=fd(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,s);r&&(t.textref=so({...r,container:i}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const s=this.docRoot.createRange();s.setStart(...this.lastFlowRange.first),s.setEnd(...this.lastFlowRange.last);const r=gd(s);r&&(t.textref=`${t.textref??"#"}${oo(r)}`)}}text(e){if(this.current.noText)return;const t=e.nodeValue??"";if(/^\s*$/.test(t)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=Ce(t,this.flowEndsWithSpace),this.updateFlowSpace());return}const i=this.textContext(e);if(Ea(i,this.currentCtx)||(this.closeSegment(),this.currentCtx=i),this.textAcc+=Ce(t,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const s=e;this.flowFirstNode===null&&(this.flowFirstNode=s,this.flowFirstOffset=t.search(/\S/)),this.flowLastNode=s,this.flowLastOffset=t.length-(t.match(/\s+$/)?.[0].length??0)}}textContext(e){const t={lang:ys(e.parentElement),tag:""};for(let i=e.parentElement;i&&i!==this.current.el;i=i.parentElement){const[s,r]=Yu(i.tagName.toLowerCase());if(s&&s!=="break"){t.tag=s,t.attrs=r;break}}return t}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(e,t,i,s){if(Tn(i))return;const r=new ht;if(r.el=e,r.object=i,this.current.noText){this.appendChild(r);return}this.closeSegment(),this.pendingChildren.push(r),this.segments.push({kind:"placeholder",tag:t,child:r,candidateID:s??e.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let e=this.segments;const t=this.pendingChildren,i=this.flowFirstNode,s=this.flowFirstOffset,r=this.flowLastNode,o=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,e.length===0)return;for(;e.length>0;){const S=e[0];if(S.kind==="break"){e=e.slice(1);continue}if(S.kind==="text"){const v=S.text.replace(/^\s+/,"");if(v===""){e=e.slice(1);continue}e=[{...S,text:v},...e.slice(1)]}break}for(;e.length>0;){const S=e[e.length-1];if(S.kind==="break"){e=e.slice(0,-1);continue}if(S.kind==="text"){const v=S.text.replace(/\s+$/,"");if(v===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...S,text:v}]}break}if(!e.some(S=>S.kind==="text"&&S.text.trim()!=="")){for(const S of t)this.appendChild(S);return}const l=[];for(const S of e)if(S.kind==="text"&&S.text.trim()!==""){const v=S.ctx.lang;l.includes(v)||l.push(v)}let c=ys(this.current.el??null);l.length===1&&l[0]!==""&&(c=l[0]);let u=!1;for(const S of e)if(S.kind!=="text"||S.ctx.tag!==""||S.ctx.lang!==c){u=!0;break}if(u&&c===""&&(c="en"),u)for(const S of e){if(S.kind!=="placeholder")continue;let v=S.candidateID;(!v||!this.idAlloc.claim(v))&&(v=this.idAlloc.allocate(S.tag,b=>this.ids.has(b))),S.child.object.id=v}let h="",d=!1,f=!1,g=!1,p=!1;for(const S of e)if(S.kind==="text"){const v=S.text.startsWith(" "),b=S.text.replace(/^ +| +$/g,"");if(b===""){p=!0;continue}let C=!1;if(h.length>0){const R=d||p||v;f?C=!0:g?C=R&&!Oe(b):C=R}C&&(h+=" "),h+=b,d=S.text.endsWith(" "),f=!1,g=!1,p=!1}else S.kind==="break"?f=!0:S.kind==="placeholder"&&(g=!0);const m=e.some(S=>S.kind==="placeholder");this.lastFlowText=h.trim();const y={plain:u&&!m?"":h.trim(),ssml:"",language:c};if(u){let S="";for(const v of e)if(v.kind==="text"){let b=v.ctx.tag,C=v.ctx.attrs;if(v.ctx.lang!==c&&v.ctx.lang!==""&&(b="lang",C=void 0),b){S+=`<${b}`;for(const[R,A]of Object.entries(C??{}))S+=` ${R}="${jt(A)}"`;v.ctx.lang!==c&&v.ctx.lang!==""&&(S+=` xml:lang="${jt(v.ctx.lang)}"`),S+=`>${X(v.text)}</${b}>`}else S+=X(v.text)}else v.kind==="break"?S+="<break/>":v.kind==="placeholder"&&(S+=`<readium:${v.tag} id="${jt(v.child.object.id)}" />`);y.ssml=S}const w=new ht;w.object={text:y};for(const S of t)w.children.push(S);this.appendChild(w),i&&r&&(this.lastFlowRange={first:[i,s],last:[r,o]})}}const Rd=/<body[\s>]/i;function Uo(n,e,t){const{predicate:i,leafText:s,domRange:r,textFragment:o}=md(t?.textrefs);if(typeof n!="string"){const h=e??(n.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),d=new Dt(h==="application/xhtml+xml");return d.selectorPredicate=i,d.leafTextEnabled=s,d.domRangeEnabled=r,d.textFragmentEnabled=o,d.docRoot=n.ownerDocument,d.selectorRoot=n,d.selectorRootAnchor=ud(n),d.convert(n),d.result()}const a=e??ih(n),l=new DOMParser().parseFromString(n,a),c=new Dt(a==="application/xhtml+xml");c.selectorPredicate=i,c.leafTextEnabled=s,c.textFragmentEnabled=o,c.docRoot=l;const u=l.querySelector("body");return u&&!Rd.test(n)?c.convertChildren(u):c.convert(u??l.documentElement),c.result()}function Ad(n,e,t){return{guided:Uo(n,e,t)}}exports.BUILTIN_DECORATION_TYPES=Rr;exports.BooleanPreference=Mr;exports.DecorationController=Fr;exports.DecorationLayout=Er;exports.DecorationStyleType=E;exports.DecorationWidth=xr;exports.Decorator=kr;exports.DirectCommsChannel=Nr;exports.DirectCommsFrame=Dr;exports.DirectCommsHost=Pr;exports.EnumPreference=ve;exports.FallbackEngineProvider=sl;exports.FallbackSpeechEngine=Ws;exports.Locator=Vn;exports.LocatorLocations=te;exports.LocatorText=zn;exports.Preference=Qe;exports.RangePreference=Ve;exports.ReadiumSpeechDecorationController=Lr;exports.ReadiumSpeechNavigator=$u;exports.ReadiumSpeechProviderRegistry=pc;exports.SpeechDefaults=$r;exports.SpeechPreferences=Re;exports.SpeechPreferencesEditor=yn;exports.SpeechServerAudioDecodeError=Mn;exports.SpeechServerEngine=Hs;exports.SpeechServerEngineProvider=tl;exports.SpeechServerError=ke;exports.SpeechServerNetworkError=_n;exports.SpeechServerStallError=$n;exports.SpeechSettings=wn;exports.StringArrayPreference=vn;exports.WebSpeechEngine=cn;exports.WebSpeechEngineProvider=Va;exports.WebSpeechVoiceManager=T;exports.blockLevelRoles=Jr;exports.chineseVariantMap=xe;exports.chunkPlainText=Bs;exports.chunkSsmlText=Us;exports.contextualizationShapesAtVerbosity=Vr;exports.contextualizedAtVerbosity=zr;exports.createLocator=Ir;exports.decodeCssSelectorFragment=io;exports.decodeDomRangeFragment=ro;exports.decodeTextref=On;exports.decorationsEqual=Or;exports.defaultContextualizations=Xn;exports.encodeCssSelectorFragment=no;exports.encodeDomRangeFragment=so;exports.extractUtterances=Iu;exports.isRecoverableFailure=qs;exports.makeGnd=Ad;exports.mapServerVoice=Ln;exports.mimeTypeForFormat=zs;exports.parseMarkup=Uo;exports.resolveBoundaryLocate=qr;exports.resolveDecorationForWire=Sn;exports.resolveUtteranceLocate=Wr;exports.selectBitrate=js;exports.selectFormat=Vs;exports.setupDecorations=gc;exports.shapeableRoles=Sc;exports.skippableRoles=tu;exports.skippedAtVerbosity=Ur;exports.supportsDecorationStyle=Ar;exports.toSpeechServerError=be;
|
|
24
|
+
`)}positionElement(e,t,i,s,r,o,a=0){const l=e.decoration?.style?.width,c=r;switch(l){case"viewport":{const u=Math.floor(t.inlineStart(c)/t.viewportInlineSize)*t.viewportInlineSize;t.applyPosition(s,u+t.inlineScrollOffset+a,t.blockStart(c)+t.blockScrollOffset,t.viewportInlineSize-2*a,t.blockSize(c),i);break}case"page":{const u=Math.floor(t.inlineStart(c)/t.pageInlineSize)*t.pageInlineSize;t.applyPosition(s,u+t.inlineScrollOffset+a,t.blockStart(c)+t.blockScrollOffset,t.pageInlineSize-2*a,t.blockSize(c),i);break}case"bounds":{t.applyPosition(s,t.inlineStart(o)+t.inlineScrollOffset,t.blockStart(c)+t.blockScrollOffset,t.inlineSize(o),t.blockSize(c),i);break}default:t.applyPosition(s,t.inlineStart(c)+t.inlineScrollOffset,t.blockStart(c)+t.blockScrollOffset,t.inlineSize(c),t.blockSize(c),i)}}computeOverlayRects(e,t,i,s){if(e.decoration?.style?.layout==="bounds")return[s?{left:i.left-s,right:i.right+s,top:i.top-s,bottom:i.bottom+s,width:i.width+s*2,height:i.height+s*2}:i];const r=e.decoration.style.type,o=r===E.Underline||r===E.Strikethrough,a=r===E.Strikethrough,l=o?ec(e.range,["rt","rp"]):e.range;let c=$e(l,!0,t.isVertical,o?0:s);return c=c.sort((u,h)=>t.isVertical?(t.isVertLR?1:-1)*(u.left-h.left):u.top-h.top),c.map(u=>{let h=u;if(a){const d=t.blockSize(u)*.1,f=t.blockStart(u)+t.blockSize(u)/2-d/2;h=t.isVertical?{left:f,right:f+d,top:u.top,bottom:u.bottom,width:d,height:u.height}:{top:f,bottom:f+d,left:u.left,right:u.right,height:d,width:u.width}}return s&&o&&(h=t.isVertical?{...h,top:h.top-s,bottom:h.bottom+s,height:h.height+s*2}:{...h,left:h.left-s,right:h.right+s,width:h.width+s*2}),h})}repositionItem(e,t){if(!e.container)return!0;const i=e.decoration.style;if(i.type!==E.Template){const u=i.type??E.Highlight;if(u===E.TextColor||u===E.Mask)return!0}const s=1/this.effectiveZoom(),r=i.expand??0,o=e.range.getBoundingClientRect(),a=(()=>{if(i.type!==E.Outline)return 0;const u=i.width;return u==="page"||u==="viewport"?3:0})(),l=this.computeOverlayRects(e,t,o,r),c=Array.from(e.container.children);return c.length!==l.length?!1:(c.forEach((u,h)=>this.positionElement(e,t,s,u,l[h],o,a)),!0)}layout(e){if(this.experimentalHighlights&&!this.notTextFlag?.has(e.id))return this.experimentalLayout(e);const t=this.wnd.document.createElement("div");t.setAttribute("id",e.id),t.dataset.highlightId=e.decoration.id,t.style.setProperty("pointer-events","none");const i=de(this.wnd),s=1/this.effectiveZoom(),r=e.decoration.style.expand??0,o=e.range.getBoundingClientRect(),a=e.decoration.style,l=(()=>{if(a.type!==E.Outline)return 0;const h=a.width;return h==="page"||h==="viewport"?3:0})();let c;if(a.type===E.Template){a.stylesheet&&this.injectCustomStylesheet(a.stylesheet);const h=lc(this.wnd,a.element);if(!h){e.container=t,e.clickableElements=[];return}h.style.setProperty("pointer-events","none"),c=h}else{const h=a,d=h.type??E.Highlight,f=h.tint??Jt(d);if(d===E.TextColor){e.container=t,e.clickableElements=[];return}if(d===E.Mask){e.container=t,e.clickableElements=[],this.updateSharedMask();return}const g=this.getCurrentDarkMode(),p=this.getBackgroundColor(),m=h.enforceContrast!==!1,v=(()=>{switch(d){case E.Underline:{const S=m?ge(f,p):f,y=h.layout==="bounds",[b,C]=i.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[y?`${C}: 0.1em solid ${S} !important`:null,`${b}: 0.1em solid ${S} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case E.Strikethrough:{const S=m?ge(f,p):f;return h.layout==="bounds"?[`background: repeating-linear-gradient(-45deg, transparent, transparent 19px, ${S} 19px, ${S} 20px) !important`,"background-color: transparent !important","box-sizing: border-box !important"].join("; "):[`background-color: ${S} !important`,"box-sizing: border-box !important"].join("; ")}case E.Outline:return[`outline: 2px solid ${m?ge(f,p):f} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case E.HighlightUnderline:{const S=m?ge(f,p):f,{r:y,g:b,b:C}=ce(S),R=`rgba(${y}, ${b}, ${C}, 0.3)`,A=h.layout==="bounds",[N,O]=i.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${R} !important`,A?`${O}: 0.1em solid ${S} !important`:null,`${N}: 0.1em solid ${S} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case E.Highlight:default:return[`background-color: ${m?ge(f,p):f} !important`,`mix-blend-mode: ${g?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important","transform: translateZ(0) !important"].join("; ")}})(),w=this.wnd.document.createElement("template");w.innerHTML=`<div data-readium="true" class="readium-${d}" style="${v}"></div>`.trim(),c=w.content.firstElementChild}const u=this.computeOverlayRects(e,i,o,r);for(const h of u){const d=c.cloneNode(!0);d.style.setProperty("pointer-events","none"),this.positionElement(e,i,s,d,h,o,l),t.append(d)}e.container=t,e.clickableElements=Array.from(t.querySelectorAll("[data-activable='1']")),e.clickableElements.length||(e.clickableElements=Array.from(t.children))}renderLayout(e){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{e=e.filter(t=>!this.experimentalHighlights||!!this.notTextFlag?.has(t.id)),!(!e||e.length===0)&&this.requireContainer().append(...e.map(t=>t.container).filter(t=>!!t))})}requireContainer(e=!1){if(e){let t;return this.wnd.document.getElementById(`${this.id}-style`)?t=this.wnd.document.getElementById(`${this.id}-style`):(t=this.wnd.document.createElement("style"),t.dataset.readium="true",t.id=`${this.id}-style`,this.wnd.document.head.appendChild(t)),t}return this.container||(this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.shadowRoot.appendChild(this.container)),this.container}getCurrentDarkMode(){return yi(this.wnd,"--USER__appearance")==="readium-night-on"||Ys(this.getBackgroundColor())}getBackgroundColor(){return yi(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color")}updateSharedMask(){const e=this.items.filter(d=>d.decoration.style?.type===E.Mask);if(e.length===0){this.maskSvg&&(this.maskSvg.remove(),this.maskSvg=void 0),this.shadowHost&&!this.container&&(this.shadowHost.remove(),this.shadowRoot=void 0,this.shadowHost=void 0);return}const t=de(this.wnd),i=1/this.effectiveZoom(),s=this.wnd.document.documentElement,r=s.scrollWidth,o=s.scrollHeight,a=[];for(const d of e){const f=d.decoration.style,g=f.layout??"boxes",p=f.width??"wrap",m=f.expand??0,v=d.range.getBoundingClientRect(),w=g==="bounds"?[m?{left:v.left-m,top:v.top-m,right:v.right+m,bottom:v.bottom+m,width:v.width+m*2,height:v.height+m*2}:v]:$e(d.range,!1,!1,m);for(const S of w){let y;switch(p){case"viewport":{const b=Math.floor(t.inlineStart(S)/t.viewportInlineSize)*t.viewportInlineSize;y=t.toRect(b,t.blockStart(S),t.viewportInlineSize,t.blockSize(S));break}case"page":{const b=Math.floor(t.inlineStart(S)/t.pageInlineSize)*t.pageInlineSize;y=t.toRect(b,t.blockStart(S),t.pageInlineSize,t.blockSize(S));break}case"bounds":{y=t.toRect(t.inlineStart(v),t.blockStart(S),t.inlineSize(v),t.blockSize(S));break}default:y=t.toRect(t.inlineStart(S),t.blockStart(S),t.inlineSize(S),t.blockSize(S))}a.push(y)}}const l=[`M0 0 H${r} V${o} H0 Z`,...a.map(d=>{const f=(d.left+t.xDocOffset)*i,g=(d.top+t.yDocOffset)*i,p=(d.right+t.xDocOffset)*i,m=(d.bottom+t.yDocOffset)*i;return`M${f} ${g} H${p} V${m} H${f} Z`})].join(" "),c="http://www.w3.org/2000/svg";if(!this.maskSvg){this.shadowRoot||(this.shadowHost=this.wnd.document.createElement("div"),this.shadowHost.style.cssText="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none",this.wnd.document.body.appendChild(this.shadowHost),this.shadowRoot=this.shadowHost.attachShadow({mode:"open"})),this.maskSvg=this.wnd.document.createElementNS(c,"svg"),this.maskSvg.style.cssText=`position:absolute;top:0;left:0;width:${r}px;height:${o}px;pointer-events:none;z-index:2147483647`,this.maskSvg.dataset.readium="true";const d=this.wnd.document.createElementNS(c,"defs"),f=this.wnd.document.createElementNS(c,"clipPath"),g=`${this.id}-mask-clip`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","userSpaceOnUse");const p=this.wnd.document.createElementNS(c,"path");p.setAttribute("clip-rule","evenodd"),f.appendChild(p),d.appendChild(f),this.maskSvg.appendChild(d);const m=this.wnd.document.createElementNS(c,"rect");m.setAttribute("id",`${this.id}-mask-rect`),m.setAttribute("clip-path",`url(#${g})`),m.style.pointerEvents="none",this.maskSvg.appendChild(m),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${r}px`,this.maskSvg.style.height=`${o}px`;const u=this.maskSvg.querySelector("path");u&&u.setAttribute("d",l);const h=this.maskSvg.querySelector("rect");if(h){const d=e[0].decoration.style.tint,f=d??this.getBackgroundColor()??Jt(E.Mask),g=d?"1":"0.5";h.setAttribute("x","0"),h.setAttribute("y","0"),h.setAttribute("width",String(r)),h.setAttribute("height",String(o)),h.setAttribute("fill",f),h.setAttribute("fill-opacity",g)}}injectCustomStylesheet(e){const t=`${this.id}-custom-style`;let i=this.wnd.document.getElementById(t);i||(i=this.wnd.document.createElement("style"),i.id=t,i.dataset.readium="true",this.wnd.document.head.appendChild(i)),i.innerHTML=e}clearContainer(){if(this.experimentalHighlights){const e=this.wnd.CSS.highlights;for(const t of this._tintSubKeys.values())e.delete(t);this._tintSubKeys.clear(),this._subKeyCounter=0}this.wnd.document.getElementById(`${this.id}-custom-style`)?.remove(),this.container&&(this.container.remove(),this.container=void 0)}}const kr=class Se extends ol{constructor(){super(...arguments),this.observedResizeTargets=new Map,this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this),this.scrollScheduled=!1,this.handleScroller=this.handleScroll.bind(this)}cleanup(){this.groups.forEach(e=>e.destroy()),this.groups.clear(),this.observedResizeTargets.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>e.requestLayout())},50)}handleScroll(){this.scrollScheduled||(this.scrollScheduled=!0,this.wnd.requestAnimationFrame(()=>{this.scrollScheduled=!1,this.groups.forEach(e=>{e.hasOverlayItems&&e.repositionOverlays()})}))}mount(e,t){return this.wnd=e,t.register("decorate",Se.moduleName,(i,s)=>{const r=i;(r.action==="add"||r.action==="update")&&r.decoration.locator&&(r.decoration.locator=Vn.deserialize(r.decoration.locator)),this.groups.has(r.group)||this.groups.set(r.group,new dc(e,t,`readium-decoration-${this.lastGroupId++}`,r.group));const o=this.groups.get(r.group);switch(r.action){case"add":o?.add(r.decoration);break;case"remove":o?.remove(r.decoration.id);break;case"clear":o?.clear();break;case"update":o?.update(r.decoration);break}s(!0)}),t.register("decoration_resize",Se.moduleName,(i,s)=>{const r=i;r.action==="watch"?this.addDecorationResizeTarget(r.selector):this.removeDecorationResizeTarget(r.selector),s(!0)}),t.register("decoration_activatable",Se.moduleName,(i,s)=>{const r=i,o=this.groups.get(r.group);o&&(o.activatable=r.activatable),s(!0)}),t.register("decoration_hoverable",Se.moduleName,(i,s)=>{const r=i,o=this.groups.get(r.group);o&&(o.hoverable=r.hoverable),s(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.documentElement),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),e.addEventListener("scroll",this.handleScroller,{passive:!0,capture:!0}),this.styleObserver=new MutationObserver(i=>{i.some(s=>s.type==="attributes"&&s.attributeName==="style"&&s.oldValue!==s.target.getAttribute("style"))&&this.updateHighlightStyles()}),this.styleObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0}),t.log("Decorator Mounted"),!0}unmount(e,t){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),e.removeEventListener("scroll",this.handleScroller,{capture:!0}),t.unregisterAll(Se.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}addDecorationResizeTarget(e){const t=this.observedResizeTargets.get(e);t&&this.resizeObserver.unobserve(t);const i=this.wnd.document.querySelector(e);i?(this.resizeObserver.observe(i),this.observedResizeTargets.set(e,i)):this.observedResizeTargets.delete(e)}removeDecorationResizeTarget(e){const t=this.observedResizeTargets.get(e);t&&(this.resizeObserver.unobserve(t),this.observedResizeTargets.delete(e))}};kr.moduleName="decorator";let Rr=kr;const Ar=new Set(Object.values(E));function Or(n,e){return n===E.TextColor?typeof window<"u"&&"Highlight"in window:Ar.has(n)?!0:!!e?.[n]}function Sn(n,e){const{style:t}=n;if(t.type===E.Template){const i=t;return{...n,style:{...i,element:Bi(i,n)}}}if(t.type&&e?.[t.type]){const i=e[t.type];return{...n,style:{type:E.Template,layout:i.layout,width:i.width,stylesheet:i.stylesheet,element:Bi(i,n)}}}return n}function Bi(n,e){return typeof n.element=="function"?n.element(e):n.element}function fc(n,e){if(n.type!==e.type)return!1;if(n.type===E.Template){const s=n,r=e;return s.layout===r.layout&&s.width===r.width&&s.stylesheet===r.stylesheet}const t=n,i=e;return t.tint===i.tint&&t.layout===i.layout&&t.width===i.width&&(t.enforceContrast??!0)===(i.enforceContrast??!0)&&(t.expand??0)===(i.expand??0)}function Tr(n,e){return n.locator.href===e.locator.href&&JSON.stringify(n.locator.locations?.serialize?.()??n.locator.locations)===JSON.stringify(e.locator.locations?.serialize?.()??e.locator.locations)&&JSON.stringify(n.locator.text??null)===JSON.stringify(e.locator.text??null)&&fc(n.style,e.style)&&JSON.stringify(n.extras??null)===JSON.stringify(e.extras??null)}class Nr{constructor(){this.queue=[],this.channel=typeof MessageChannel<"u"?new MessageChannel:void 0,this.channel&&(this.channel.port1.onmessage=()=>this.flush())}push(e){const t=this.queue.length===0;this.queue.push(e),t&&(this.channel?this.channel.port2.postMessage(null):setTimeout(()=>this.flush(),0))}flush(){const e=this.queue;this.queue=[],e.forEach(t=>t())}clear(){this.queue=[]}}class Dr{constructor(){this.frame=new Pr(this),this.host=new Fr(this)}}class Pr{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new Nr,this.ready=!0}register(e,t,i){(Array.isArray(e)?e:[e]).forEach(s=>{const r=this.registrar.get(s)??[];if(r.find(o=>o.module===t))throw new Error(`Duplicate callback for "${s}" in module "${t}"`);r.push({module:t,cb:i}),this.registrar.set(s,r)})}unregister(e,t){(Array.isArray(e)?e:[e]).forEach(i=>{const s=this.registrar.get(i);s&&this.registrar.set(i,s.filter(r=>r.module!==t))})}unregisterAll(e){this.registrar.forEach((t,i)=>{this.registrar.set(i,t.filter(s=>s.module!==e))})}_dispatch(e,t,i){const s=this.registrar.get(e);if(!s?.length){i(!1);return}s.forEach(r=>r.cb(t,i))}send(e,t){this.outbox.push(()=>this.channel.host._receive(e,t))}log(...e){this.outbox.push(()=>this.channel.host._receive("log",e))}destroy(){this.registrar.clear(),this.outbox.clear()}}class Fr{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new Nr,this.ready=!0}send(e,t,i){this.outbox.push(()=>this.channel.frame._dispatch(e,t,i??(()=>{})))}on(e,t){const i=this.listeners.get(e)??[];i.push(t),this.listeners.set(e,i)}off(e,t){const i=this.listeners.get(e);i&&this.listeners.set(e,i.filter(s=>s!==t))}_receive(e,t){this.listeners.get(e)?.forEach(i=>i(t))}}class Ir{constructor(e,t={}){this.host=e,this._decorations=new Map,this._activationState=new Map,this._hoverState=new Map,this._observers=new Map,this._hoveredDecorations=new Map,this._config=t,t.resizeWatchSelectors?.forEach(i=>this.addDecorationResizeTarget(i)),e.on("decoration_activated",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId);r&&this._observers.get(s.group)?.forEach(o=>o.onDecorationActivated?.({group:s.group,decoration:r,rect:s.rect,point:s.point}))}),e.on("decoration_pointer_enter",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId);r&&(this._hoveredDecorations.set(s.group,r),this._observers.get(s.group)?.forEach(o=>o.onDecorationPointerEnter?.({group:s.group,decoration:r,rect:s.rect,point:s.point})))}),e.on("decoration_pointer_leave",i=>{const s=i,r=this._decorations.get(s.group)?.find(o=>o.id===s.decorationId)??this._hoveredDecorations.get(s.group);this._hoveredDecorations.delete(s.group),r&&this._observers.get(s.group)?.forEach(o=>o.onDecorationPointerLeave?.({group:s.group,decoration:r,rect:s.rect,point:s.point}))})}addDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"watch",selector:e})}removeDecorationResizeTarget(e){this.host.send("decoration_resize",{action:"unwatch",selector:e})}supportsDecorationStyle(e){return Or(e,this._config.decorationTemplates)}applyDecorations(e,t){const i=this._decorations.get(t)??[],s=new Map(i.map(l=>[l.id,l])),r=new Map(e.map(l=>[l.id,l]));for(const[l,c]of s){const u=r.get(l);u?Tr(c,u)||this.host.send("decorate",{group:t,action:"update",decoration:Sn(u,this._config.decorationTemplates)}):this.host.send("decorate",{group:t,action:"remove",decoration:{id:l}})}for(const[l,c]of r)s.has(l)||this.host.send("decorate",{group:t,action:"add",decoration:Sn(c,this._config.decorationTemplates)});this._decorations.set(t,e);const o=this._activationState.get(t);o!==void 0&&this.host.send("decoration_activatable",{group:t,activatable:o});const a=this._hoverState.get(t);a!==void 0&&this.host.send("decoration_hoverable",{group:t,hoverable:a})}registerDecorationObserver(e,t){this._observers.has(e)||this._observers.set(e,new Set),this._observers.get(e).add(t),t.onDecorationActivated&&(this._activationState.set(e,!0),this.host.send("decoration_activatable",{group:e,activatable:!0})),(t.onDecorationPointerEnter||t.onDecorationPointerLeave)&&(this._hoverState.set(e,!0),this.host.send("decoration_hoverable",{group:e,hoverable:!0}))}unregisterDecorationObserver(e){this._observers.forEach((t,i)=>{if(!t.has(e))return;t.delete(e);const s=[...t].some(o=>o.onDecorationActivated);this._activationState.has(i)&&!s&&(this._activationState.delete(i),this.host.send("decoration_activatable",{group:i,activatable:!1}));const r=[...t].some(o=>o.onDecorationPointerEnter||o.onDecorationPointerLeave);this._hoverState.has(i)&&!r&&(this._hoverState.delete(i),this.host.send("decoration_hoverable",{group:i,hoverable:!1}))})}destroy(){this._decorations.clear(),this._activationState.clear(),this._hoverState.clear(),this._observers.clear(),this._hoveredDecorations.clear()}}function gc(n){return new Xs({start:new St(n.start),end:n.end?new St(n.end):void 0})}function Lr(n,e=window){const{text:t,cssSelector:i,domRange:s,fragment:r}=n,o=t?new zn(t):void 0,a=i||s?new Map:void 0;a&&(i&&a.set("cssSelector",i),s&&a.set("domRange",gc(s).serialize()));const c=a!==void 0||r!==void 0?new te({fragments:r?[r]:void 0,otherLocations:a}):void 0;return new Vn({href:e.location.href,type:"text/html",text:o,locations:c})}class $r extends Ir{constructor(e,t,i,s={}){super(e.host,s),this.channel=e,this.wnd=t,this.decorator=i}decorate(e,t){this.applyDecorations(e.map(({id:i,style:s,...r})=>({id:i,style:s,locator:Lr(r,this.wnd)})),t)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function pc(n=window,e={}){const t=new Dr,i=new Rr;return i.mount(n,t.frame),new $r(t,n,i,e)}class mc{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`A provider is already registered under id "${e.id}"`);this.providers.set(e.id,e)}unregister(e){this.providers.delete(e)}get(e){return this.providers.get(e)}list(){return[...this.providers.values()]}async getVoices(e){return this.require(e).getVoices()}async getAllVoices(){return Promise.all(this.list().map(async e=>({providerId:e.id,voices:await e.getVoices()})))}async createEngine(e,t){return this.require(e).createEngine(t)}async destroy(){await Promise.all(this.list().map(e=>e.destroy())),this.providers.clear()}require(e){const t=this.providers.get(e);if(!t)throw new Error(`No provider registered under id "${e}"`);return t}}const vt={range:[0,5e3],step:100},bt={range:[.1,10],step:.1},wt={range:[0,2],step:.1},xt={range:[0,1],step:.05},jn=["none","few","some","most","custom"],Hn=["none","block-level","always"],qn=["plain","ssml"],Wn=["none","utterance","block"],Kn=["structure","sentence"],Ui=["format","inlineContextualization","verbosity","skip","contextualize","language","segmentation"];function Gn(n){return n==null||typeof n=="boolean"?n:void 0}function z(n,e){return n==null||e.includes(n)?n:void 0}function J(n,e){if(n==null)return n;if(typeof n!="number"||Number.isNaN(n))return;const t=Math.min(...e),i=Math.max(...e);return n>=t&&n<=i?n:void 0}function We(n){return n==null||Array.isArray(n)&&n.every(e=>typeof e=="string")?n:void 0}class Mr{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=z(e.format,qn)??"plain",this.inlineContextualization=Gn(e.inlineContextualization)??!1,this.verbosity=z(e.verbosity,jn)??"few",this.skip=We(e.skip)??[],this.contextualize=We(e.contextualize)??[],this.language=z(e.language,Hn)??"block-level",this.segmentation=z(e.segmentation,Kn)??"structure",this.pauseDuration=J(e.pauseDuration,vt.range)??300,this.autoPause=z(e.autoPause,Wn)??"none",this.rate=J(e.rate,bt.range)??1,this.pitch=J(e.pitch,wt.range)??1,this.volume=J(e.volume,xt.range)??1}}class Re{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=z(e.format,qn),this.inlineContextualization=Gn(e.inlineContextualization),this.verbosity=z(e.verbosity,jn),this.skip=We(e.skip),this.contextualize=We(e.contextualize),this.language=z(e.language,Hn),this.segmentation=z(e.segmentation,Kn),this.pauseDuration=J(e.pauseDuration,vt.range),this.autoPause=z(e.autoPause,Wn),this.rate=J(e.rate,bt.range),this.pitch=J(e.pitch,wt.range),this.volume=J(e.volume,xt.range)}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new Re(t)}}class Qe{_value;_effectiveValue;_isEffective;_onChange;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s}){this._value=e,this._effectiveValue=t,this._isEffective=i,this._onChange=s}set value(e){this._value=e,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null,this._onChange(this._value)}}class ye extends Qe{_supportedValues;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s,supportedValues:r}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:s}),this._supportedValues=r}set value(e){if(e!=null&&z(e,this._supportedValues)===void 0)throw new Error(`Value '${String(e)}' is not in the supported values for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedValues(){return this._supportedValues}}class _r extends Qe{set value(e){if(e!=null&&Gn(e)===void 0)throw new Error(`Value '${String(e)}' is not a boolean.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class yn extends Qe{set value(e){if(e!=null&&We(e)===void 0)throw new Error(`Value '${String(e)}' is not an array of strings.`);this._value=e,this._onChange(this._value)}get value(){return this._value}}class Ve extends Qe{_supportedRange;_step;_decimals;constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:s,supportedRange:r,step:o}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:s}),this._supportedRange=r,this._step=o,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e!=null&&J(e,this._supportedRange)===void 0)throw new Error(`Value '${String(e)}' is out of the supported range for this preference.`);this._value=e,this._onChange(this._value)}get value(){return this._value}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value!=null&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value!=null&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(e){return e.toString()}}class vn{preferences;settings;constructor(e,t){this.preferences=new Re({...e}),this.settings=t}clear(){this.preferences=new Re({format:null,inlineContextualization:null,verbosity:null,skip:null,contextualize:null,language:null,segmentation:null,pauseDuration:null,autoPause:null,rate:null,pitch:null,volume:null})}updatePreference(e,t){this.preferences[e]=t}get format(){return new ye({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:qn})}get inlineContextualization(){return new _r({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new ye({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:jn})}get skip(){return new yn({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new yn({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new ye({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:Hn})}get segmentation(){return new ye({initialValue:this.preferences.segmentation,effectiveValue:this.settings.segmentation,isEffective:this.preferences.segmentation!=null,onChange:e=>this.updatePreference("segmentation",e??null),supportedValues:Kn})}get pauseDuration(){return new Ve({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:vt.range,step:vt.step})}get autoPause(){return new ye({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:Wn})}get rate(){return new Ve({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:bt.range,step:bt.step})}get pitch(){return new Ve({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:wt.range,step:wt.step})}get volume(){return new Ve({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:xt.range,step:xt.step})}}const Br=["audio","figure","image","math","table","video"],Ur=[...Br,"blockquote","chapter","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],Sc=[...Ur,"abstract","acknowledgments","afterword","appendix","aside","backlink","bibliography","biblioref","colophon","complementary","conclusion","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","glossref","heading1","heading2","heading3","heading4","heading5","heading6","index","introduction","list","listItem","noteref","pagebreak","pagelist","preface","prologue","pullquote","separator","summary","term"],zr={none:new Set(["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"]),few:new Set(["aside","bibliography","biblioref","cell","columnheader","details","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","toc"]),some:new Set(["aside","bibliography","biblioref","endnotes","footnote","glossary","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","toc"]),most:new Set(["landmarks","loa","loi","lot","lov","toc"])},Vr={none:new Set,few:new Set(Br),some:new Set(Ur),most:new Set(Sc)},bn={table:{few:"inline",some:"block",most:"block"}};function lt(n){const e={};for(const t of Object.keys(bn))e[t]=bn[t]?.[n]??"inline";return e}const jr={none:lt("none"),few:lt("few"),some:lt("some"),most:lt("most")},yc=Object.keys(bn);function vc(n,e){const t=n==="custom"?{}:jr[n];if(!e)return t;const i={...t};for(const s of Object.keys(e)){const r=e[s]?.[n];r&&(i[s]=r)}return i}class wn{format;inlineContextualization;verbosity;skip;contextualize;language;segmentation;pauseDuration;autoPause;rate;pitch;volume;constructor(e,t){this.format=e.format??t.format,this.inlineContextualization=e.inlineContextualization??t.inlineContextualization,this.verbosity=e.verbosity??t.verbosity,this.verbosity==="custom"?(this.skip=e.skip??t.skip,this.contextualize=e.contextualize??t.contextualize):(this.skip=[...zr[this.verbosity]],this.contextualize=[...Vr[this.verbosity]]),this.language=e.language??t.language,this.segmentation=e.segmentation??t.segmentation,this.pauseDuration=e.pauseDuration??t.pauseDuration,this.autoPause=e.autoPause??t.autoPause,this.rate=e.rate??t.rate,this.pitch=e.pitch??t.pitch,this.volume=e.volume??t.volume}}const zi=new WeakMap,Hr=new WeakMap;function Vi(n,e){Hr.set(n,e)}const qr=new WeakSet;function ji(n){return qr.add(n),n}function Wr(n,e,t){const i=Hr.get(n);if(i){const u=gi(i.map,e),h=gi(i.map,e+t);e=u,t=Math.max(0,h-u)}const s=n.offsets,r=!n.plain&&!!n.ssml,o=i?.plain??n.plain??(n.ssml?le(n.ssml):"");if(!s?.length||!o)return;const a=zi.get(n),l=a!==void 0&&e>=a.cursor;let c=l?a.cursor:0;for(let u=l?a.pieceIndex:0;u<s.length;u++){const h=s[u],d=h.locate.text?.highlight,f=d?r?le(d):d:o.slice(c);if(!f)continue;const g=o.indexOf(f,c);if(g===-1)continue;const p=g+f.length;if(e>=g&&e<p){if(qr.has(h.locate))return;zi.set(n,{pieceIndex:u,cursor:c});const m=e-g,v=f.substring(m,Math.min(m+t,f.length));return{locate:{...h.locate,domRange:void 0,text:{highlight:v,before:f.substring(0,m),after:f.substring(m+v.length)}},word:v}}c=p}}function Kr(n,e){return e==="sentence"&&n.offsets?.length?n.offsets.map(t=>t.locate):n.locate?[n.locate]:[]}const x=n=>typeof n=="string",Me=()=>{let n,e;const t=new Promise((i,s)=>{n=i,e=s});return t.resolve=n,t.reject=e,t},Hi=n=>n==null?"":String(n),bc=(n,e,t)=>{n.forEach(i=>{e[i]&&(t[i]=e[i])})},wc=/###/g,qi=n=>n&&n.includes("###")?n.replace(wc,"."):n,Wi=n=>!n||x(n),je=(n,e,t)=>{const i=x(e)?e.split("."):e;let s=0;for(;s<i.length-1;){if(Wi(n))return{};const r=qi(i[s]);!n[r]&&t&&(n[r]=new t),Object.prototype.hasOwnProperty.call(n,r)?n=n[r]:n={},++s}return Wi(n)?{}:{obj:n,k:qi(i[s])}},Ki=(n,e,t)=>{const{obj:i,k:s}=je(n,e,Object);if(i!==void 0||e.length===1){i[s]=t;return}let r=e[e.length-1],o=e.slice(0,e.length-1),a=je(n,o,Object);for(;a.obj===void 0&&o.length;)r=`${o[o.length-1]}.${r}`,o=o.slice(0,o.length-1),a=je(n,o,Object),a?.obj&&typeof a.obj[`${a.k}.${r}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${r}`]=t},xc=(n,e,t,i)=>{const{obj:s,k:r}=je(n,e,Object);s[r]=s[r]||[],s[r].push(t)},Et=(n,e)=>{const{obj:t,k:i}=je(n,e);if(t&&Object.prototype.hasOwnProperty.call(t,i))return t[i]},Ec=(n,e,t)=>{const i=Et(n,t);return i!==void 0?i:Et(e,t)},Gr=(n,e,t)=>{for(const i in e)i!=="__proto__"&&i!=="constructor"&&(Object.prototype.hasOwnProperty.call(n,i)?x(n[i])||n[i]instanceof String||x(e[i])||e[i]instanceof String?t&&(n[i]=e[i]):Gr(n[i],e[i],t):n[i]=e[i]);return n},W=n=>n.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),Cc={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},kc=n=>x(n)?n.replace(/[&<>"'\/]/g,e=>Cc[e]):n;class Rc{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(t!==void 0)return t;const i=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,i),this.regExpQueue.push(e),i}}const Ac=[" ",",","?","!",";"],Oc=new Rc(20),Tc=(n,e,t)=>{e=e||"",t=t||"";const i=Ac.filter(o=>!e.includes(o)&&!t.includes(o));if(i.length===0)return!0;const s=Oc.getRegExp(`(${i.map(o=>o==="?"?"\\?":o).join("|")})`);let r=!s.test(n);if(!r){const o=n.indexOf(t);o>0&&!s.test(n.substring(0,o))&&(r=!0)}return r},xn=(n,e,t=".")=>{if(!n)return;if(n[e])return Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0;const i=e.split(t);let s=n;for(let r=0;r<i.length;){if(!s||typeof s!="object")return;let o,a="";for(let l=r;l<i.length;++l)if(l!==r&&(a+=t),a+=i[l],o=s[a],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&l<i.length-1)continue;r+=l-r+1;break}s=o}return s},Ke=n=>n?.replace(/_/g,"-"),Nc={type:"logger",log(n){this.output("log",n)},warn(n){this.output("warn",n)},error(n){this.output("error",n)},output(n,e){console?.[n]?.apply?.(console,e)}};class Ct{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Nc,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,i,s){return s&&!this.debug?null:(e=e.map(r=>x(r)?r.replace(/[\r\n\x00-\x1F\x7F]/g," "):r),x(e[0])&&(e[0]=`${i}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Ct(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ct(this.logger,e)}}var q=new Ct;class Mt{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(i=>{this.observers[i]||(this.observers[i]=new Map);const s=this.observers[i].get(t)||0;this.observers[i].set(t,s+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}once(e,t){const i=(...s)=>{t(...s),this.off(e,i)};return this.on(e,i),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,r])=>{for(let o=0;o<r;o++)s(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,r])=>{for(let o=0;o<r;o++)s(e,...t)})}}class Gi extends Mt{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,i,s={}){const r=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,o=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.includes(".")?a=e.split("."):(a=[e,t],i&&(Array.isArray(i)?a.push(...i):x(i)&&r?a.push(...i.split(r)):a.push(i)));const l=Et(this.data,a);return!l&&!t&&!i&&e.includes(".")&&(e=a[0],t=a[1],i=a.slice(2).join(".")),l||!o||!x(i)?l:xn(this.data?.[e]?.[t],i,r)}addResource(e,t,i,s,r={silent:!1}){const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let a=[e,t];i&&(a=a.concat(o?i.split(o):i)),e.includes(".")&&(a=e.split("."),s=t,t=a[1]),this.addNamespaces(t),Ki(this.data,a,s),r.silent||this.emit("added",e,t,i,s)}addResources(e,t,i,s={silent:!1}){for(const r in i)(x(i[r])||Array.isArray(i[r]))&&this.addResource(e,t,r,i[r],{silent:!0});s.silent||this.emit("added",e,t,i)}addResourceBundle(e,t,i,s,r,o={silent:!1,skipCopy:!1}){let a=[e,t];e.includes(".")&&(a=e.split("."),s=i,i=t,t=a[1]),this.addNamespaces(t);let l=Et(this.data,a)||{};o.skipCopy||(i=JSON.parse(JSON.stringify(i))),s?Gr(l,i,r):l={...l,...i},Ki(this.data,a,l),o.silent||this.emit("added",e,t,i)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(s=>t[s]&&Object.keys(t[s]).length>0)}toJSON(){return this.data}}var Xr={processors:{},addPostProcessor(n){this.processors[n.name]=n},handle(n,e,t,i,s){return n.forEach(r=>{e=this.processors[r]?.process(e,t,i,s)??e}),e}};const Jr=Symbol("i18next/PATH_KEY");function Dc(){const n=[],e=Object.create(null);let t;return e.get=(i,s)=>(t?.revoke?.(),s===Jr?n:(n.push(s),t=Proxy.revocable(i,e),t.proxy)),Proxy.revocable(Object.create(null),e).proxy}function we(n,e){const{[Jr]:t}=n(Dc()),i=e?.keySeparator??".",s=e?.nsSeparator??":",r=e?.enableSelector==="strict";if(t.length>1&&s){const o=e?.ns,a=r?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(a&&(r?a:a.length>1?a.slice(1):[]).includes(t[0]))return`${t[0]}${s}${t.slice(1).join(i)}`}return t.join(i)}const Yt=n=>!x(n)&&typeof n!="boolean"&&typeof n!="number";class kt extends Mt{constructor(e,t={}){super(),bc(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=q.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const i={...t};if(e==null)return!1;const s=this.resolve(e,i);if(s?.res===void 0)return!1;const r=Yt(s.res);return!(i.returnObjects===!1&&r)}extractFromKey(e,t){let i=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;i===void 0&&(i=":");const s=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let r=t.ns||this.options.defaultNS||[];const o=i&&e.includes(i),a=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!Tc(e,i,s);if(o&&!a){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:x(r)?[r]:r};const c=e.split(i);(i!==s||i===s&&this.options.ns.includes(c[0]))&&(r=c.shift()),e=c.join(s)}return{key:e,namespaces:x(r)?[r]:r}}translate(e,t,i){let s=typeof t=="object"?{...t}:t;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=we(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(P=>typeof P=="function"?we(P,{...this.options,...s}):String(P));const r=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(e[e.length-1],s),c=l[l.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const h=s.lng||this.language,d=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return d?r?{res:`${c}${u}${a}`,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:`${c}${u}${a}`:r?{res:a,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:a;const f=this.resolve(e,s);let g=f?.res;const p=f?.usedKey||a,m=f?.exactUsedKey||a,v=["[object Number]","[object Function]","[object RegExp]"],w=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,y=s.count!==void 0&&!x(s.count),b=kt.hasDefaultValue(s),C=y?this.pluralResolver.getSuffix(h,s.count,s):"",R=s.ordinal&&y?this.pluralResolver.getSuffix(h,s.count,{ordinal:!1}):"",A=y&&!s.ordinal&&s.count===0,N=A&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${C}`]||s[`defaultValue${R}`]||s.defaultValue;let O=g;S&&!g&&b&&(O=N);const tt=Yt(O),he=Object.prototype.toString.apply(O);if(S&&O&&tt&&!v.includes(he)&&!(x(w)&&Array.isArray(O))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const P=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,O,{...s,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return r?(f.res=P,f.usedParams=this.getUsedParamsDetails(s),f):P}if(o){const P=Array.isArray(O),$=P?[]:{},De=P?m:p;for(const V in O)if(Object.prototype.hasOwnProperty.call(O,V)){const j=`${De}${o}${V}`;b&&!g?$[V]=this.translate(j,{...s,defaultValue:Yt(N)?N[V]:void 0,joinArrays:!1,ns:l}):$[V]=this.translate(j,{...s,joinArrays:!1,ns:l}),$[V]===j&&($[V]=O[V])}g=$}}else if(S&&x(w)&&Array.isArray(g))g=g.join(w),g&&(g=this.extendTranslation(g,e,s,i));else{let P=!1,$=!1;!this.isValidLookup(g)&&b&&(P=!0,g=N),this.isValidLookup(g)||($=!0,g=a);const V=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&$?void 0:g,j=b&&N!==g&&this.options.updateMissing;if($||P||j){if(this.logger.log(j?"updateKey":"missingKey",h,c,y&&!j?`${a}${this.pluralResolver.getSuffix(h,s.count,s)}`:a,j?N:g),o){const M=this.resolve(a,{...s,keySeparator:!1});M&&M.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Pe=[];const nt=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&nt&&nt[0])for(let M=0;M<nt.length;M++)Pe.push(nt[M]);else this.options.saveMissingTo==="all"?Pe=this.languageUtils.toResolveHierarchy(s.lng||this.language):Pe.push(s.lng||this.language);const ri=(M,ee,Fe)=>{const oi=b&&Fe!==g?Fe:V;this.options.missingKeyHandler?this.options.missingKeyHandler(M,c,ee,oi,j,s):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(M,c,ee,oi,j,s),this.emit("missingKey",M,c,ee,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&y?Pe.forEach(M=>{const ee=this.pluralResolver.getSuffixes(M,s);A&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!ee.includes(`${this.options.pluralSeparator}zero`)&&ee.push(`${this.options.pluralSeparator}zero`),ee.forEach(Fe=>{ri([M],a+Fe,s[`defaultValue${Fe}`]||N)})}):ri(Pe,a,N))}g=this.extendTranslation(g,e,s,f,i),$&&g===a&&this.options.appendNamespaceToMissingKey&&(g=`${c}${u}${a}`),($||P)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${u}${a}`:a,P?g:void 0,s))}return r?(f.res=g,f.usedParams=this.getUsedParamsDetails(s),f):g}extendTranslation(e,t,i,s,r){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...i},i.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!i.skipInterpolation){i.interpolation&&this.interpolator.init({...i,interpolation:{...this.options.interpolation,...i.interpolation}});const l=x(e)&&(i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(l){const h=e.match(this.interpolator.nestingRegexp);c=h&&h.length}let u=i.replace&&!x(i.replace)?i.replace:i;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,i.lng||this.language||s.usedLng,i),l){const h=e.match(this.interpolator.nestingRegexp),d=h&&h.length;c<d&&(i.nest=!1)}!i.lng&&s&&s.res&&(i.lng=this.language||s.usedLng),i.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>r?.[0]===h[0]&&!i.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${t[0]}`),null):this.translate(...h,t),i)),i.interpolation&&this.interpolator.reset()}const o=i.postProcess||this.options.postProcess,a=x(o)?[o]:o;return e!=null&&a?.length&&i.applyPostProcessor!==!1&&(e=Xr.handle(a,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(i)},...i}:i,this)),e}resolve(e,t={}){let i,s,r,o,a;return x(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?we(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(i))return;const c=this.extractFromKey(l,t),u=c.key;s=u;let h=c.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const d=t.count!==void 0&&!x(t.count),f=d&&!t.ordinal&&t.count===0,g=t.context!==void 0&&(x(t.context)||typeof t.context=="number")&&t.context!=="",p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);h.forEach(m=>{this.isValidLookup(i)||(a=m,!this.checkedLoadedFor[`${p[0]}-${m}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(this.checkedLoadedFor[`${p[0]}-${m}`]=!0,this.logger.warn(`key "${s}" for languages "${p.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),p.forEach(v=>{if(this.isValidLookup(i))return;o=v;const w=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,u,v,m,t);else{let y;d&&(y=this.pluralResolver.getSuffix(v,t.count,t));const b=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&y.startsWith(C)&&w.push(u+y.replace(C,this.options.pluralSeparator)),w.push(u+y),f&&w.push(u+b)),g){const R=`${u}${this.options.contextSeparator||"_"}${t.context}`;w.push(R),d&&(t.ordinal&&y.startsWith(C)&&w.push(R+y.replace(C,this.options.pluralSeparator)),w.push(R+y),f&&w.push(R+b))}}let S;for(;S=w.pop();)this.isValidLookup(i)||(r=S,i=this.getResource(v,m,S,t))}))})}),{res:i,usedKey:s,exactUsedKey:r,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,i,s={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,i,s):this.resourceStore.getResource(e,t,i,s)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],i=e.replace&&!x(e.replace);let s=i?e.replace:e;if(i&&typeof e.count<"u"&&(s={...s,count:e.count}),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!i){s={...s};for(const r of t)delete s[r]}return s}static hasDefaultValue(e){const t="defaultValue";for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&i.startsWith(t)&&e[i]!==void 0)return!0;return!1}}class Xi{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=q.create("languageUtils"),this.resolveHierarchyCache={}}clearCache(){this.resolveHierarchyCache={}}getScriptPartFromCode(e){if(e=Ke(e),!e||!e.includes("-"))return null;const t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=Ke(e),!e||!e.includes("-"))return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(x(e)&&e.includes("-")){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(i=>{if(t)return;const s=this.formatLanguageCode(i);(!this.options.supportedLngs||this.isSupportedCode(s))&&(t=s)}),!t&&this.options.supportedLngs&&e.forEach(i=>{if(t)return;const s=this.getScriptPartFromCode(i);if(this.isSupportedCode(s))return t=s;const r=this.getLanguagePartFromCode(i);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(o=>o===r?!0:!o.includes("-")&&!r.includes("-")?!1:!!(o.includes("-")&&!r.includes("-")&&o.slice(0,o.indexOf("-"))===r||o.startsWith(r)&&r.length>1))}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),x(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let i=e[t];return i||(i=e[this.getScriptPartFromCode(t)]),i||(i=e[this.formatLanguageCode(t)]),i||(i=e[this.getLanguagePartFromCode(t)]),i||(i=e.default),i||[]}toResolveHierarchy(e,t){const i=this.options.fallbackLng,s=Array.isArray(i)?i.join("|"):i;s!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=s);const r=t===void 0||t===!1||x(t),o=t===void 0&&typeof this.options.fallbackLng=="function",a=x(e)&&r&&!o;let l=null;if(a){let d;t===void 0?d="undefined":t===!1?d="boolean:false":d=`string:${t}`,l=`${e.length}:${e}|${d}`}if(l!==null){const d=this.resolveHierarchyCache[l];if(d!==void 0)return d.slice()}const c=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),u=[],h=d=>{d&&(this.isSupportedCode(d)?u.push(d):this.logger.warn(`rejecting language code not found in supportedLngs: ${d}`))};return x(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&h(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&h(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&h(this.getLanguagePartFromCode(e))):x(e)&&h(this.formatLanguageCode(e)),c.forEach(d=>{u.includes(d)||h(this.formatLanguageCode(d))}),l!==null?(this.resolveHierarchyCache[l]=u,u.slice()):u}}const Ji={zero:0,one:1,two:2,few:3,many:4,other:5},Yi={select:n=>n===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Pc{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=q.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const i=Ke(e==="dev"?"en":e),s=t.ordinal?"ordinal":"cardinal",r=JSON.stringify({cleanedCode:i,type:s});if(r in this.pluralRulesCache)return this.pluralRulesCache[r];let o;try{o=new Intl.PluralRules(i,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Yi;if(!e.match(/-|_/))return Yi;const l=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(l,t)}return this.pluralRulesCache[r]=o,o}needsPlural(e,t={}){let i=this.getRule(e,t);return i||(i=this.getRule("dev",t)),i?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,i={}){return this.getSuffixes(e,i).map(s=>`${t}${s}`)}getSuffixes(e,t={}){let i=this.getRule(e,t);return i||(i=this.getRule("dev",t)),i?i.resolvedOptions().pluralCategories.sort((s,r)=>Ji[s]-Ji[r]).map(s=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,t,i={}){const s=this.getRule(e,i);return s?`${this.options.prepend}${i.ordinal?`ordinal${this.options.prepend}`:""}${s.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,i))}}const Qi=(n,e,t,i=".",s=!0)=>{let r=Ec(n,e,t);return!r&&s&&x(t)&&(r=xn(n,t,i),r===void 0&&(r=xn(e,t,i))),r},Fc=n=>n.replace(/\$/g,"$$$$");class Zi{constructor(e={}){this.logger=q.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(t=>t),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:i,useRawValueToEscape:s,prefix:r,prefixEscaped:o,suffix:a,suffixEscaped:l,formatSeparator:c,unescapeSuffix:u,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:g,nestingSuffixEscaped:p,nestingOptionsSeparator:m,maxReplaces:v,alwaysFormat:w}=e.interpolation;this.escape=t!==void 0?t:kc,this.escapeValue=i!==void 0?i:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=r?W(r):o||"{{",this.suffix=a?W(a):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=u?"":h?W(h):"-",this.unescapeSuffix=this.unescapePrefix?"":u?W(u):"",this.nestingPrefix=d?W(d):f||W("$t("),this.nestingSuffix=g?W(g):p||W(")"),this.nestingOptionsSeparator=m||",",this.maxReplaces=v||1e3,this.alwaysFormat=w!==void 0?w:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(t,i)=>t?.source===i?(t.lastIndex=0,t):new RegExp(i,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,i,s){let r,o,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=f=>{if(!f.includes(this.formatSeparator)){const v=Qi(t,l,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(v,void 0,i,{...s,...t,interpolationkey:f}):v}const g=f.split(this.formatSeparator),p=g.shift().trim(),m=g.join(this.formatSeparator).trim();return this.format(Qi(t,l,p,this.options.keySeparator,this.options.ignoreJSONStructure),m,i,{...s,...t,interpolationkey:p})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=s?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>f},{regex:this.regexp,safeValue:f=>this.escapeValue?this.escape(f):f}].forEach(f=>{for(a=0;r=f.regex.exec(e);){const g=r[1].trim();if(o=c(g),o===void 0)if(typeof u=="function"){const m=u(e,r,s);o=x(m)?m:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))o="";else if(h){o=r[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),o="";else!x(o)&&!this.useRawValueToEscape&&(o=Hi(o));const p=f.safeValue(o);if(e=e.replace(r[0],Fc(p)),h?(f.regex.lastIndex+=p.length,f.regex.lastIndex-=r[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,t,i={}){let s,r,o;const a=(l,c)=>{const u=this.nestingOptionsSeparator;if(!l.includes(u))return l;const h=l.split(new RegExp(`${W(u)}[ ]*{`));let d=`{${h[1]}`;l=h[0],d=this.interpolate(d,o);const f=d.match(/'/g),g=d.match(/"/g);((f?.length??0)%2===0&&!g||(g?.length??0)%2!==0)&&(d=d.replace(/'/g,'"'));try{o=JSON.parse(d),c&&(o={...c,...o})}catch(p){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,p),`${l}${u}${d}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,l};for(;s=this.nestingRegexp.exec(e);){let l=[];o={...i},o=o.replace&&!x(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const c=/{.*}/s.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(c!==-1&&(l=s[1].slice(c).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,c)),r=t(a.call(this,s[1].trim(),o),o),r&&s[0]===e&&!x(r))return r;x(r)||(r=Hi(r)),r||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),r=""),l.length&&(r=l.reduce((u,h)=>this.format(u,h,i.lng,{...i,interpolationkey:s[1].trim()}),r.trim())),e=e.replace(s[0],r),this.regexp.lastIndex=0}return e}}const Ic=n=>{let e=n.toLowerCase().trim();const t={};if(n.includes("(")){const i=n.split("(");e=i[0].toLowerCase().trim();const s=i[1].slice(0,-1);e==="currency"&&!s.includes(":")?t.currency||(t.currency=s.trim()):e==="relativetime"&&!s.includes(":")?t.range||(t.range=s.trim()):s.split(";").forEach(o=>{if(o){const[a,...l]=o.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();t[u]||(t[u]=c),c==="false"&&(t[u]=!1),c==="true"&&(t[u]=!0),isNaN(c)||(t[u]=parseInt(c,10))}})}return{formatName:e,formatOptions:t}},es=n=>{const e={};return(t,i,s)=>{let r=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(r={...r,[s.interpolationkey]:void 0});const o=i+JSON.stringify(r);let a=e[o];return a||(a=n(Ke(i),s),e[o]=a),a(t)}},Lc=n=>(e,t,i)=>n(Ke(t),i)(e);class $c{constructor(e={}){this.logger=q.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const i=t.cacheInBuiltFormats?es:Lc;this.formats={number:i((s,r)=>{const o=new Intl.NumberFormat(s,{...r});return a=>o.format(a)}),currency:i((s,r)=>{const o=new Intl.NumberFormat(s,{...r,style:"currency"});return a=>o.format(a)}),datetime:i((s,r)=>{const o=new Intl.DateTimeFormat(s,{...r});return a=>o.format(a)}),relativetime:i((s,r)=>{const o=new Intl.RelativeTimeFormat(s,{...r});return a=>o.format(a,r.range||"day")}),list:i((s,r)=>{const o=new Intl.ListFormat(s,{...r});return a=>o.format(a)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=es(t)}format(e,t,i,s={}){if(!t||e==null)return e;const r=t.split(this.formatSeparator),o=[];for(let l=0;l<r.length;l++){let c=r[l];for(;c.indexOf("(")>-1&&!c.includes(")")&&l+1<r.length;)c=`${c}${this.formatSeparator}${r[++l]}`;o.push(c)}return o.reduce((l,c)=>{const{formatName:u,formatOptions:h}=Ic(c);if(this.formats[u]){let d=l;try{const f=s?.formatParams?.[s.interpolationkey]||{},g=f.locale||f.lng||s.locale||s.lng||i;d=this.formats[u](l,g,{...h,...s,...f})}catch(f){this.logger.warn(f)}return d}else this.logger.warn(`there was no format function for ${u}`);return l},e)}}const Mc=(n,e)=>{n.pending[e]!==void 0&&(delete n.pending[e],n.pendingCount--)};class _c extends Mt{constructor(e,t,i,s={}){super(),this.backend=e,this.store=t,this.services=i,this.languageUtils=i.languageUtils,this.options=s,this.logger=q.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(i,s.backend,s)}queueLoad(e,t,i,s){const r={},o={},a={},l={};return e.forEach(c=>{let u=!0;t.forEach(h=>{const d=`${c}|${h}`;!i.reload&&this.store.hasResourceBundle(c,h)?this.state[d]=2:this.state[d]<0||(this.state[d]===1?o[d]===void 0&&(o[d]=!0):(this.state[d]=1,u=!1,o[d]===void 0&&(o[d]=!0),r[d]===void 0&&(r[d]=!0),l[h]===void 0&&(l[h]=!0)))}),u||(a[c]=!0)}),(Object.keys(r).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(r),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(l)}}loaded(e,t,i){const s=e.split("|"),r=s[0],o=s[1];t&&this.emit("failedLoading",r,o,t),!t&&i&&this.store.addResourceBundle(r,o,i,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&i&&(this.state[e]=0);const a={};this.queue.forEach(l=>{xc(l.loaded,[r],o),Mc(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{a[c]||(a[c]={});const u=l.loaded[c];u.length&&u.forEach(h=>{a[c][h]===void 0&&(a[c][h]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(l=>!l.done)}read(e,t,i,s=0,r=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:i,tried:s,wait:r,callback:o});return}this.readingCalls++;const a=(c,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const h=this.waitingReads.shift();this.read(h.lng,h.ns,h.fcName,h.tried,h.wait,h.callback)}if(c&&u&&s<this.maxRetries){setTimeout(()=>{this.read(e,t,i,s+1,r*2,o)},r);return}o(c,u)},l=this.backend[i].bind(this.backend);if(l.length===2){try{const c=l(e,t);c&&typeof c.then=="function"?c.then(u=>a(null,u)).catch(a):a(null,c)}catch(c){a(c)}return}return l(e,t,a)}prepareLoading(e,t,i={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();x(e)&&(e=this.languageUtils.toResolveHierarchy(e)),x(t)&&(t=[t]);const r=this.queueLoad(e,t,i,s);if(!r.toLoad.length)return r.pending.length||s(),null;r.toLoad.forEach(o=>{this.loadOne(o)})}load(e,t,i){this.prepareLoading(e,t,{},i)}reload(e,t,i){this.prepareLoading(e,t,{reload:!0},i)}loadOne(e,t=""){const i=e.split("|"),s=i[0],r=i[1];this.read(s,r,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${t}loading namespace ${r} for language ${s} failed`,o),!o&&a&&this.logger.log(`${t}loaded namespace ${r} for language ${s}`,a),this.loaded(e,o,a)})}saveMissing(e,t,i,s,r,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${i}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(i==null||i==="")){if(this.backend?.create){const l={...o,isUpdate:r},c=this.backend.create.bind(this.backend);if(c.length<6)try{let u;c.length===5?u=c(e,t,i,s,l):u=c(e,t,i,s),u&&typeof u.then=="function"?u.then(h=>a(null,h)).catch(a):a(null,u)}catch(u){a(u)}else c(e,t,i,s,a,l)}!e||!e[0]||this.store.addResource(e[0],t,i,s)}}}const Qt=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:n=>{let e={};if(typeof n[1]=="object"&&(e=n[1]),x(n[1])&&(e.defaultValue=n[1]),x(n[2])&&(e.tDescription=n[2]),typeof n[2]=="object"||typeof n[3]=="object"){const t=n[3]||n[2];Object.keys(t).forEach(i=>{e[i]=t[i]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ts=n=>(x(n.ns)&&(n.ns=[n.ns]),x(n.fallbackLng)&&(n.fallbackLng=[n.fallbackLng]),x(n.fallbackNS)&&(n.fallbackNS=[n.fallbackNS]),n.supportedLngs&&!n.supportedLngs.includes("cimode")&&(n.supportedLngs=n.supportedLngs.concat(["cimode"])),n),ct=()=>{},Bc=n=>{Object.getOwnPropertyNames(Object.getPrototypeOf(n)).forEach(t=>{typeof n[t]=="function"&&(n[t]=n[t].bind(n))})};class He extends Mt{constructor(e={},t){if(super(),this.options=ts(e),this.services={},this.logger=q,this.modules={external:[]},Bc(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e=="function"&&(t=e,e={}),e.defaultNS==null&&e.ns&&(x(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const i=Qt();this.options={...i,...this.options,...ts(e)},this.options.interpolation={...i.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=i.overloadTranslationOptionHandler);const s=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?q.init(s(this.modules.logger),this.options):q.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=$c;const u=new Xi(this.options);this.store=new Gi(this.options.resources,this.options);const h=this.services;h.logger=q,h.resourceStore=this.store,h.languageUtils=u,h.pluralResolver=new Pc(u,{prepend:this.options.pluralSeparator}),c&&(h.formatter=s(c),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new Zi(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new _c(s(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.languageDetector&&(h.languageDetector=s(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=s(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new kt(this.services,this.options),this.translator.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,t||(t=ct),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...u)=>this.store[c](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...u)=>(this.store[c](...u),this)});const a=Me(),l=()=>{const c=(u,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(h),t(u,h)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),a}loadResources(e,t=ct){let i=t;const s=x(e)?e:this.language;if(typeof e=="function"&&(i=e),!this.options.resources||this.options.partialBundledLanguages){if(s?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return i();const r=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&(r.includes(c)||r.push(c))})};s?o(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>o(l)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(r,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),i(a)})}else i(null)}reloadResources(e,t,i){const s=Me();return typeof e=="function"&&(i=e,e=void 0),typeof t=="function"&&(i=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),i||(i=ct),this.services.backendConnector.reload(e,t,r=>{s.resolve(),i(r)}),s}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&Xr.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let t=0;t<this.languages.length;t++){const i=this.languages[t];if(!["cimode","dev"].includes(i)&&this.store.hasLanguageSomeTranslations(i)){this.resolvedLanguage=i;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const i=Me();this.emit("languageChanging",e);const s=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},r=(a,l)=>{l?this.isLanguageChangingTo===e&&(s(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,i.resolve((...c)=>this.t(...c)),t&&t(a,(...c)=>this.t(...c))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const l=x(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(x(a)?[a]:a);c&&(this.language||s(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,u=>{r(u,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),i}getFixedT(e,t,i,s){const r=s?.scopeNs,o=(a,l,...c)=>{let u;typeof l!="object"?u=this.options.overloadTranslationOptionHandler([a,l].concat(c)):u={...l},u.lng=u.lng||o.lng,u.lngs=u.lngs||o.lngs;const h=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||o.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||i||o.keyPrefix);const d={...this.options,...u};Array.isArray(r)&&!h&&(d.ns=r),typeof u.keyPrefix=="function"&&(u.keyPrefix=we(u.keyPrefix,d));const f=this.options.keySeparator||".";let g;return u.keyPrefix&&Array.isArray(a)?g=a.map(p=>(typeof p=="function"&&(p=we(p,d)),`${u.keyPrefix}${f}${p}`)):(typeof a=="function"&&(a=we(a,d)),g=u.keyPrefix?`${u.keyPrefix}${f}${a}`:a),this.t(g,u)};return x(e)?o.lng=e:o.lngs=e,o.ns=t,o.keyPrefix=i,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const i=t.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,r=this.languages[this.languages.length-1];if(i.toLowerCase()==="cimode")return!0;const o=(a,l)=>{const c=this.services.backendConnector.state[`${a}|${l}`];return c===-1||c===0||c===2};if(t.precheck){const a=t.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(i,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(i,e)&&(!s||o(r,e)))}loadNamespaces(e,t){const i=Me();return this.options.ns?(x(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{i.resolve(),t&&t(s)}),i):(t&&t(),Promise.resolve())}loadLanguages(e,t){const i=Me();x(e)&&(e=[e]);const s=this.options.preload||[],r=e.filter(o=>!s.includes(o)&&this.services.languageUtils.isSupportedCode(o));return r.length?(this.options.preload=s.concat(r),this.loadResources(o=>{i.resolve(),t&&t(o)}),i):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const s=new Intl.Locale(e);if(s&&s.getTextInfo){const r=s.getTextInfo();if(r&&r.direction)return r.direction}}catch{}const t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],i=this.services?.languageUtils||new Xi(Qt());return e.toLowerCase().indexOf("-latn")>1?"ltr":t.includes(i.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const i=new He(e,t);return i.createInstance=He.createInstance,i}cloneInstance(e={},t=ct){const i=e.forkResourceStore;i&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},r=new He(s);if((e.debug!==void 0||e.prefix!==void 0)&&(r.logger=r.logger.clone(e)),["store","services","language"].forEach(a=>{r[a]=this[a]}),r.services={...this.services},r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},i){const a=Object.keys(this.store.data).reduce((l,c)=>(l[c]={...this.store.data[c]},l[c]=Object.keys(l[c]).reduce((u,h)=>(u[h]={...l[c][h]},u),l[c]),l),{});r.store=new Gi(a,s),r.services.resourceStore=r.store}if(e.interpolation){const l={...Qt().interpolation,...this.options.interpolation,...e.interpolation},c={...s,interpolation:l};r.services.interpolator=new Zi(c)}return r.translator=new kt(r.services,s),r.translator.on("*",(a,...l)=>{r.emit(a,...l)}),r.init(s,t),r.translator.options=s,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const I=He.createInstance();I.createInstance;I.dir;I.init;I.loadResources;I.reloadResources;I.use;I.changeLanguage;I.getFixedT;I.t;I.exists;I.setDefaultNamespace;I.hasLoadedNamespace;I.loadNamespaces;I.loadLanguages;function H(n){return{pattern:new RegExp(`(\\d+)\\s?u${n}\\b`,"g"),replace:(e,t)=>`${t}µ${n}`}}const Uc={"1/4":"¼","1/2":"½","3/4":"¾","1/7":"⅐","1/9":"⅑","1/10":"⅒","1/3":"⅓","2/3":"⅔","1/5":"⅕","2/5":"⅖","3/5":"⅗","4/5":"⅘","1/6":"⅙","5/6":"⅚","1/8":"⅛","3/8":"⅜","5/8":"⅝","7/8":"⅞","0/3":"↉"},zc={...Uc,"(c)":{pattern:new RegExp("(?<!\\([ab]\\)\\s{0,3})\\(c\\)","g"),replace:"©"},"(C)":{pattern:new RegExp("(?<!\\([AB]\\)\\s{0,3})\\(C\\)","g"),replace:"©"},"(r)":"®","(R)":"®","(tm)":"™","(TM)":"™",deg:{pattern:/(\d+)\s?deg\b/g,replace:(n,e)=>`${e}°`},x:{pattern:/(\d+)\s?[xX]\s?(?=\d)/g,replace:(n,e)=>`${e}×`},ug:H("g"),um:H("m"),us:H("s"),uL:H("L"),uF:H("F"),uA:H("A"),uV:H("V"),uW:H("W"),uN:H("N"),umol:H("mol"),"->":"→","<-":"←","′":"'","″":'"'},Vc={contextualizations:{abstract:{block:{start:"Start of the abstract.",end:"End of the abstract."}},acknowledgments:{block:{start:"Start of the acknowledgments.",end:"End of the acknowledgments."}},afterword:{block:{start:"Start of the afterword.",end:"End of the afterword."}},appendix:{block:{start:"Start of the appendix.",end:"End of the appendix."}},aside:{block:{start:"Start of the aside.",end:"End of the aside."}},audio:{inline:{labelled:"Audio with a label: {{ description }}",unlabelled:"Audio with no label."}},bibliography:{block:{start:"Start of the bibliography.",end:"End of the bibliography."}},blockquote:{inline:"Blockquote."},cell:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},chapter:{block:{start:"Start of the chapter.",end:"End of the chapter."}},colophon:{inline:"Colophon."},complementary:{block:{start:"Start of the complementary content.",end:"End of the complementary content."}},conclusion:{block:{start:"Start of the conclusion.",end:"End of the conclusion."}},cover:{inline:{labelled:"Cover with a label: {{ description }}",unlabelled:"Cover with no label."}},credit:{inline:"Credit."},credits:{block:{start:"Start of the credits.",end:"End of the credits."}},dedication:{inline:"Dedication."},definition:{inline:"Definition."},details:{block:{start:"Start of the disclosure.",end:"End of the disclosure."}},endnotes:{block:{start:"Start of the endnotes.",end:"End of the endnotes."}},epigraph:{inline:"Epigraph."},epilogue:{block:{start:"Start of the epilogue.",end:"End of the epilogue."}},errata:{block:{start:"Start of the errata.",end:"End of the errata."}},example:{block:{start:"Start of the example.",end:"End of the example."}},figure:{inline:"Figure: {{ description }}"},footnote:{block:{start:"Start of the footnote.",end:"End of the footnote."}},foreword:{block:{start:"Start of the foreword.",end:"End of the foreword."}},glossary:{block:{start:"Start of the glossary.",end:"End of the glossary."}},heading1:{inline:"Heading level 1."},heading2:{inline:"Heading level 2."},heading3:{inline:"Heading level 3."},heading4:{inline:"Heading level 4."},heading5:{inline:"Heading level 5."},heading6:{inline:"Heading level 6."},image:{inline:{labelled:"Image with a label: {{ description }}",unlabelled:"Image with no label."}},index:{block:{start:"Start of the index.",end:"End of the index."}},introduction:{block:{start:"Start of the introduction.",end:"End of the introduction."}},list:{block:{start:"Start of the list.",end:"End of the list."}},listItem:{inline:"List item."},math:{inline:{labelled:"{{ description }}",unlabelled:"Math formula with no label."}},notice:{inline:"Notice."},pagebreak:{inline:"Pagebreak."},pagelist:{block:{start:"Start of the page list.",end:"End of the page list."}},part:{inline:"Part."},preface:{block:{start:"Start of the preface.",end:"End of the preface."}},prologue:{block:{start:"Start of the prologue.",end:"End of the prologue."}},pullquote:{inline:"Pullquote."},qna:{block:{start:"Start of the questions and answers.",end:"End of the questions and answers."}},row:{inline:"Row: {{ count }}"},rowheader:{inline:{withHeader:"{{ header }}: {{ value }}",withoutHeader:"{{ value }}"}},separator:{inline:"Separator."},subtitle:{inline:"Subtitle."},summary:{inline:"Summary."},table:{block:{end:"End of the table.",start:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."}},inline:{labelled:"Table: {{ description }}. {{ lines }}. {{ columns }}.",unlabelled:"Table. {{ lines }}. {{ columns }}."},parts:{columns_one:"1 column",columns_other:"{{ count }} columns",lines_one:"1 line",lines_other:"{{ count }} lines"}},term:{inline:"Term."},tip:{inline:"Tip."},video:{inline:{labelled:"Video with a label: {{ description }}",unlabelled:"Video with no label."}}}},jc={speech:Vc},Xn=jc.speech.contextualizations,ns={en:Xn},Hc={};async function qc(n){const e=ns[n];if(e)return e;const t=Hc[n];if(!t)return Xn;const i=(await t()).speech.contextualizations;return ns[n]=i,i}const is={de:["A.","A.M.","Abs.","Abt.","Abw.","Adj.","Adr.","Akt.","Allg.","Alt.","App.","Apr.","Art.","Aug.","Ausg.","Ausschl.","B.","Bed.","Ben.","Ber.","Best.","Bibl.","C.","Ca.","Chin.","Chr.","Co.","D.","D. h.","Dat.","Dez.","Di.","Dim.","Dipl.-Ing.","Dipl.-Kfm.","Dir.","Do.","Dr.","Dtzd.","Einh.","Erf.","Evtl.","F.","F.f.","Fa.","Fam.","Feb.","Fn.","Folg.","Forts. f.","Fr.","Frl.","G.","Gebr.","Gem.","Geograph.","Ges.","Gesch.","Ggf.","Hbf.","Hptst.","Hr.","Hrn.","Hrsg.","I.","Inc.","Ing.","Inh.","Int.","J.","J.D.","Jahrh.","Jan.","Jr.","Kap.","Kfm.","Kl.","Konv.","Kop.","L.","Ltd.","M.","Max.","Mi.","Min.","Mind.","Mio.","Mo.","Mod.","Mrd.","Msp.","N.","Nov.","Nr.","O.","Obj.","Okt.","Op.","P.","P.M.","PIN.","Pfd.","Phys.","Port.","Prot.","Proz.","Qu.","R.","Rd.","Reg.","Reg.-Bez.","Rel.","Rep.","S.A.","Sa.","Schr.","Sek.","Sep.","Sept.","So.","Spezif.","St.","StR.","Std.","Str.","T.","Tel.","Temp.","Test.","Trans.","Tägl.","U.","U. U.","U.S.","U.S.A.","U.U.","Urspr.","Ursprüngl.","Verf.","Vgl.","W.","Wg.","Y.","Z.","Z. B.","Z. Zt.","Ztr.","a.D.","a.M.","a.Rh.","a.a.O.","a.a.S.","am.","amtl.","b.","beil.","d.J.","d.Ä.","e.V.","e.Wz.","e.h.","ehem.","eigtl.","einschl.","entspr.","erw.","ev.","evtl.","exkl.","frz.","geb.","gedr.","gek.","gesch.","gest.","ggf.","ggfs.","hpts.","i.A.","i.B.","i.H.","i.J.","i.R.","i.V.","inkl.","jew.","jhrl.","k. u. k.","k.u.k.","kath.","kfm.","kgl.","led.","m.E.","m.W.","mtl.","möbl.","n. Chr.","n.u.Z.","näml.","o.A.","o.B.","o.g.","od.","p.Adr.","r.","röm.","röm.-kath.","s.","s.a.","schles.","schweiz.","schwäb.","sog.","südd.","tägl.","u.","u. Z.","u.A.w.g.","u.U.","u.a.","u.v.a.","u.Ä.","u.ä.","v. Chr.","v. H.","v. u. Z.","v.Chr.","v.H.","v.R.w.","v.T.","v.u.Z.","verh.","verw.","vgl.","z.","z.B.","z.Hd.","z.Z.","zzgl.","österr."],en:["A.D.","A.I.","A.M.","A.S.","AA.","AB.","Abs.","Adj.","Adv.","Alt.","Approx.","Aug.","B.V.","C.F.","C.O.D.","Capt.","Col.","Comm.","Conn.","Cont.","D.A.","D.C.","DC.","DR.","Dec.","Def.","Dept.","Diff.","Dr.","E.G.","E.g.","Ed.","Est.","Etc.","Ex.","Exec.","Feb.","Fn.","Fri.","Hon.B.A.","I.","I.D.","I.T.","I.e.","J.B.","J.D.","J.K.","Jan.","Jun.","K.R.","L.A.","L.P.","Lev.","Lib.","Lt.","Lt.Cdr.","M.","M.I.T.","M.R.","M.T.","MR.","Maj.","Mar.","Mart.","Mb.","Md.","Mgr.","Min.","Misc.","Mr.","Mrs.","Ms.","Mt.","N.V.","N.Y.","Nov.","Nr.","Num.","Op.","Org.","P.M.","P.O.","P.V.","PP.","Ph.D.","Phys.","Prof.","Pvt.","R.L.","R.T.","Rep.","Rev.","S.A.","S.A.R.","S.E.","S.p.A.","Sep.","Sept.","Sgt.","Sq.","St.","U.S.","U.S.A.","U.S.C.","VS.","Yr.","a.m.","d.","dr.","exec.","pp.","vs."],es:["A.C.","AA.","All.","Ant.","Av.","Avda.","Bien.","C.","C.P.","C.S.","C.V.","CA.","Col.","Comm.","Corp.","Cía.","D.","DC.","Da.","Desc.","Desv.","Dr.","Dra.","Drs.","Dto.","Dª.","Dña.","Em.","Emm.","Exc.","Excma.","Excmas.","Excmo.","Excmos.","Exma.","Exmas.","Exmo.","Exmos.","FF.CC.","Fabric.","Fr.","H.P.","Id.","Ilma.","Ilmas.","Ilmo.","Ilmos.","Inc.","JJ.OO.","K.","Kit.","Korn.","L.","Lcda.","Lcdo.","Lda.","Ldo.","Lic.","Ltd.","Ltda.","Ltdo.","M.","MM.","Mons.","Mr.","Mrs.","O.M.","PP.","R.D.","R.U.","RAM.","RR.HH.","Rdo.","Rdos.","Reg.","Rev.","Rol.","Rvdmo.","Rvdmos.","Rvdo.","Rvdos.","SA.","SS.AA.","SS.MM.","Sdad.","Seg.","Sol.","Sr.","Sra.","Sras.","Sres.","Srta.","Srtas.","Sta.","Sto.","Trab.","U.S.","U.S.A.","Var.","Vda.","a. C.","a. e. c.","abr.","afma.","afmas.","afmo.","afmos.","ago.","bco.","bol.","c/c.","cap.","cf.","cfr.","col.","d. C.","depto.","deptos.","dic.","doc.","dom.","dpto.","dptos.","dtor.","e. c.","e.g.","ed.","ej.","ene.","feb.","fig.","figs.","fund.","hnos.","jue.","jul.","jun.","licda.","licdo.","lun.","mar.","may.","mié.","ms.","mss.","mtro.","nov.","ntra.","ntro.","oct.","p.ej.","prof.","prov.","sept.","sras.","sres.","srs.","ss.","sáb.","trad.","v.gr.","vid.","vie.","vs."],fr:["All.","C.","Comm.","D.","DC.","Desc.","Inc.","Jr.","L.","M.","MM.","Mart.","Op.","P.","P.-D. G.","P.O.","Prof.","S.A.","S.M.A.R.T.","U.","U.S.","U.S.A.","Var.","W.","acoust.","adr.","anc.","ann.","anon.","ap. J.-C.","append.","aux.","av. J.-C.","avr.","broch.","bull.","cam.","categ.","coll.","collab.","config.","dest.","dict.","dim.","dir.","doc.","déc.","encycl.","exempl.","fig.","févr.","gouv.","graph.","hôp.","ill.","illustr.","imm.","imprim.","indus.","janv.","jeu.","juil.","lun.","mar.","mer.","niv.","nov.","oct.","quart.","réf.","sam.","sept.","symb.","synth.","syst.","trav. publ.","ven.","voit.","éd.","édit.","équiv.","éval."],it:["C.P.","Cfr.","D.","DC.","Geom.","Ing.","L.","Liv.","Ltd.","Mod.","N.B.","N.d.A.","N.d.E.","N.d.T.","O.d.G.","S.A.R.","S.M.A.R.T.","S.p.A.","Sig.","U.S.","U.S.A.","a.C.","ag.","all.","arch.","avv.","c.c.p.","d.C.","d.p.R.","div.","dott.","dr.","fig.","int.","mitt.","on.","p.","p.i.","pag.","rag.","sez.","tab.","tav.","ver.","vol."],pt:["A.C.","Alm.","Av.","Dir.","Dr.","Dra.","Dras.","Drs.","E.","Est.","Exma.","Exmo.","Fr.","Ilma.","Ilmo.","Jr.","Ltd.","Ltda.","Mar.","N.Sra.","N.T.","P.M.","Pe.","Ph.D.","R.","S.","S.A.","Sta.","Sto.","V.T.","W.C.","a.C.","a.m.","abr.","abrev.","adm.","aer.","ago.","agric.","anat.","ap.","apart.","apt.","arit.","arqueol.","arquit.","astron.","autom.","aux.","biogr.","bras.","cap.","caps.","cat.","cel.","cf.","col.","com.","comp.","compl.","cont.","contab.","créd.","cx.","círc.","cód.","d.C.","des.","desc.","dez.","dipl.","dir.","div.","doc.","déb.","ed.","educ.","elem.","eletr.","eletrôn.","end.","eng.","esp.","ex.","f.","fac.","fasc.","fem.","fev.","ff.","fig.","fil.","filos.","fisiol.","fl.","fot.","fr.","fís.","geom.","gram.","gên.","hist.","ind.","ingl.","jan.","jul.","jun.","jur.","l.","lat.","lin.","lit.","liter.","long.","mai.","mar.","mat.","matem.","mov.","máq.","méd.","mús.","neol.","nov.","náut.","obs.","odont.","odontol.","org.","organiz.","out.","p.","p. ex.","p.m.","pal.","pol.","port.","pp.","pq.","prod.","prof.","profa.","pron.","próx.","psicol.","pág.","quím.","r.s.v.p.","ref.","rel.","relat.","rep.","res.","rod.","set.","sociol.","sup.","séc.","símb.","tec.","tecnol.","tel.","trad.","transp.","univ.","vol.","vs.","álg.","índ."],ru:["авг.","апр.","дек.","до н. э.","кв.","н. э.","н.э.","нояб.","окт.","отд.","проф.","руб.","сент.","тел.","тыс.","ул.","февр.","янв."],th:["ค.ศ."]};function Zt(n,e,t){let i=t;for(;i>e&&/\s/.test(n[i-1]);)i--;return i}const Wc=/[\s([{"'“‘]/;function Kc(n,e){for(const t of e){if(n.length<t.length||!n.endsWith(t))continue;const i=n.length-t.length-1;if(i<0||Wc.test(n[i]))return!0}return!1}function Gc(n){let e=0;for(const t of n)if(new RegExp("\\p{L}","u").test(t)&&e++,e>=2)return!0;return!1}function Xc(n){return/\.{3,}$/.test(n)}function Jc(n,e,t,i){if(i==="“")return!0;if(i!=='"')return!1;let s=0;for(let r=e;r<t;r++)n[r]==='"'&&s++;return s%2===1}const Yc=new RegExp(`[.!?][”"'’)\\]]*\\s+—\\s+(?=\\p{Lu})`,"gu");function Qc(n,e){const t=[...n.matchAll(Yc)].map(s=>s.index+s[0].length);if(t.length===0)return e;const i=[];for(const s of e){let r=s.start;for(const o of t)o>r&&o<s.end&&(i.push({start:r,end:o}),r=o);i.push({start:r,end:s.end})}return i}function Zc(n,e,t){const i=Qc(n,e).map(r=>({...r}));for(let r=0;r<i.length-1;r++){const o=Zt(n,i[r].start,i[r].end);if(o!==i[r].end||o<=i[r].start)continue;const a=n[o-1];Jc(n,i[r].start,o,a)&&(i[r].end-=1,i[r+1].start-=1)}const s=[];for(const r of i){let o=r;for(;s.length>0;){const a=s[s.length-1],l=Zt(n,a.start,a.end),c=n.slice(a.start,l);if(!Kc(c,t)&&Gc(c)&&!Xc(c))break;s.pop(),o={start:a.start,end:o.end}}s.push(o)}return s.map(r=>{const o=Zt(n,r.start,r.end);return{text:n.slice(r.start,o),start:r.start,end:r.end,contentEnd:o}})}const ss=new Map;function eu(n){let e=ss.get(n);return e||(e=new Intl.Segmenter(n,{granularity:"sentence"}),ss.set(n,e)),e}async function tu(n,e,t){if(e==="")return[];const s=[...eu(n).segment(e)].map(o=>({start:o.index,end:o.index+o.segment.length})),r=t?[...is[n]??[],...t]:is[n]??[];return Zc(e,s,r)}const nu=["aside","audio","bibliography","biblioref","cell","columnheader","details","endnotes","figure","footnote","glossary","image","landmarks","loa","loi","lot","lov","noteref","pagebreak","pullquote","row","rowheader","table","toc","video"],Yr=["heading1","heading2","heading3","heading4","heading5","heading6","paragraph","blockquote","preformatted","pullquote","list","listItem","table","row","cell","columnheader","rowheader","audio","video","figure","image","math","abstract","acknowledgments","afterword","appendix","article","aside","bibliography","chapter","colophon","conclusion","dedication","endnotes","epigraph","epilogue","errata","example","footnote","foreword","glossary","index","introduction","notice","part","preface","prologue","qna","section","summary","tip"],iu={footnote:{drops:["aside"],unconditional:!0},cover:{drops:["image"]},pullquote:{drops:["blockquote","aside"]},epigraph:{drops:["blockquote"]}},su=["noteref","pagebreak"],ru=["audio","video","image","figure","math","table","cover"],ou=["cell","rowheader"],au=["separator"],rs=new Set(Yr),lu=new Set(su),cu=new Set(ru),Qr=new Set(ou),uu=new Set(au);function hu(n,e){const t=I.createInstance();return t.init({lng:n,resources:{[n]:{translation:e}},interpolation:{escapeValue:!1}}),t}function du(n,e,t){if(!e)return n;const i={...n};for(const s of Object.keys(e))i[s]=t(n[s],e[s]);return i}function Zr(n,e){if(typeof e=="string"||typeof n!="object")return e;const t={...n};for(const i of Object.keys(e))t[i]=Zr(n[i],e[i]);return t}function fu(n,e){return du(n,e,Zr)}function eo(n,e=[],t=new Map){for(const i of n)t.set(i,e),i.children&&eo(i.children,[i,...e],t);return t}async function to(n,e){const t=e.contextualizationLocale??"en",i=fu(await qc(t),e.contextualization?.contextualizations);return{i18n:hu(t,i),skip:new Set(e.skip??[]),contextualize:new Set(e.contextualize??[]),contextualizationShapes:e.contextualization?.shapes??{},contextualizationParams:e.contextualization?.params,format:e.format??"plain",inlineContextualization:e.inlineContextualization??!1,language:e.language??"block-level",segmentation:e.segmentation?.mode??"structure",segmentationSuppressions:e.segmentation?.suppressions??{},segmenter:e.segmentation?.segmenter??tu,substitutions:{...zc,...e.substitutions},blockStarts:new Set,tableRowNumbers:new Map,tableCellHeaders:new Map,synthetic:new Set,ancestorChains:eo(n),pendingRange:new Map,edgeSubstitutedLocate:new WeakMap}}const gu=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function no(n){return n.replace(gu,"$1")}const En="#css(",Cn=")";function io(n){return`${En}${encodeURIComponent(n)}${Cn}`}function so(n){if(!(!n||!n.startsWith(En)||!n.endsWith(Cn)))return decodeURIComponent(n.slice(En.length,-Cn.length))}const kn="#domrange(",Rn=")";function ro(n){return`${kn}${encodeURIComponent(JSON.stringify(n))}${Rn}`}function oo(n){if(!(!n||!n.startsWith(kn)||!n.endsWith(Rn)))try{const e=JSON.parse(decodeURIComponent(n.slice(kn.length,-Rn.length)));return!e?.start?.cssSelector||typeof e.start.textNodeIndex!="number"?void 0:e}catch{return}}const An=":~:text=";function ut(n){return encodeURIComponent(n).replace(/-/g,"%2D")}function ao(n){let e="";return n.prefix&&(e+=`${ut(n.prefix)}-,`),e+=ut(n.textStart),n.textEnd&&(e+=`,${ut(n.textEnd)}`),n.suffix&&(e+=`,-${ut(n.suffix)}`),`${An}${e}`}function pu(n){if(!n)return;const e=n.indexOf(An);if(e===-1)return;const t=n.slice(e+An.length).split("&")[0];if(t)try{let i=t.split(",");const s={textStart:""};return i[0].endsWith("-")&&(s.prefix=decodeURIComponent(i[0].slice(0,-1)),i=i.slice(1)),i.length>0&&i[i.length-1].startsWith("-")&&(s.suffix=decodeURIComponent(i[i.length-1].slice(1)),i=i.slice(0,-1)),i.length===0||i[0]===""?void 0:(s.textStart=decodeURIComponent(i[0]),i.length>1&&(s.textEnd=decodeURIComponent(i[1])),s)}catch{return}}function mu(n,e){if(!n.domRange||!e.domRange)return;const t={start:n.domRange.start,end:e.domRange.end??e.domRange.start};return n.domRange.container!==void 0&&(t.container=n.domRange.container),{domRange:t,cssSelector:t.container??t.start.cssSelector}}function On(n){const e=n?.textref;if(!e)return;const t=e.indexOf(":~:"),i=t===-1?e:e.slice(0,t);let s,r;const o=oo(i);if(o)r=o,s=o.container??o.start.cssSelector;else{const c=so(i);c!==void 0?s=c:n?.id&&i===`#${CSS.escape(n.id)}`&&(s=i)}const a=pu(e);if(s===void 0&&r===void 0&&a===void 0)return;const l={};return s!==void 0&&(l.cssSelector=s),r!==void 0&&(l.domRange=r),a?.textEnd!==void 0?l.fragment=ao(a):a&&(l.text={highlight:a.textStart},a.prefix!==void 0&&(l.text.before=a.prefix),a.suffix!==void 0&&(l.text.after=a.suffix)),l}function Te(n,e){const t=n.cssSelector??n.domRange?.start.cssSelector;return t?{cssSelector:t,text:{highlight:e}}:{...n,text:{highlight:e}}}function _(n,e){const t=On(n);if(t)return{own:!0,ref:t};for(const i of e.get(n)??[]){const s=On(i);if(s)return{own:!1,ref:s}}}function Jn(n,e){if(n)return n.own?n.ref:Te(n.ref,e)}function Yn(n,e,t){return(n&&e?mu(n.ref,e.ref):void 0)??t}function lo(n,e,t){const{ancestorChains:i}=t,s=new Map;for(const r of e)r&&!Array.isArray(r)&&s.set(r,(s.get(r)??0)+1);return n.map((r,o)=>{if(r.offsets)return r;const a=e[o],l=r.plain??r.ssml??"";if(Array.isArray(a)){const[d,f]=a,g=_(d,i),p=_(f,i),m=Yn(g,p,Jn(g,l));return m?{...r,locate:m}:r}const c=a,u=c?_(c,i):void 0;if(!u)return r;const h={...r,locate:u.ref};if(!t.synthetic.has(r)){const d=t.pendingRange.get(r),f=d!==void 0||c&&(s.get(c)??0)>1;h.locate=u.own&&!f?u.ref:Te(u.ref,l),h.offsets=[{start:d?.start??0,end:d?.end??l.length,locate:h.locate}]}return h})}function Qn(n){const e=Pn(n.text);return e?e.plain??(e.ssml?le(e.ssml):""):""}function Su(n){const e=new Map,t=new Map;let i=0,s;return n.forEach((r,o)=>{e.set(r,o+1);const a=r.children??[];if(i=Math.max(i,a.length),a.some(l=>l.role?.includes("columnheader"))){s=a.map(Qn);return}s&&a.forEach((l,c)=>{const u=l.role??[];if(!u.includes("cell")&&!u.includes("rowheader"))return;const h=s[c];h&&t.set(l,h)})}),{lines:n.length,columns:i,rowNumbers:e,cellHeaders:t}}function se(n,e){const t=e.format==="ssml"?{ssml:X(n)}:{plain:n};return e.synthetic.add(t),t}function re(n,e,t,i){n.push(...i);for(let s=0;s<i.length;s++)e.push(t)}function co(n,e,t,i,s,r,o){o?(s.some(a=>t.blockStarts.has(a))&&t.blockStarts.add(o),re(n,e,r[0]??i,[o])):(n.push(...s),e.push(...r))}function Ge(n,e,t,i){const s=t?`${e}.${t}`:void 0;if(s&&n.i18n.exists(s))return n.i18n.t(s,i);if(n.i18n.exists(e))return n.i18n.t(e,i)}function Zn(n,e){return Qr.has(n)?!0:e.contextualize.has(n)}function yu(n,e,t){return e.some(i=>{const s=iu[i];return s?.drops.includes(n)?s.unconditional||Zn(i,t):!1})}function Rt(n,e,t,i,s){const r=e.lastIndexOf(t);if(r===-1)return;const o=_(i,s.ancestorChains);if(!o)return;const a=Te(o.ref,t);n.offsets=[{start:r,end:r+t.length,locate:a}],n.locate=o.own?o.ref:a}function os(n,e,t,i,s,r){const o=r?.value;if(o!==void 0&&o===Qn(t)){if(i.language!=="none"){const l=typeof t.text=="object"?t.text.language:void 0;l&&(n.language=l)}i.synthetic.delete(n),Rt(n,e,o,t,i);return}const a=r?.description;a!==void 0&&a===t.description&&(s==="figure"||s==="table")&&Rt(n,e,a,t,i)}function as(n,e,t,i,s,r,o,a){if(!Zn(s,i))return;if((i.i18n.exists(`${s}.block.start`)||i.i18n.exists(`${s}.block.end`))&&i.contextualizationShapes[s]!=="inline"){const c=r==="before"?`${s}.block.start`:`${s}.block.end`,u=Ge(i,c,o,a);if(u){const h=se(u,i);os(h,u,t,i,s,a),re(n,e,t,[h])}return}if(r==="before"){const c=Ge(i,`${s}.inline`,o,a);if(c){const u=se(c,i);os(u,c,t,i,s,a),re(n,e,t,[u])}}}function ls(n,e,t,i){const s=`${e}.parts.${t}`;return n.i18n.exists(s,{count:i})?n.i18n.t(s,{count:i}):String(i)}function vu(n){return n.description===void 0?{variantKey:"unlabelled"}:{variantKey:"labelled",params:{description:n.description}}}function cs(n,e){const t=e.tableCellHeaders.get(n);return{variantKey:t!==void 0?"withHeader":"withoutHeader",params:{header:t??"",value:Qn(n)}}}const bu={table:(n,e)=>{const t=(n.children??[]).filter(s=>s.role?.includes("row")),i=Su(t);for(const[s,r]of i.rowNumbers)e.tableRowNumbers.set(s,r);for(const[s,r]of i.cellHeaders)e.tableCellHeaders.set(s,r);return{params:{lines:ls(e,"table","lines",i.lines),columns:ls(e,"table","columns",i.columns)}}},row:(n,e)=>({params:{count:String(e.tableRowNumbers.get(n)??"")}}),cell:cs,rowheader:cs};function us(n,e,t){const i=vu(e);let s=i.variantKey,r=i.params;const o=bu[n]?.(e,t);o&&(o.variantKey&&(s=o.variantKey),r={...r,...o.params});const a=t.contextualizationParams?.(n,e);return a&&(r={...r,...a}),{variantKey:s,params:r}}const wu=["math","separator"],ei=new WeakSet,Ne=new WeakSet,uo=new WeakMap,ho=new WeakMap;function Tn(n){return n.role?.some(e=>wu.includes(e))?!1:!n.audioref&&!n.imgref&&!n.textref&&!n.videoref&&(!n.text||Je(n.text))&&!(n.children&&n.children.length>0)&&!n.description}function xu(n){return!n.audioref&&!n.imgref&&!n.textref&&!n.videoref&&(!n.text||Je(n.text))&&!!(n.children&&n.children.length>0)&&!(n.role&&n.role.length>0)&&!n.id}function Eu(n){return!(n.role&&n.role.length>0)&&!n.id&&!n.textref&&!n.imgref&&!n.audioref&&!n.videoref}class ht{el;object={};children=[];noText=!1;finalize(){const e=this.object,t=[];for(const i of this.children){const s=i.finalize();if(!Tn(s)){if(xu(s)){t.push(...s.children??[]);continue}t.push(s)}}if(t.length>0&&(e.children=t),e.role?.length&&e.children?.length===1&&!e.role.includes("presentation")){const i=e.children[0];i.role?.length&&e.role.every(s=>i.role.includes(s))&&delete e.role}if((!e.text||Je(e.text))&&e.children?.length===1){const i=e.children[0];Eu(i)&&(i.text&&(e.text=i.text),e.children=i.children)}return e}}function Nn(n){const e={};n.id&&(e.id=n.id),n.textref&&(e.textref=n.textref),n.imgref&&(e.imgref=n.imgref),n.audioref&&(e.audioref=n.audioref),n.videoref&&(e.videoref=n.videoref);const t=Ea(n.text);t!==void 0&&(e.text=t),n.role&&n.role.length>0&&(e.role=n.role),n.children&&n.children.length>0&&(e.children=n.children.map(Nn)),n.description&&(e.description=n.description),ei.has(n)&&Ne.add(e);const i=uo.get(n);return i&&ho.set(e,i),e}function fo(n){const e={};return n.id&&(e.id=n.id),n.textref&&(e.textref=n.textref),n.imgref&&(e.imgref=n.imgref),n.audioref&&(e.audioref=n.audioref),n.videoref&&(e.videoref=n.videoref),n.role&&(e.role=n.role),n.description&&(e.description=n.description),typeof n.text=="string"?e.text={plain:n.text,ssml:"",language:""}:n.text&&(e.text={plain:n.text.plain??"",ssml:n.text.ssml??"",language:n.text.language}),n.children&&(e.children=n.children.map(fo)),e}function At(n){let e="";const t=[];for(const i of n){if(i.length===1&&wa(i)&&e.endsWith(i)){t.push({start:e.length,end:e.length});continue}e&&!Oe(i)&&!/\s$/.test(e)&&!/^\s/.test(i)&&(e+=" ");const s=e.length;e+=i,t.push({start:s,end:e.length})}return{joined:e,ranges:t}}function _t(n,e){const t=ho.get(n);if(t)return ji({cssSelector:t});const i=_(n,e.ancestorChains)?.ref;return i&&ji(i)}function Cu(n,e,t){const i=[];return n.forEach((s,r)=>{if(s.offsets){i.push(...s.offsets);return}if(t.synthetic.has(s))return;const o=e[r];if(!o||Array.isArray(o))return;const a=_(o,t.ancestorChains);if(!a)return;const l=t.format==="ssml"?s.ssml:s.plain;if(!l)return;const c=t.pendingRange.get(s),u=Ne.has(o)?_t(o,t)??a.ref:Te(a.ref,l);i.push({start:c?.start??0,end:c?.end??l.length,locate:u})}),i}function hs(n,e,t,i){const s=i.edgeSubstitutedLocate.get(n);if(s)return s[t];if(!(!e||Array.isArray(e)||!Ne.has(e)))return _t(e,i)}function ku(n,e,t){const i=n.map((l,c)=>{if(l.locate)return l.locate;if(t.synthetic.has(l))return;const u=e[c];if(!u||Array.isArray(u))return;const h=t.format==="ssml"?l.ssml:l.plain;if(h)return Ne.has(u)?_t(u,t):Jn(_(u,t.ancestorChains),h)}),s=i.findIndex(l=>l!==void 0);if(s===-1)return;let r=i.length-1;for(;i[r]===void 0;)r--;if(s===r)return i[s];const o=e[s],a=e[r];if(o&&a&&!Array.isArray(o)&&!Array.isArray(a)){const l=_(o,t.ancestorChains),c=_(a,t.ancestorChains);return Yn(l,c,i[s])}return i[s]}function ti(n,e,t){let i,s=!1;const r=[],o=[],a=[];for(let g=0;g<n.length;g++){const p=n[g],m=t.format==="ssml"?p.ssml:p.plain;if(m&&(r.push(m),o.push(p),a.push(e[g]),p.language!==void 0)){if(s&&p.language!==i)return;i=p.language,s=!0}}if(r.length===0)return;const{joined:l}=At(r),c=t.format==="ssml"?{ssml:l}:{plain:l};i&&(c.language=i),n.some(g=>t.synthetic.has(g))&&t.synthetic.add(c);const u=Cu(o,a,t);u.length>0&&(c.offsets=u);const h=ku(o,a,t);h&&(c.locate=h);const d=hs(o[0],a[0],"leading",t),f=hs(o[o.length-1],a[o.length-1],"trailing",t);return(d||f)&&t.edgeSubstitutedLocate.set(c,{leading:d,trailing:f}),c}function go(n,e,t,i){if(e==="plain"&&t!=="block-level"&&t!=="none"&&n.ssml&&Ls(n.ssml))return $s(n.ssml,n.language).map(r=>{const o={plain:r.plain};return r.language&&(o.language=r.language),i.pendingRange.set(o,{start:r.start,end:r.end}),o});const s={};return n.language&&(s.language=n.language),e==="ssml"?s.ssml=n.ssml??X(n.plain??""):s.plain=n.plain??le(n.ssml??""),(t==="block-level"||t==="none")&&(s.ssml&&(s.ssml=no(s.ssml)),t==="none"&&delete s.language),[s]}function Ze(n,e){return e!=="ssml"?n:n.replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function ds(n,e){return e.size>0&&n.some(t=>e.has(t))}function Ru(n,e){const t=Pn(n.text),i=t?go(t,e.format,e.language,e):[];if(!e.contextualize.has("pagebreak"))return i;const s=e.i18n.exists("pagebreak.block.start")?"pagebreak.block.start":"pagebreak.inline",r=Ge(e,s);if(r===void 0)return i;const o=se(r,e);if(i.length===0)return[o];const a=ti([o,...i],[void 0,...i.map(()=>n)],e);return a?(a.plain!==void 0&&(a.plain+="."),a.ssml!==void 0&&(a.ssml+="."),[a]):[o,...i]}function Au(n){return(n.role??[]).some(e=>lu.has(e))}function Ou(n,e,t,i,s,r){const o=typeof n.text=="object"?n.text.language:void 0,a=new Map((n.children??[]).map(d=>[d.id,d])),l=[],c=[],u=[];for(const d of Va(e)){if(d.placeholderId!==void 0){const g=a.get(d.placeholderId);if(!g)continue;s.inlineContextualization||!Au(g)?po(g,l,c,s,r):u.push(g);continue}if(!d.ssml)continue;if(s.format==="plain"&&s.language!=="block-level"&&s.language!=="none"&&Ls(d.ssml)){for(const g of $s(d.ssml,o)){const p={plain:g.plain};g.language&&(p.language=g.language),l.push(p),c.push(n)}continue}const f={};o&&(f.language=o),s.format==="ssml"?f.ssml=d.ssml:f.plain=le(d.ssml),(s.language==="block-level"||s.language==="none")&&(f.ssml&&(f.ssml=no(f.ssml)),s.language==="none"&&delete f.language),l.push(f),c.push(n)}const h=l.length>1?ti(l,c,s):void 0;return co(t,i,s,n,l,c,h),u}function po(n,e,t,i,s){const r=n.role??[];if(ds(r,i.skip))return;const o=r.some(d=>rs.has(d)),a=o&&!s,l=e.length,c=r.filter(d=>d!=="footnote"&&d!=="pagebreak"&&!yu(d,r,i)),u=r.some(d=>cu.has(d)&&i.contextualize.has(d)),h=r.includes("table")&&n.description!==void 0&&!u;if(h){const d=se(n.description,i);Rt(d,n.description,n.description,n,i),re(e,t,n,[d])}for(const d of c){if(d==="figure"&&n.description===void 0)continue;const{variantKey:f,params:g}=us(d,n,i);as(e,t,n,i,d,"before",f,g)}if(r.includes("noteref"))for(const d of n.children??[]){const f=d.role??[];if(!ds(f,i.skip))if(f.includes("footnote")){const g=i.contextualize.has("footnote"),p=i.i18n.exists("footnote.block.start")||i.i18n.exists("footnote.block.end"),m=f.some(A=>rs.has(A))&&!s&&!i.inlineContextualization,v=g?Ge(i,p?"footnote.block.start":"footnote.inline"):void 0,w=g&&(v!==void 0||p),S=[],y=[];v!==void 0&&(S.push(se(v,i)),y.push(d));const b=[],C=[];if(ne([d],b,C,i,s||m),m&&b.length>0&&i.blockStarts.add(b[0]),S.push(...b),y.push(...C),w&&p){const A=Ge(i,"footnote.block.end");A!==void 0&&(S.push(se(A,i)),y.push(d))}const R=w&&S.length>1?ti(S,y,i):void 0;co(e,t,i,d,S,y,R)}else ne([d],e,t,i,s)}else if(!r.some(d=>uu.has(d))){const d=typeof n.text=="object"?n.text.ssml:void 0;if(d&&za(d)){const f=Ou(n,d,e,t,i,s);if(f.length>0){const g=s||o&&e.length>l;ne(f,e,t,i,g)}}else if(r.includes("pagebreak")){if(re(e,t,n,Ru(n,i)),n.children){const f=s||o&&e.length>l;ne(n.children,e,t,i,f)}}else{const g=r.some(p=>Qr.has(p)&&Zn(p,i))?void 0:Pn(n.text);if(g&&re(e,t,n,go(g,i.format,i.language,i)),n.children){const p=s||o&&e.length>l;ne(n.children,e,t,i,p)}}}if(a&&e.length>l&&i.blockStarts.add(e[l]),n.description!==void 0&&!u&&!h){const d=se(n.description,i);r.includes("figure")&&Rt(d,n.description,n.description,n,i),re(e,t,n,[d])}for(const d of c){if(d==="figure"&&n.description===void 0)continue;const{variantKey:f,params:g}=us(d,n,i);as(e,t,n,i,d,"after",f,g)}}function ne(n,e,t,i,s){n.forEach((r,o)=>po(r,e,t,i,o===0?s:!1))}const Tu=Fs;async function mo(n,e,t,i){const s=Tu(n);let r="";const o=[];for(const d of s)o.push(r.length),d.kind==="text"?r+=d.text:d.kind==="paired"&&(r+=d.innerText);if(!r)return;const a=await t(e,r,i);if(a.length<=1)return;const l=[];let c="",u=0;function h(d,f,g){let p=f;const m=f+d.length;for(;p<m;){const v=a[u],w=Math.min(m,v.end),S=w>=v.end&&u<a.length-1;let y=d.slice(p-f,w-f);S&&(y=y.replace(/[ \t\r\n]+$/,""));const b=X(y);c+=g?g(b):b,p=w,S&&(l.push(c),c="",u++)}}return s.forEach((d,f)=>{if(d.kind==="selfClosing")c+=d.raw;else if(d.kind==="text")h(d.text,o[f]);else{const g=`<${d.tag}${d.attrs}>`,p=`</${d.tag}>`;d.innerText?h(d.innerText,o[f],m=>`${g}${m}${p}`):c+=g+p}}),c&&l.push(c.replace(/[ \t\r\n]+$/,"")),l}async function Nu(n,e){const t=n.language??"en",i=e.segmentationSuppressions[t],s=e.format==="ssml"?n.ssml:n.plain;if(!s)return;const r=await e.segmenter(t,Ze(s,e.format),i);if(r.length<=1)return;if(e.format!=="ssml")return r.map(a=>({text:a.text,start:a.start,end:a.contentEnd}));const o=await mo(s,t,e.segmenter,i);if(o)return r.map((a,l)=>({text:o[l],start:a.start,end:a.contentEnd}))}const fs=new Set(["cell","rowheader","columnheader","row","table","list","listItem","heading1","heading2","heading3","heading4","heading5","heading6"]);function gs(n){return n?(Array.isArray(n)?n[1]:n).role??[]:[]}function ps(n,e,t,i){return i.edgeSubstitutedLocate.get(e)?.[t]?!0:!!n&&!Array.isArray(n)&&Ne.has(n)}function Du(n,e,t,i,s){if(s.synthetic.has(n)||s.synthetic.has(t)||!e||!i)return!1;const r=s.format==="ssml"?n.ssml:n.plain,o=s.format==="ssml"?t.ssml:t.plain;return!(!r||!o||(n.language??"en")!==(t.language??"en")||gs(e).some(a=>fs.has(a))||gs(i).some(a=>fs.has(a))||ps(e,n,"trailing",s)||ps(i,t,"leading",s))}async function ms(n,e,t,i,s){const r=t.synthetic.has(n)?void 0:await Nu(n,t);if(!r){i.push(n),s.push(e);return}const o=t.blockStarts.has(n);o&&t.blockStarts.delete(n);const a=Array.isArray(e)?void 0:e,l=a?_(a,t.ancestorChains):void 0,c=a&&Ne.has(a)?_t(a,t):void 0,u=t.edgeSubstitutedLocate.get(n);r.forEach(({text:h,start:d,end:f},g)=>{const p={...n,[t.format]:h},m=(g===0?u?.leading:void 0)??(g===r.length-1?u?.trailing:void 0)??c;if(m)p.locate=m,p.offsets=[{start:d,end:f,locate:m}];else if(l){const v=t.format==="ssml"?Ze(h,t.format):h,w=Te(l.ref,v);p.locate=w,p.offsets=[{start:d,end:f,locate:w}]}o&&g===0&&t.blockStarts.add(p),i.push(p),s.push(e)})}function Ot(n,e){let t=0;for(;t<n.length-1&&n[t+1].start<=e;)t++;return t}async function Pu(n,e,t,i){const s=n.map(c=>Ze(e.format==="ssml"?c.ssml:c.plain,e.format)),{joined:r,ranges:o}=At(s),a=await e.segmenter(t,r,i),l=new Array(n.length-1).fill(!1);for(const c of a){const u=Ot(o,c.start),h=c.end>c.start?Ot(o,c.end-1):u;for(let d=u;d<h;d++)l[d]=!0}return l}function Fu(n,e,t,i,s,r,o){const a=[];for(let l=s;l<=r;l++){const c=_(e[l],o.ancestorChains);if(!c)continue;const u=t[l],h=Math.max(u.start,i.start),d=Math.min(u.end,l===r?i.contentEnd:i.end);if(d<=h)continue;const f=h-u.start,g=d-u.start,p=Ze(o.format==="ssml"?n[l].ssml:n[l].plain,o.format),m=Te(c.ref,p.slice(f,g));a.push({start:f,end:g,locate:m})}return a}async function Iu(n,e,t,i,s){const r=n[0].language??"en",o=t.segmentationSuppressions[r],a=n.map(g=>Ze(t.format==="ssml"?g.ssml:g.plain,t.format)),{joined:l,ranges:c}=At(a),u=await t.segmenter(r,l,o);let h,d;t.format==="ssml"&&(d=At(n.map(g=>g.ssml)).joined,h=u.length>1?await mo(d,r,t.segmenter,o):void 0),(u.length>0?u:[{text:l,start:0,end:l.length,contentEnd:l.length}]).forEach((g,p)=>{const m=Ot(c,g.start),v=g.end>g.start?Ot(c,g.end-1):m,w=t.format==="ssml"?h?h[p]:d:g.text,S={[t.format]:w};r&&(S.language=r),n.slice(m,v+1).some(N=>t.blockStarts.has(N))&&t.blockStarts.add(S);const b=Fu(n,e,c,g,m,v,t);b.length>0&&(S.offsets=b);const C=_(e[m],t.ancestorChains),R=Jn(C,w),A=m!==v?Yn(C,_(e[v],t.ancestorChains),R):R;A&&(S.locate=A),i.push(S),s.push(m===v?e[m]:[e[m],e[v]])})}async function So(n,e,t){if(t.segmentation!=="sentence")return{out:n,sources:e};const i=[],s=[];let r=0;for(;r<n.length;){let o=r;for(;o+1<n.length&&Du(n[o],e[o],n[o+1],e[o+1],t);)o++;if(o===r){await ms(n[r],e[r],t,i,s),r=o+1;continue}const a=n.slice(r,o+1),l=e.slice(r,o+1),c=a[0].language??"en",u=await Pu(a,t,c,t.segmentationSuppressions[c]);let h=0;for(let d=0;d<a.length;d++)d<a.length-1&&u[d]||(h===d?await ms(a[h],l[h],t,i,s):await Iu(a.slice(h,d+1),l.slice(h,d+1),t,i,s),h=d+1);r=o+1}return{out:i,sources:s}}function yo(n,e){return Object.keys(e.substitutions).length===0?n:n.map(t=>{if(t.ssml){const{ssml:a,plain:l,map:c}=$a(t.ssml,e.substitutions);if(a===t.ssml)return t;const u={...t,ssml:a};return Vi(u,{plain:l,map:c}),u}const i=t.plain;if(!i)return t;const{text:s,map:r}=Ia(i,e.substitutions);if(s===i)return t;const o={...t,plain:s};return Vi(o,{plain:i,map:r}),o})}async function Lu(n,e){const t=[],i=[],s=await to(n,e);ne(n,t,i,s,!1);const r=await So(t,i,s);return yo(lo(r.out,r.sources,s),s)}async function $u(n,e){const t=[],i=[],s=await to(n,e);ne(n,t,i,s,!1);const r=await So(t,i,s),o=r.out.map(l=>s.blockStarts.has(l)),a=lo(r.out,r.sources,s);return{utterances:yo(a,s),sources:r.sources,blockStarts:o}}class Mu{engine;contentQueue=[];events=new Lt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;contextualizationOverrides;segmentationOverrides;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,t={}){this.engine=e,this._defaults=new Mr(t.defaults),this._preferences=new Re(t.preferences),this._settings=new wn(this._preferences,this._defaults),this.contextualizationOverrides=t.contextualizationOverrides,this.segmentationOverrides=t.segmentationOverrides,this.setupEngineListeners(),this.applyEngineParameters(),this.initializeEngine()}applyEngineParameters(){this.engine.setRate(this._settings.rate),this.engine.setPitch(this._settings.pitch),this.engine.setVolume(this._settings.volume)}async initializeEngine(){try{await this.engine.initialize?.()}catch(e){console.warn("Failed to initialize speech engine:",e)}}setupEngineListeners(){this.engine.on("start",()=>{this.setNavigatorState("playing");const e=this.getCurrentContent();e&&this.emitUtteranceBoundary(e),this.emitEvent({type:"start"})}),this.engine.on("end",()=>{const e=this.engine.getCurrentUtteranceIndex(),t=this.engine.getUtteranceCount();if(e<t-1){const i=this._settings.autoPause==="utterance"||this.contentBlockStarts[e+1]===!0;this._settings.autoPause!=="none"&&i?(this.pendingAutoPauseIndex=e+1,this.setNavigatorState("paused"),this.emitEvent({type:"pause"})):this.pendingAdvanceTimeout=setTimeout(()=>{this.pendingAdvanceTimeout=null,this.engine.speak(e+1)},this._settings.pauseDuration)}else this.engine.setCurrentUtteranceIndex(0),this.setNavigatorState("idle");this.emitEvent({type:"end"})}),this.engine.on("pause",()=>{this.setNavigatorState("paused"),this.emitEvent({type:"pause"})}),this.engine.on("resume",()=>{this.setNavigatorState("playing"),this.emitEvent({type:"resume"})}),this.engine.on("stop",()=>{this.setNavigatorState("idle"),this.emitEvent({type:"stop"})}),this.engine.on("error",e=>{this.setNavigatorState("idle"),this.emitEvent(e)}),this.engine.on("ready",()=>{if(this.contentQueue.length===0)return;const e=this.pendingResumeIndex,t=this.pendingResumeState;if(this.pendingResumeIndex=null,this.pendingResumeState=null,this.navigatorState==="loading"){if(t==="playing"){this.setNavigatorState("playing"),this.engine.speak(e??0);return}if(t==="paused"){const i=e??0;i>0?this.engine.setCurrentUtteranceIndex(i,()=>this.setNavigatorState("paused")):this.setNavigatorState("paused");return}this.setNavigatorState("ready"),this.emitEvent({type:"ready"})}}),this.engine.on("boundary",e=>{const{charIndex:t,charLength:i}=e.detail??{},s=this.getCurrentContent(),r=s&&typeof t=="number"&&typeof i=="number"?Wr(s,t,i):void 0;this.emitEvent(r?{...e,detail:{...e.detail,...r}}:e)}),this.engine.on("mark",e=>{this.emitEvent(e)}),this.engine.on("voiceschanged",()=>{this.emitEvent({type:"voiceschanged"})}),this.engine.on("languagefallback",e=>{this.emitEvent(e)}),this.engine.on("enginefallback",e=>{this.emitEvent(e)}),this.engine.on("enginerecovered",e=>{this.emitEvent(e)})}setNavigatorState(e){this.navigatorState=e}async getVoices(){return this.engine.getAvailableVoices()}setVoice(e){this.engine.setVoice(e)}getCurrentVoice(){return this.engine.getCurrentVoice()}setSpeakInContentLanguage(e){this.engine.setSpeakInContentLanguage(e)}getSpeakInContentLanguage(){return this.engine.getSpeakInContentLanguage()}loadContent(e){if(this.source)throw new Error("loadContent() cannot be used after loadGndContent() — the two are exclusive. Create a new navigator instance to switch content sources.");this.setContentQueue(e)}async loadGndContent(e){this.source=e,await this.reextract()}setContentQueue(e,t=null,i=null){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,(this.navigatorState==="playing"||this.navigatorState==="paused")&&this.engine.stop();const s=Array.isArray(e)?e:[e];this.contentQueue=[...s],this.pendingResumeIndex=t,this.pendingResumeState=i,this.setNavigatorState("loading"),this.emitEvent({type:"loading"}),this.engine.loadUtterances(s,t??void 0),this.emitContentChangeEvent({content:s})}async reextract(){if(!this.source)return;const e=this.navigatorState==="playing"||this.navigatorState==="paused"?this.navigatorState:null,t=this.contentSources,i=this.getCurrentUtteranceIndex(),{utterances:s,sources:r,blockStarts:o}=await $u(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,contextualization:{contextualizations:this.contextualizationOverrides?.contextualizations,shapes:vc(this._settings.verbosity,this.contextualizationOverrides?.shapes),params:this.contextualizationOverrides?.params},language:this._settings.language,segmentation:{mode:this._settings.segmentation,suppressions:this.segmentationOverrides?.suppressions,segmenter:this.segmentationOverrides?.segmenter}});this.contentSources=r,this.contentBlockStarts=o;const a=e?this.resolveResumeIndex(t,i,r):null;this.setContentQueue(s,a,e)}resolveResumeIndex(e,t,i){for(let s=Math.min(t,e.length-1);s>=0;s--){const r=e[s];if(r===void 0||Array.isArray(r))continue;const o=i.indexOf(r);if(o!==-1)return o}return null}getCurrentContent(){const e=this.getCurrentUtteranceIndex();return e<this.contentQueue.length?this.contentQueue[e]:null}getContentQueue(){return[...this.contentQueue]}getCurrentUtteranceIndex(){return this.engine.getCurrentUtteranceIndex()}play(){if(this.navigatorState==="paused")if(this.setNavigatorState("playing"),this.pendingAutoPauseIndex!==null){const e=this.pendingAutoPauseIndex;this.pendingAutoPauseIndex=null,this.engine.speak(e)}else this.engine.resume();else if(this.navigatorState==="ready"||this.navigatorState==="idle")this.setNavigatorState("playing"),this.engine.speak();else if(this.navigatorState==="playing")return}pause(){this.navigatorState==="playing"&&(this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("paused"),this.engine.pause())}stop(){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,this.setNavigatorState("idle"),this.engine.stop(),this.emitEvent({type:"stop"})}clearPendingAdvance(){this.pendingAdvanceTimeout!==null&&(clearTimeout(this.pendingAdvanceTimeout),this.pendingAdvanceTimeout=null)}skipToPosition(e,t=!1){const i=this.getCurrentUtteranceIndex();return e<0||e>=this.contentQueue.length?!1:(e===i||(this.clearPendingAdvance(),this.navigatorState==="paused"&&!t?(this.pendingAutoPauseIndex!==null&&(this.pendingAutoPauseIndex=e),this.engine.setCurrentUtteranceIndex(e,s=>{if(s){const r=this.getCurrentContent();r&&this.emitUtteranceBoundary(r),this.emitEvent({type:"skip",detail:{position:e}})}})):(this.pendingAutoPauseIndex=null,this.setNavigatorState("playing"),this.engine.speak(e))),!0)}next(e=!1){const t=this.getCurrentUtteranceIndex();return this.skipToPosition(t+1,e)}previous(e=!1){const t=this.getCurrentUtteranceIndex();return this.skipToPosition(t-1,e)}jumpTo(e,t=!1){return this.skipToPosition(e,t)}getState(){return this.navigatorState}on(e,t){return this.events.on(e,t)}emitEvent(e){this.events.emit(e.type,e)}emitUtteranceBoundary(e){const t=this._settings.segmentation,i=Kr(e,t);if(!i.length)return;const s=t==="sentence"?"sentence":"structure";this.emitEvent({type:"boundary",detail:{name:s,charIndex:0,charLength:(e.plain??"").length,locate:i}})}emitContentChangeEvent(e){this.events.emit("contentchange",{type:"contentchange",detail:e})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new vn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){!this.source&&Ui.some(t=>e[t]!==void 0)&&console.warn("submitPreferences(): extraction-affecting preferences (format, inlineContextualization, verbosity, skip, contextualize, language, segmentation) have no effect on content loaded via loadContent() — use loadGndContent() to re-extract on submission."),this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new wn(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new vn(this._preferences,this._settings)),Ui.some(t=>!this.sameSettingValue(e[t],this._settings[t]))&&await this.reextract()}sameSettingValue(e,t){return Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(i=>t.includes(i)):e===t}async destroy(){this.clearPendingAdvance(),this.events.clear(),await this.engine.destroy()}}const _u=["heading1","heading2","heading3","heading4","heading5","heading6"],Ss={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",grid:"table",gridcell:"cell",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},Bu={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},Uu={article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"},zu=new Set(["table","tr","td","th"]),Vu=new Set(["table","row","cell","columnheader","rowheader"]);function ju(n){const e=n.getAttribute("role");if(!e)return!1;const t=e.split(/\s+/).filter(Boolean);return t.includes("presentation")||t.includes("none")}function Hu(n){for(let e=n.parentElement;e;e=e.parentElement)if(ju(e))return!0;return!1}function qu(n,e,t){return zu.has(e)||t.some(i=>Vu.has(i))}function pt(n,e){const t=n.getAttribute("role");return t?t.split(/\s+/).filter(Boolean).includes(e):!1}function Wu(n){return n.tagName.toLowerCase()==="table"||pt(n,"table")||pt(n,"grid")||pt(n,"treegrid")}function Ku(n){return n.tagName.toLowerCase()==="tr"||pt(n,"row")}function Gu(n){let e=null;for(let i=n.parentElement;i;i=i.parentElement)if(Wu(i)){e=i;break}return e?e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:i=>Ku(i)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===n:!1}function vo(n){const e=[];let t=!1;const i=n.getAttribute("role");if(i)for(const r of i.split(/\s+/).filter(Boolean))if((r==="presentation"||r==="none")&&(t=!0),r==="heading"){let o=2;const a=parseInt(n.getAttribute("aria-level")??"",10);Number.isFinite(a)&&a>=1&&(o=Math.min(a,6)),e.push(_u[o-1])}else Ss[r]&&e.push(Ss[r]);const s=n.getAttribute("epub:type");if(s)for(const r of s.split(/\s+/).filter(Boolean)){const o=Bu[r];o&&e.push(o)}return{attrRoles:e,presentational:t}}function bo(n){const{attrRoles:e,presentational:t}=vo(n);return e.length>0||t}function qe(n){const e=[],t=o=>{e.includes(o)||e.push(o)},{attrRoles:i,presentational:s}=vo(n),r=n.tagName.toLowerCase();if(s)return["presentation"];if(qu(n,r,i)&&Hu(n))return["presentation"];if(r==="body")t("body");else if(r==="th")switch(n.getAttribute("scope")){case"col":t("columnheader");break;case"row":t("rowheader");break;default:{const o=n.parentElement;o&&Gu(o)?t("columnheader"):n.previousElementSibling===null?t("rowheader"):t("cell")}}else{const o=Uu[r];o&&t(o)}for(const o of i)t(o);return e}function ys(n){return!!(n.getAttribute("aria-hidden")==="true"||n.hasAttribute("hidden"))}function Xu(n){let e="";const t=i=>{i.nodeType===3&&(e+=i.nodeValue??"");for(let s=i.firstChild;s;s=s.nextSibling)t(s)};return t(n),e}function Bt(n){return Ce(Xu(n),!0).trim()}function Dn(n){let e="";const t=(i,s)=>{if(i.nodeType===3){e+=i.nodeValue??"";return}if(!(i.nodeType===1&&!s&&bo(i)))for(let r=i.firstChild;r;r=r.nextSibling)t(r,!1)};return t(n,!0),e}function vs(n){return Ce(Dn(n),!0).trim()}function Ju(n){if(ys(n))return[null,!1];const e=(n.getAttribute("aria-labelledby")??"").trim();if(e){const r=[...new Set(e.split(/\s+/).filter(Boolean))],o=n.ownerDocument,a=r.map(l=>o.getElementById(l)).filter(l=>l!==null);if(a.length>0){let l="";a.forEach((u,h)=>{if(ys(u))return;const d=u.getAttribute("aria-label");l+=d||Dn(u),h<a.length-1&&(l+=" ")});const c=Ce(l,!0).trim();if(c!=="")return[{language:"",plain:c},!0]}}const t=(n.getAttribute("aria-label")??"").trim();if(t)return[{language:"",plain:t},!0];const i=(n.getAttribute("aria-describedby")??"").trim();if(i){const o=[...new Set(i.split(/\s+/).filter(Boolean))].map(a=>n.ownerDocument.getElementById(a)).filter(a=>a!==null);if(o.length>0){const a=o.map(c=>Dn(c)).join(" "),l=Ce(a,!0).trim();if(l!=="")return[{language:"",plain:l},!0]}}const s=n.tagName.toLowerCase();if(s==="img"){const r=(n.getAttribute("alt")??"").trim();if(r)return[{language:"",plain:r},!0];const o=(n.getAttribute("title")??"").trim();if(o)return[{language:"",plain:o},!0]}else if(s==="svg"){const r=n.querySelector(":scope > title");if(r){const o=Bt(r);if(o)return[{language:"",plain:o},!0]}}else if(s==="math"){const r=(n.getAttribute("alttext")??"").trim();if(r)return[{language:"",plain:r},!0]}return[null,!0]}const Yu={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Qu(n){return Yu[n]??["",void 0]}const Zu=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]),eh=1;function bs(n){for(let e=n;e;e=e.parentElement){const t=e.getAttribute("xml:lang");if(t)return t;const i=e.getAttribute("lang");if(i)return i}return""}function th(n){for(let e=n.firstChild;e;e=e.nextSibling)if(e.nodeType===eh)return!0;return!1}function wo(n,e){for(let t=e;t;t=t.parentElement)if(t===n)return!0;return!1}const nh=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]);function ih(n){return nh.has(n)}function sh(n){const e=n.slice(0,500);return/<\?xml\b/.test(e)||/xmlns:epub=/.test(e)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(e)?"application/xhtml+xml":"text/html"}function xo(n){return typeof n=="object"&&n!==null&&n.nodeType===Node.ELEMENT_NODE}const Xe={NONE:"",DESCENDANT:" ",CHILD:" > "},D={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"};function rh(n,e){return Object.values(n).includes(e)}const oh="CssSelectorGenerator";function Tt(n="unknown problem",...e){console.warn(`${oh}: ${n}`,...e)}const ah={selectors:[D.id,D.class,D.tag,D.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1,ignoreGeneratedClassNames:!1};function _e(n){return!!n}function lh(n){return Array.isArray(n)?n.filter(e=>rh(D,e)):[]}function Eo(n){return n instanceof RegExp}function ch(n){return["string","function"].includes(typeof n)||Eo(n)}function ws(n){return Array.isArray(n)?n.filter(ch):[]}function uh(n){return n!=null&&typeof n=="object"&&"nodeType"in n&&typeof n.nodeType=="number"}function xs(n){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return uh(n)&&e.includes(n.nodeType)}function Co(n,e){if(xs(n))return n.contains(e)||Tt("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element's real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will not work as intended."),n;const t=e.getRootNode({composed:!1});return xs(t)?(t.nodeType!==Node.DOCUMENT_NODE&&Tt("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),t):ii(e)}function en(n){return typeof n=="number"?n:Number.POSITIVE_INFINITY}function hh(n,e={}){const t=Object.assign(Object.assign({},ah),e);return{selectors:lh(t.selectors),whitelist:ws(t.whitelist),blacklist:ws(t.blacklist),root:Co(t.root,n),combineWithinSelector:_e(t.combineWithinSelector),combineBetweenSelectors:_e(t.combineBetweenSelectors),includeTag:_e(t.includeTag),maxCombinations:en(t.maxCombinations),maxCandidates:en(t.maxCandidates),useScope:_e(t.useScope),maxResults:en(t.maxResults),ignoreGeneratedClassNames:_e(t.ignoreGeneratedClassNames)}}function et(n=[]){const[e=[],...t]=n;return t.length===0?e:t.reduce((i,s)=>{const r=new Set(s);return i.filter(o=>r.has(o))},e)}function dh(n){return[].concat(...n)}function fh(n){return n.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function Nt(n){const e=n.map(t=>{if(Eo(t))return i=>t.test(i);if(typeof t=="function")return i=>{const s=t(i);return typeof s!="boolean"?(Tt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):s};if(typeof t=="string"){const i=new RegExp("^"+fh(t)+"$");return s=>i.test(s)}return Tt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1});return t=>e.some(i=>i(t))}function ni(n,e,t){const i=Co(t,n[0]).querySelectorAll(e);if(i.length!==n.length)return!1;const s=new Set(i);return n.every(r=>s.has(r))}function ko(n,e){e=e??ii(n);const t=[];let i=n;for(;i&&i!==e;)xo(i)&&t.push(i),i=i.parentNode;return t}function gh(n,e){return et(n.map(t=>ko(t,e)))}function ph(n){return typeof n=="object"&&n!==null&&"nodeType"in n&&n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function ii(n){return n.ownerDocument.querySelector(":root")}const Ro=", ",mh=new RegExp(["^$","\\s"].join("|")),Sh=new RegExp(["^$"].join("|")),Ao=[D.nthoftype,D.tag,D.id,D.class,D.attribute,D.nthchild],yh=Nt(["class","id","ng-*"]);function vh({name:n}){return`[${n}]`}function bh({name:n,value:e}){return`[${n}='${e}']`}function wh({nodeName:n,nodeValue:e},t){const i=t.tagName.toLowerCase();return["input","option"].includes(i)&&n==="value"||n==="src"&&e?.startsWith("data:")?!1:!yh(n)}function xh({nodeName:n,nodeValue:e}){return{name:Ae(n),value:Ae(e??void 0)}}function Oo(n,e){const t=Array.from(n.attributes).filter(i=>wh(i,n)).map(xh);return[...t.map(vh),...t.map(bh)]}function Eh(n,e){const t=n.map(i=>Oo(i));return et(t)}const Ch=/^[a-z_-]{3,}$/i,kh=/[bcdfghjklmnpqrstvwxyz]{4,}/i;function Rh(n){if(!Ch.test(n)||n.includes("_")&&!n.includes("__")||/^(css|sc|jsx|emotion|makeStyles|MuiButton|MuiBox)-/i.test(n))return!1;const e=n.split(new RegExp("--|__|[-]|(?<=[a-z])(?=[A-Z])")).filter(t=>t.length>0);if(e.length===0||e.length===1&&e[0].length<4)return!1;for(const t of e)if(t.length<=2||kh.test(t))return!1;return!0}function To(n,e){var t;const i=((t=n.getAttribute("class"))!==null&&t!==void 0?t:"").trim().split(/\s+/).filter(r=>!Sh.test(r));let s=i;if(e?.ignoreGeneratedClassNames){const r=Nt(e.whitelist);s=i.filter(o=>{const a=`.${Ae(o)}`;return r(a)?!0:Rh(o)})}return s.map(r=>`.${Ae(r)}`)}function Ah(n,e){const t=n.map(i=>To(i,e));return et(t)}function No(n,e){var t;const i=(t=n.getAttribute("id"))!==null&&t!==void 0?t:"",s=`#${Ae(i)}`,r=n.getRootNode({composed:!1});return!mh.test(i)&&ni([n],s,r)?[s]:[]}function Oh(n,e){return n.length===0||n.length>1?[]:No(n[0])}function Do(n,e){const t=n.parentNode,i=t&&"children"in t?t.children:null;if(i){for(let s=0;s<i.length;s++)if(i[s]===n)return[`:nth-child(${String(s+1)})`]}return[]}function Th(n,e){return et(n.map(t=>Do(t)))}function Po(n,e){return[Ae(n.tagName.toLowerCase())]}function Fo(n,e){const t=[...new Set(dh(n.map(i=>Po(i))))];return t.length===0||t.length>1?[]:[t[0]]}function Io(n,e){const t=Fo([n])[0],i=n.parentNode,s=i&&"children"in i?i:null;if(s){const o=Array.from(s.children).filter(a=>a.tagName.toLowerCase()===t).indexOf(n);if(o>-1)return[`${t}:nth-of-type(${String(o+1)})`]}return[]}function Nh(n,e){return et(n.map(t=>Io(t)))}function*Lo(n=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let t=0,i=$o(1);for(;i.length<=n.length&&t<e;){t+=1;const s=new Array(i.length);for(let r=0;r<i.length;r++)s[r]=n[i[r]];yield s,i=Ph(i,n.length-1)}}function Dh(n=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(Lo(n,{maxResults:e}))}function Ph(n=[],e=0){const t=n.length;if(t===0)return n;let i=t-1;for(;i>=0&&n[i]===e-(t-1-i);)i-=1;if(i<0)return $o(t+1);n[i]+=1;for(let s=i+1;s<t;s++)n[s]=n[s-1]+1;return n}function $o(n=1){const e=new Array(n);for(let t=0;t<n;t++)e[t]=t;return e}function*Fh(n={}){const e=Object.entries(n);if(e.length===0)return;const t=[{index:e.length-1,partial:{}}];for(;t.length>0;){const i=t.pop();if(!i)break;const{index:s,partial:r}=i;if(s<0){yield r;continue}const[o,a]=e[s];for(let l=a.length-1;l>=0;l--)t.push({index:s-1,partial:Object.assign(Object.assign({},r),{[o]:a[l]})})}}const Ih="3a".toUpperCase(),Lh=/[ !"#$%&'()[\]{|}<>*+,./;=?@^`~\\]/;function Ae(n=""){return CSS?CSS.escape(n):$h(n)}function $h(n=""){return n.split("").map(e=>e===":"?`\\${Ih} `:Lh.test(e)?`\\${e}`:escape(e).replace(/%/g,"\\")).join("")}const Mh={tag:Fo,id:Oh,class:Ah,attribute:Eh,nthchild:Th,nthoftype:Nh},_h={tag:Po,id:No,class:To,attribute:Oo,nthchild:Do,nthoftype:Io};function Bh(n,e,t){return _h[e](n,t)}function Uh(n,e,t){const i=Mh[e];return i(n,t)}function zh(n=[],e,t){return n.filter(i=>t(i)||!e(i))}function Vh(n=[],e){return n.sort((t,i)=>{const s=e(t),r=e(i);return s&&!r?-1:!s&&r?1:0})}function Ut(){const n=new Map;let e;return(t,i)=>{if(t.length!==1)return e??(e=Es(t,i));const[s]=t;let r=n.get(s);return r||(r=Es(t,i),n.set(s,r)),r}}function*jh(n,e,t=Ut()){const i=new Set,s=t(n,e);for(const r of Kh(s,e))i.has(r)||(i.add(r),yield r)}function Es(n,e){const{blacklist:t,whitelist:i,combineWithinSelector:s,maxCombinations:r}=e,o=Nt(t),a=Nt(i),l=(c,u)=>{const h=Uh(n,u,e),d=zh(h,o,a),f=Vh(d,a);return c[u]=s?Array.from(Lo(f,{maxResults:r})):f.map(g=>[g]),c};return Hh(e).reduce(l,{})}function Hh(n){const{selectors:e,includeTag:t}=n,i=[...e];return t&&!i.includes("tag")&&i.push("tag"),i}function qh(n){return n.includes(D.tag)||n.includes(D.nthoftype)?[...n]:[...n,D.tag]}function Wh(n){const{selectors:e,combineBetweenSelectors:t,includeTag:i,maxCandidates:s}=n,r=t?Dh(e,{maxResults:s}):e.map(o=>[o]);return i?r.map(qh):r}function*Kh(n,e){for(const t of Wh(e))yield*Gh(t,n)}function*Gh(n,e){const t={};for(const i of n){const s=e[i];s&&s.length>0&&(t[i]=s)}for(const i of Fh(t))yield Jh(i)}function Xh(n,e){return e[n]?e[n].join(""):""}function Jh(n={}){const e=[...Ao];return n[D.tag]&&n[D.nthoftype]&&e.splice(e.indexOf(D.tag),1),e.map(t=>Xh(t,n)).join("")}function Yh(n,e){return[...n.map(t=>e+Xe.DESCENDANT+t),...n.map(t=>e+Xe.CHILD+t)]}function*Qh(n,e){if(e==="")yield*n;else for(const t of n)yield*Yh([t],e)}function*Zh(n,e,t="",i,s=Ut()){const r=jh(n,i,s);for(const o of Qh(r,t))ni(n,o,e)&&(yield o)}function*ed(n,e,t="",i,s=Ut()){if(n.length===0)return null;const r=[n.length>1?n:[],...gh(n,e).map(o=>[o])];for(const o of r)for(const a of Zh(o,e,t,i,s))yield{foundElements:o,selector:a}}function*td({elements:n,root:e,rootSelector:t="",options:i}){let s=e,r=t,o=!0;const a=Ut();for(;o;){let l=!1;for(const c of ed(n,s,r,i,a)){const{foundElements:u,selector:h}=c;if(l=!0,ni(n,h,e))yield h;else{s=u[0],r=h;break}}l||(o=!1)}}function nd(n){(n instanceof NodeList||n instanceof HTMLCollection)&&(n=Array.from(n));const e=(Array.isArray(n)?n:[n]).filter(xo);return[...new Set(e)]}function id(n){return{value:n,include:!1}}function sd(n,e,t=Xe.NONE){const i={};return e.forEach(s=>{Reflect.set(i,s,Bh(n,s).map(id))}),{element:n,operator:t,selectors:i}}function rd({selectors:n,operator:e}){let t=[...Ao];n[D.tag]&&n[D.nthoftype]&&(t=t.filter(s=>s!==D.tag));let i="";return t.forEach(s=>{var r;((r=n[s])!==null&&r!==void 0?r:[]).forEach(({value:a,include:l})=>{l&&(i+=a)})}),e+i}function od(n,e){const t=ko(n,e).reverse(),i=ph(e),s=t.map((o,a)=>{var l;const c=sd(o,[D.nthchild],i&&a===0?Xe.NONE:Xe.CHILD);return((l=c.selectors.nthchild)!==null&&l!==void 0?l:[]).forEach(u=>{u.include=!0}),c});return[i?"":e?":scope":":root",...s.map(rd)].join("")}function ad(n,e){return n.map(t=>od(t,e)).join(Ro)}var ld=function(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t};function Mo(n,e={}){const t=Object.assign(Object.assign({},e),{maxResults:1});return cd(n,t).next().value}function*cd(n,e={}){var t;const i=nd(n),s=hh(i[0],e),r=(t=s.root)!==null&&t!==void 0?t:ii(i[0]);let o=0;for(const l of td({elements:i,options:s,root:r,rootSelector:""}))if(yield l,o++,o>=s.maxResults)return;if(i.length>1){const{maxResults:l}=e,c=ld(e,["maxResults"]);if(yield i.map(u=>Mo(u,c)).join(Ro),o++,o>=s.maxResults)return}const a=e.root!==void 0;yield ad(i,s.useScope||a?r:void 0)}function si(n,e){return n.querySelectorAll(`#${CSS.escape(e)}`).length===1}function ud(n){const e=n.getAttribute("id");if(e&&si(n.ownerDocument,e))return`#${CSS.escape(e)}`;const t=n.parentElement,i=n.tagName.toLowerCase();if(!t)return i;const s=Array.from(t.children);for(const r of n.classList){const o=`.${CSS.escape(r)}`;if(s.filter(a=>a.matches(o)).length===1)return o}return s.filter(r=>r.tagName===n.tagName).length===1?i:`${i}:nth-child(${s.indexOf(n)+1})`}function _o(n,e){const t=[];let i=n;for(;i&&i!==e;){const s=ud(i);if(t.unshift(s),s.startsWith("#"))return t;i=i.parentElement}return i===e?t:void 0}function hd(n){if(!n)return null;const e=n.getAttribute("id");if(e&&si(n.ownerDocument,e))return`#${CSS.escape(e)}`;const t=n.ownerDocument.documentElement,i=_o(n,t)??[];return i.length>0&&i[0].startsWith("#")?i.join(" > "):[t.tagName.toLowerCase(),...i].join(" > ")}function zt(n,e,t){const i=n.getAttribute("id");if(i&&(!e||si(n.ownerDocument,i)))return`#${CSS.escape(i)}`;if(!e)return Mo(n,{selectors:["id","class","tag","nthchild"]})??void 0;if(n===e)return t??void 0;const s=_o(n,e);if(!(!s||s.length===0))return s[0].startsWith("#")?s.join(" > "):t?`${t} > ${s.join(" > ")}`:s.join(" > ")}function Bo(n,e){if(!n)return;const t=e.getAttribute("id");return!!t&&n===`#${CSS.escape(t)}`?n:io(n)}const dd=3;function fd(n,e){let t=0;for(const i of Array.from(n.childNodes)){if(i===e)return t;i.nodeType===dd&&t++}return t}function Cs(n,e,t,i,s){const r=n.parentElement;if(!r)return;const o=s&&r===s.el?s.selector:zt(r,t,i);if(o)return{cssSelector:o,textNodeIndex:fd(r,n),charOffset:e}}function gd(n,e,t,i){const s=Cs(...n.first,e,t,i);if(!s)return;const r=Cs(...n.last,e,t,i);return r?{start:s,end:r}:{start:s}}function pd(n){const e=Nl(n);return e.status===ie.SUCCESS?e.fragment:void 0}const Uo="leaf-text";function ks(n){if(n===!0)return e=>e.length>0;if(Array.isArray(n)&&n.length>0){const e=new Set(n.filter(t=>t!==Uo));return t=>t.some(i=>e.has(i))}return null}function Rs(n){return n===!0||Array.isArray(n)&&n.includes(Uo)}function md(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function Sd(n){return md(n)?{predicate:ks(n.roles),leafText:Rs(n.roles),domRange:!!n.domRange,textFragment:!!n.textFragment}:{predicate:ks(n),leafText:Rs(n),domRange:!1,textFragment:!1}}class yd{claimed=new Set;counters=new Map;allocate(e,t){for(;;){const i=(this.counters.get(e)??0)+1;this.counters.set(e,i);const s=`${e}${i}`;if(!(t(s)||this.claimed.has(s)))return this.claimed.add(s),s}}claim(e){return this.claimed.has(e)?!1:(this.claimed.add(e),!0)}}function vd(n){for(let e=n.parentElement;e;e=e.parentElement)if(qe(e).includes("endnotes"))return!0;return!1}function bd(n,e,t){const i=[],s=(r,o)=>{const a=r.getAttribute("id");if(a&&!e.has(a)&&e.set(a,r),o=o||r.getAttribute("aria-hidden")==="true"||r.hasAttribute("hidden"),!o&&r.tagName.toLowerCase()==="a"&&qe(r).includes("noteref")){const c=r.getAttribute("href")??"";c.startsWith("#")&&i.push({id:c.slice(1),ref:r})}for(let l=r.firstElementChild;l;l=l.nextElementSibling)s(l,o)};s(n,!1);for(const r of i){const o=e.get(r.id);o&&(wo(o,r.ref)||vd(o)||t.add(o))}}function wd(n,e,t,i){const s={role:i},r=(e.getAttribute("title")??"").trim();r?s.text={plain:r,ssml:"",language:""}:t&&(s.text={plain:t.plain??"",ssml:t.ssml??"",language:t.language},ei.add(s));const o=!!(s.text&&!Je(s.text)),a=!n.xmlParsed&&(th(e)||o&&e.firstChild!==null);if(!o&&!a){const u=Bt(e);u&&(s.text={plain:u,ssml:"",language:""})}const l=zt(e,n.selectorRoot,n.selectorRootAnchor),c=Bo(l,e);return c&&(s.textref=c),n.placeholder(e,"pagebreak",s),a}function xd(n,e,t){const i={role:t},s=Bt(e);s&&(i.text={plain:s,ssml:"",language:""});const r=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&r.startsWith("#")&&(o=r.slice(1)),r.startsWith("#")){const a=r.slice(1),l=n.ids.get(a);if(l&&!wo(l,e)&&n.noterefDepth<3){const c=n.spawnChild(l);c.convert(l);const u=c.result();u.length>0&&(i.children=u.map(h=>{const d=fo(h);return delete d.id,d}))}}!i.children&&r&&(i.children=[{textref:r}]),n.placeholder(e,"noteref",i,o||void 0)}function Ed(n,e,t,i){const s={};if(t.length>0&&(s.role=t),i){s.text={plain:i.plain??"",ssml:i.ssml??"",language:i.language},ei.add(s);const o=zt(e,n.selectorRoot,n.selectorRootAnchor);o&&uo.set(s,o)}else{const o=Bt(e);o&&(s.text={plain:o,ssml:"",language:""})}const r=e.getAttribute("href");r&&(s.textref=r),n.placeholder(e,t[0]??"link",s)}const Cd=3,kd=1,Rd=new Set(["summary","dfn","span"]);function As(n,e){return Rd.has(n)&&e.length>0?!0:!ih(n)}class Dt{xmlParsed;ids=new Map;suppressed=new Set;idAlloc=new yd;noterefDepth=0;allowNode=null;selectorPredicate=null;domRangeEnabled=!1;textFragmentEnabled=!1;leafTextEnabled=!1;docRoot=null;selectorRoot=null;selectorRootAnchor=null;root=new ht;current=this.root;foldedCaptions=new Set;segments=[];textAcc="";currentCtx={lang:"",tag:""};flowEndsWithSpace=!0;pendingChildren=[];flowFirstNode=null;flowFirstOffset=0;flowLastNode=null;flowLastOffset=0;lastFlowRange=null;lastFlowText=null;constructor(e){this.xmlParsed=e}spawnChild(e,t=1){const i=new Dt(this.xmlParsed);return i.ids=this.ids,i.suppressed=this.suppressed,i.idAlloc=this.idAlloc,i.noterefDepth=this.noterefDepth+t,i.allowNode=e,i.docRoot=this.docRoot,i.selectorRoot=this.selectorRoot,i.selectorRootAnchor=this.selectorRootAnchor,i.selectorPredicate=this.selectorPredicate,i.domRangeEnabled=this.domRangeEnabled,i.textFragmentEnabled=this.textFragmentEnabled,i.leafTextEnabled=this.leafTextEnabled,i}prescan(e){bd(e,this.ids,this.suppressed)}convert(e){this.prescan(e),this.walk(e)}convertChildren(e){this.prescan(e);for(let t=e.firstChild;t;t=t.nextSibling)this.walk(t);this.flushText()}result(){const e=this.root.finalize();return!e.children||e.children.length===0?Tn(e)?[]:[Nn(e)]:e.children.map(Nn)}descend(e,t){const i=new ht;i.el=e,i.noText=this.foldedCaptions.has(e)||(!bo(e)||t.includes("caption"))&&this.current.noText,this.current.children.push(i),this.current=i}appendChild(e){e.noText=this.current.noText,this.current.children.push(e)}walk(e){if(e.nodeType===Cd){this.text(e);return}if(e.nodeType!==kd)return;const t=e,i=this.current,s=this.head(t);if(!s)for(let r=t.firstChild;r;r=r.nextSibling)this.walk(r);this.tail(t,s,i)}head(e){const t=e.tagName.toLowerCase();if(Zu.has(t)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[i,s]=Ju(e);if(!s&&e!==this.allowNode)return!0;const r=qe(e);if((t==="img"||t==="svg")&&(r.includes("presentation")||i===null&&e.hasAttribute("alt")&&e.getAttribute("alt").trim()===""))return!0;if(t==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(r.includes("pagebreak"))return!wd(this,e,i,r);if(t==="a"&&r.includes("noteref")&&e.getAttribute("href"))return xd(this,e,r),!0;if(t==="a"&&e.getAttribute("href"))return Ed(this,e,r,i),!0;if(t==="img"){const l={role:r},c=e.getAttribute("src");return c&&(l.imgref=c),i&&(l.description=i.plain),this.placeholder(e,"image",l),!0}if(t==="audio"||t==="video"){const l={role:r};let c=e.getAttribute("src");if(!c){const u=e.querySelector(":scope > source[src]");u&&(c=u.getAttribute("src"))}return t==="audio"?c&&(l.audioref=c):c&&(l.videoref=c),i&&(l.description=i.plain),this.placeholder(e,t,l),!0}if(r.includes("image")||r.includes("math")){const l={role:r};return i&&(l.description=i.plain),this.placeholder(e,r.includes("math")?"math":"image",l),!0}if(!As(t,r))return!1;this.flushText(),this.descend(e,r);const o=this.current.object;if(r.length>0&&(o.role=r),i)o.description=i.plain,r.includes("figure")&&(this.current.noText=!0);else if(r.includes("figure")){const l=this.implicitCaptionOf(e);if(l){const c=vs(l);c&&(o.description=c,this.current.noText=!0)}}else if(r.includes("table")){const l=this.implicitCaptionOf(e);if(l){const c=vs(l);c&&(o.description=c,this.foldedCaptions.add(l))}}const a=e.getAttribute("id");return a&&(o.id=a),!1}implicitCaptionOf(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling)if(qe(t).includes("caption")&&!t.getAttribute("aria-labelledby"))return t;return null}tail(e,t,i){if(t)return;const s=e.tagName.toLowerCase(),r=qe(e);if(As(s,r)){this.flushText();const o=this.leafTextEnabled&&r.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(r)||o)&&this.applyTextref(e),this.current=i}}applyTextref(e){const t=this.current.object,i=zt(e,this.selectorRoot,this.selectorRootAnchor);if(t.textref=Bo(i,e),this.domRangeEnabled&&this.lastFlowRange){const s=i?{el:e,selector:i}:void 0,r=gd(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,s);r&&(t.textref=ro({...r,container:i}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const s=this.docRoot.createRange();s.setStart(...this.lastFlowRange.first),s.setEnd(...this.lastFlowRange.last);const r=pd(s);r&&(t.textref=`${t.textref??"#"}${ao(r)}`)}}text(e){if(this.current.noText)return;const t=e.nodeValue??"";if(/^\s*$/.test(t)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=Ce(t,this.flowEndsWithSpace),this.updateFlowSpace());return}const i=this.textContext(e);if(Ca(i,this.currentCtx)||(this.closeSegment(),this.currentCtx=i),this.textAcc+=Ce(t,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const s=e;this.flowFirstNode===null&&(this.flowFirstNode=s,this.flowFirstOffset=t.search(/\S/)),this.flowLastNode=s,this.flowLastOffset=t.length-(t.match(/\s+$/)?.[0].length??0)}}textContext(e){const t={lang:bs(e.parentElement),tag:""};for(let i=e.parentElement;i&&i!==this.current.el;i=i.parentElement){const[s,r]=Qu(i.tagName.toLowerCase());if(s&&s!=="break"){t.tag=s,t.attrs=r;break}}return t}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(e,t,i,s){if(Tn(i))return;const r=new ht;if(r.el=e,r.object=i,this.current.noText){this.appendChild(r);return}this.closeSegment(),this.pendingChildren.push(r),this.segments.push({kind:"placeholder",tag:t,child:r,candidateID:s??e.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let e=this.segments;const t=this.pendingChildren,i=this.flowFirstNode,s=this.flowFirstOffset,r=this.flowLastNode,o=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,e.length===0)return;for(;e.length>0;){const S=e[0];if(S.kind==="break"){e=e.slice(1);continue}if(S.kind==="text"){const y=S.text.replace(/^\s+/,"");if(y===""){e=e.slice(1);continue}e=[{...S,text:y},...e.slice(1)]}break}for(;e.length>0;){const S=e[e.length-1];if(S.kind==="break"){e=e.slice(0,-1);continue}if(S.kind==="text"){const y=S.text.replace(/\s+$/,"");if(y===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...S,text:y}]}break}if(!e.some(S=>S.kind==="text"&&S.text.trim()!=="")){for(const S of t)this.appendChild(S);return}const l=[];for(const S of e)if(S.kind==="text"&&S.text.trim()!==""){const y=S.ctx.lang;l.includes(y)||l.push(y)}let c=bs(this.current.el??null);l.length===1&&l[0]!==""&&(c=l[0]);let u=!1;for(const S of e)if(S.kind!=="text"||S.ctx.tag!==""||S.ctx.lang!==c){u=!0;break}if(u&&c===""&&(c="en"),u)for(const S of e){if(S.kind!=="placeholder")continue;let y=S.candidateID;(!y||!this.idAlloc.claim(y))&&(y=this.idAlloc.allocate(S.tag,b=>this.ids.has(b))),S.child.object.id=y}let h="",d=!1,f=!1,g=!1,p=!1;for(const S of e)if(S.kind==="text"){const y=S.text.startsWith(" "),b=S.text.replace(/^ +| +$/g,"");if(b===""){p=!0;continue}let C=!1;if(h.length>0){const R=d||p||y;f?C=!0:g?C=R&&!Oe(b):C=R}C&&(h+=" "),h+=b,d=S.text.endsWith(" "),f=!1,g=!1,p=!1}else S.kind==="break"?f=!0:S.kind==="placeholder"&&(g=!0);const m=e.some(S=>S.kind==="placeholder");this.lastFlowText=h.trim();const v={plain:u&&!m?"":h.trim(),ssml:"",language:c};if(u){let S="";for(const y of e)if(y.kind==="text"){let b=y.ctx.tag,C=y.ctx.attrs;if(y.ctx.lang!==c&&y.ctx.lang!==""&&(b="lang",C=void 0),b){S+=`<${b}`;for(const[R,A]of Object.entries(C??{}))S+=` ${R}="${jt(A)}"`;y.ctx.lang!==c&&y.ctx.lang!==""&&(S+=` xml:lang="${jt(y.ctx.lang)}"`),S+=`>${X(y.text)}</${b}>`}else S+=X(y.text)}else y.kind==="break"?S+="<break/>":y.kind==="placeholder"&&(S+=`<readium:${y.tag} id="${jt(y.child.object.id)}" />`);v.ssml=S}const w=new ht;w.object={text:v};for(const S of t)w.children.push(S);this.appendChild(w),i&&r&&(this.lastFlowRange={first:[i,s],last:[r,o]})}}const Ad=/<body[\s>]/i;function zo(n,e,t){const{predicate:i,leafText:s,domRange:r,textFragment:o}=Sd(t?.textrefs);if(typeof n!="string"){const h=e??(n.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),d=new Dt(h==="application/xhtml+xml");return d.selectorPredicate=i,d.leafTextEnabled=s,d.domRangeEnabled=r,d.textFragmentEnabled=o,d.docRoot=n.ownerDocument,d.selectorRoot=n,d.selectorRootAnchor=hd(n),d.convert(n),d.result()}const a=e??sh(n),l=new DOMParser().parseFromString(n,a),c=new Dt(a==="application/xhtml+xml");c.selectorPredicate=i,c.leafTextEnabled=s,c.textFragmentEnabled=o,c.docRoot=l;const u=l.querySelector("body");return u&&!Ad.test(n)?c.convertChildren(u):c.convert(u??l.documentElement),c.result()}function Od(n,e,t){return{guided:zo(n,e,t)}}exports.BUILTIN_DECORATION_TYPES=Ar;exports.BooleanPreference=_r;exports.DecorationController=Ir;exports.DecorationLayout=Cr;exports.DecorationStyleType=E;exports.DecorationWidth=Er;exports.Decorator=Rr;exports.DirectCommsChannel=Dr;exports.DirectCommsFrame=Pr;exports.DirectCommsHost=Fr;exports.EnumPreference=ye;exports.FallbackEngineProvider=rl;exports.FallbackSpeechEngine=Ks;exports.Locator=Vn;exports.LocatorLocations=te;exports.LocatorText=zn;exports.Preference=Qe;exports.RangePreference=Ve;exports.ReadiumSpeechDecorationController=$r;exports.ReadiumSpeechNavigator=Mu;exports.ReadiumSpeechProviderRegistry=mc;exports.SpeechDefaults=Mr;exports.SpeechPreferences=Re;exports.SpeechPreferencesEditor=vn;exports.SpeechServerAudioDecodeError=Mn;exports.SpeechServerEngine=qs;exports.SpeechServerEngineProvider=nl;exports.SpeechServerError=ke;exports.SpeechServerNetworkError=_n;exports.SpeechServerStallError=$n;exports.SpeechSettings=wn;exports.StringArrayPreference=yn;exports.WebSpeechEngine=cn;exports.WebSpeechEngineProvider=ja;exports.WebSpeechVoiceManager=T;exports.blockLevelRoles=Yr;exports.chineseVariantMap=xe;exports.chunkPlainText=Us;exports.chunkSsmlText=zs;exports.contextualizationShapesAtVerbosity=jr;exports.contextualizedAtVerbosity=Vr;exports.createLocator=Lr;exports.decodeCssSelectorFragment=so;exports.decodeDomRangeFragment=oo;exports.decodeTextref=On;exports.decorationsEqual=Tr;exports.defaultContextualizations=Xn;exports.encodeCssSelectorFragment=io;exports.encodeDomRangeFragment=ro;exports.extractUtterances=Lu;exports.isRecoverableFailure=Ws;exports.makeGnd=Od;exports.mapServerVoice=Ln;exports.mimeTypeForFormat=Vs;exports.parseMarkup=zo;exports.resolveBoundaryLocate=Wr;exports.resolveDecorationForWire=Sn;exports.resolveUtteranceLocate=Kr;exports.selectBitrate=Hs;exports.selectFormat=js;exports.setupDecorations=pc;exports.shapeableRoles=yc;exports.skippableRoles=nu;exports.skippedAtVerbosity=zr;exports.supportsDecorationStyle=Or;exports.toSpeechServerError=be;
|