@readium/speech 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +13 -11
  2. package/build/gnd/converter.d.ts +3 -0
  3. package/build/gnd/domRangeGenerator.d.ts +1 -1
  4. package/build/gnd/object.d.ts +4 -0
  5. package/build/gnd/options.d.ts +2 -0
  6. package/build/gnd/selectorGenerator.d.ts +3 -2
  7. package/build/gnd/textrefFragment.d.ts +2 -0
  8. package/build/index.cjs +17 -43
  9. package/build/index.js +4987 -5320
  10. package/build/preferences/SpeechDefaults.d.ts +4 -1
  11. package/build/preferences/SpeechPreferences.d.ts +3 -2
  12. package/build/preferences/SpeechPreferencesEditor.d.ts +3 -1
  13. package/build/preferences/SpeechSettings.d.ts +3 -1
  14. package/build/preferences/constraints.d.ts +3 -1
  15. package/build/preferences/index.d.ts +2 -1
  16. package/build/speechNavigator.d.ts +8 -0
  17. package/build/utils/text.d.ts +3 -0
  18. package/build/utterance.d.ts +6 -1
  19. package/build/utterances/applySubstitutions.d.ts +3 -0
  20. package/build/utterances/boundaryLocate.d.ts +11 -0
  21. package/build/utterances/builtInSubstitutions.d.ts +2 -0
  22. package/build/utterances/builtInSuppressions.d.ts +1 -0
  23. package/build/utterances/contextualization.d.ts +15 -0
  24. package/build/utterances/extractUtterances.d.ts +3 -1
  25. package/build/utterances/index.d.ts +4 -1
  26. package/build/utterances/locate.d.ts +22 -0
  27. package/build/utterances/mergeUtterances.d.ts +17 -0
  28. package/build/utterances/sentenceBoundaryMerge.d.ts +7 -0
  29. package/build/utterances/sentenceReconstruction.d.ts +6 -0
  30. package/build/utterances/sentenceSegmenter.d.ts +8 -0
  31. package/build/utterances/splitSsmlAtSentences.d.ts +2 -0
  32. package/build/utterances/text.d.ts +29 -0
  33. package/build/utterances/types.d.ts +18 -2
  34. package/build/utterances/utteranceLocate.d.ts +4 -0
  35. package/build/utterances/utteranceOutput.d.ts +6 -0
  36. package/build/utterances/walk.d.ts +4 -0
  37. package/build/utterances/walkContext.d.ts +40 -0
  38. package/package.json +4 -5
package/build/index.cjs CHANGED
@@ -1,50 +1,24 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=t=>{if(!t)return["",void 0];const e=t.replace(/_/g,"-");try{const n=new Intl.Locale(e);return[n.language.toLowerCase(),n.region?.toUpperCase()]}catch{const n=e.split("-");return[n[0].toLowerCase(),n[1]?.toUpperCase()]}},ne={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},係越中文聲。"}},sn=new Map,yo=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 bo(t){try{const e=t.split("-")[0],n=yo[`../../json/${e}.json`];if(!n)throw new Error(`No voice data found for language: ${t}`);const i=(await n()).default;return{...i,voices:i.voices.map(wo)}}catch(e){return console.warn(`Failed to load voice data for ${t}:`,e),{language:t,defaultRegion:"",testUtterance:"",voices:[]}}}function $r(t){return sn.has(t)||sn.set(t,bo(t)),sn.get(t)}const So=["veryLow","low","normal","high","veryHigh"],vo=["android","apple"],wo=t=>({...t,quality:t.quality?.filter(e=>So.includes(e)),localizedName:t.localizedName&&vo.includes(t.localizedName)?t.localizedName:void 0}),Pe={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"},J=t=>{if(!t)return"";let e=t.toLowerCase().replace(/_/g,"-");if(/\w{2,3}-\w{2,3}/.test(e)){const[n,r]=e.split("-");e=`${n.toLowerCase()}-${r.toUpperCase()}`}return Pe[e]||e},On=async t=>{if(!t)return[];try{const e=J(t);try{const r=await $r(e);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for ${e}:`,r)}const[n]=q(e);if(n!==e)try{const r=await $r(n);if(r?.voices?.length)return r.voices}catch(r){console.warn(`Failed to load voices for base language ${n}:`,r)}return[]}catch(e){return console.error(`Error in getVoices for ${t}:`,e),[]}},An=(t,e)=>{try{return new Intl.DisplayNames(e?[e]:[],{type:"language",languageDisplay:"standard"}).of(t)||t.toUpperCase()}catch{return t.toUpperCase()}},_r=t=>{if(!t)return"";try{const e=J(t),n=ne[e];if(n?.testUtterance)return n.testUtterance;if(e in Pe){const i=Pe[e];if(i&&ne[i]?.testUtterance)return ne[i].testUtterance}const[r]=q(e);return r!==e&&ne[r]?.testUtterance?ne[r].testUtterance:""}catch(e){return console.error(`Error in getTestUtterance for ${t}:`,e),""}},Wt=t=>{if(!t)return"";try{const e=J(t),n=ne[e];if(n?.defaultRegion)return`${e}-${n.defaultRegion}`;if(e in Pe){const i=Pe[e];if(i){const s=ne[i];if(s?.defaultRegion)return`${i}-${s.defaultRegion}`}}const[r]=q(e);if(r!==e){const i=ne[r];if(i?.defaultRegion)return`${r}-${i.defaultRegion}`}return""}catch(e){return console.error(`Failed to get default region for ${t}:`,e),""}},Gt=t=>{if(!t?.length)return[];const e=new Set,n=new Map,r=new Map;for(const[i,s]of t.entries()){if(!s)continue;const o=J(s),[a,c]=q(o);c&&(e.add(c),r.has(c)||r.set(c,i)),n.has(a)||n.set(a,new Set),c&&n.get(a).add(c)}return Array.from(n.entries()).map(([i,s])=>{const o=new Set(ne[i]?.availableRegions||[]),a=Array.from(s),c=Array.from(e).filter(u=>o.has(u)&&!a.includes(u)),l=Array.from(new Set([...a,...c])).sort((u,h)=>{const d=r.get(u)??Number.MAX_SAFE_INTEGER,g=r.get(h)??Number.MAX_SAFE_INTEGER;return d-g});if(l.length===0){const u=Wt(i),[,h]=q(u);h&&l.push(h)}return{baseLang:i,regions:l}})},Le=async t=>{const e=new Map;for(const r of t){if(r.source!=="json")continue;const[i]=q(r.language);e.has(i)||e.set(i,[]),e.get(i).push(r)}const n=new Map;for(const[r,i]of e.entries()){const s=new Map,o=await On(r),a=new Map;o.forEach((c,l)=>{a.set(c.name.toLowerCase(),l),c.altNames?.forEach(u=>{a.set(u.toLowerCase(),l)})});for(const c of i){const l=c.name.toLowerCase(),u=a.get(l);u!==void 0&&s.set(c.name,u)}s.size>0&&n.set(r,s)}return n},xo={veryLow:1,low:2,normal:3,high:4,veryHigh:5},Nt=t=>t?xo[t]??0:0,pe=(t,e,n,r)=>{const i=Nt(t.quality),s=Nt(e.quality);if(n&&r&&t.source==="json"&&e.source==="json"){const o=n.get(r);if(o){const a=o.get(t.name),c=o.get(e.name);if(a!==void 0&&c!==void 0)return a-c}}return s!==i?s-i:t.name.localeCompare(e.name)},Kt=(t,e)=>{const n=new Map(e.map(s=>[s.baseLang,s])),r=new Map,i=[];for(const s of t){const[o]=q(s.language);n.get(o)?(r.has(o)||r.set(o,[]),r.get(o).push(s)):i.push(s)}return{voicesByLang:r,otherLangVoices:i}},rs=(t,e,n,r)=>{const[,i]=q(t.language),[,s]=q(e.language),o=i&&n.regions.includes(i),a=s&&n.regions.includes(s);if(o&&a){const d=n.regions.indexOf(i),g=n.regions.indexOf(s);return d===g?pe(t,e,r,n.baseLang):d-g}if(o)return-1;if(a)return 1;const c=Wt(n.baseLang),[,l]=q(c),u=!!l&&i===l,h=!!l&&s===l;if(u&&!h)return-1;if(!u&&h)return 1;if(i&&s){const d=i.localeCompare(s);return d!==0?d:pe(t,e,r,n.baseLang)}return i?-1:s?1:pe(t,e,r,n.baseLang)},Eo=async(t,e,n)=>{const r=n??await Le(t);t.sort((i,s)=>rs(i,s,e,r))},is=(t,e,n)=>{const[r]=q(t.language),[i]=q(e.language),s=An(r).toLowerCase(),o=An(i).toLowerCase(),a=s.localeCompare(o);if(a!==0)return a;if(r===i){const c=Wt(r),[,l]=q(t.language),[,u]=q(e.language),h=c&&l===c.split("-")[1],d=c&&u===c.split("-")[1];if(h&&!d)return-1;if(!h&&d)return 1;if(l&&u){const g=l.localeCompare(u);if(g!==0)return g}return l&&!u?-1:!l&&u?1:pe(t,e,n,r)}return pe(t,e,n,r)},Tn=async(t,e)=>{const n=e??await Le(t);t.sort((r,i)=>is(r,i,n))},Co=async(t,e)=>{if(!e?.length)return[];const n=Gt(t||[]),{voicesByLang:r,otherLangVoices:i}=Kt(e,n),s=await Le(e),o=[];for(const a of n){const c=r.get(a.baseLang);c&&(await Eo(c,a,s),o.push(...c))}return await Tn(i,s),o.push(...i),o},ko=async(t,e)=>{if(!e.length)return null;const[n]=Gt([t]),{voicesByLang:r,otherLangVoices:i}=Kt(e,[n]),s=r.get(n.baseLang),o=s?.length?s:i,a=await Le(e),c=s?.length?(l,u)=>rs(l,u,n,a):(l,u)=>is(l,u,a);return o.reduce((l,u)=>c(u,l)<0?u:l)},Oo=[{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}],Ao={voices:Oo},To=[{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}],Ro={voices:To},No=Ao,Do=Ro,Rn=(t,e)=>No.voices.some(n=>t.includes(n.name)||e&&n.nativeID?.some(r=>e.includes(r))||n.altNames?.some(r=>t.includes(r))),Nn=(t,e)=>Do.voices.some(n=>t.includes(n.name))||e==="veryLow",Br=t=>t?.length?t.filter(e=>!(e.isNovelty||Rn(e.name,e.voiceURI))):[],qr=t=>t?.length?t.filter(e=>!Nn(e.name,e.quality)):[],Fo={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"}},Io={quality:Fo},Dn={apple:Io.quality},Po=(t,e,n)=>{if(!t)return;const r=Array.isArray(n)?n:n?[n]:[];for(const i of r)if(i&&Dn[i]){const s=Dn[i],o=q(e)[0],a=s[e]||s[o];if(a){const c=t.toLowerCase(),{normal:l,high:u}=a;if(u&&c.includes(u.toLowerCase()))return"high";if(l&&c.includes(l.toLowerCase()))return"normal"}}},Lo=(t,e)=>{const n=Dn[e];if(n)for(const[r,{high:i,normal:s}]of Object.entries(n)){const o=i&&t.some(c=>c.includes(i)),a=s&&t.some(c=>c.includes(s));if(o&&a)return r}},$o={low:{values:["super-compact","compact"],quality:"low"},normal:{values:["enhanced"],quality:"normal"},high:{values:["premium"],quality:"high"}},Ur=t=>{if(!t)return;const n=t.toLowerCase().split(/[._-]/);for(const r of Object.values($o))if(r.values.some(i=>n.includes(i)))return r.quality};function _o(t,e){if(t.name===t.originalName)return t;if(e.name===e.originalName)return e;const n=[t.originalName,...t.altNames||[]],r=[e.originalName,...e.altNames||[]],i=n.findIndex(o=>r.includes(o)),s=r.findIndex(o=>n.includes(o));return i===-1&&s===-1||i!==-1&&(s===-1||i<=s)?t:e}function Bo(t,e){if(!t.altNames&&!e.altNames)return!1;const n=t.originalName,r=e.originalName,i=t.altNames||[],s=e.altNames||[];return s.includes(n)||i.includes(r)?!0:i.filter(a=>s.includes(a)).length>0}class P{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(P.instance?.isInitialized){const n=P.instance;return e?.languages&&e.languages.length>0&&await n.broadenLanguages(e.languages),n}return P.initializationPromise||(P.initializationPromise=(async()=>{try{const n=new P;P.instance=n,n.browserVoices=await n.getBrowserVoices(e?.maxTimeout,e?.interval),n.updateSystemLocale(n.browserVoices);let r=n.browserVoices;return e?.languages&&e.languages.length>0?(r=n.filterBrowserVoicesByLanguages(n.browserVoices,e.languages),n.scopedLanguages=P.toBaseLangSet(e.languages)):n.scopedLanguages=null,n.voices=await n.parseToReadiumSpeechVoices(r),n.isInitialized=!0,n}catch(n){throw P.initializationPromise=null,console.error("Failed to initialize WebSpeechVoiceManager:",n),n}})()),P.initializationPromise}filterBrowserVoicesByLanguages(e,n){if(!n?.length)return e;const r=P.toBaseLangSet(n);return e.filter(i=>{if(!i?.lang)return!1;const s=J(i.lang),[o]=P.extractLangRegionFromBCP47(s);return r.has(o)})}static toBaseLangSet(e){return new Set(e.map(n=>{const r=J(n),[i]=P.extractLangRegionFromBCP47(r);return i}))}async broadenLanguages(e){if(this.scopedLanguages===null)return;const r=[...P.toBaseLangSet(e)].filter(a=>!this.scopedLanguages.has(a));if(r.length===0)return;const i=r.filter(a=>this.broadenPromises.has(a)),s=r.filter(a=>!this.broadenPromises.has(a));let o;s.length>0&&(o=(async()=>{const a=this.filterBrowserVoicesByLanguages(this.browserVoices,s),c=await this.parseToReadiumSpeechVoices(a);this.voices=[...this.voices,...c],s.forEach(l=>this.scopedLanguages.add(l)),s.forEach(l=>this.broadenPromises.delete(l))})(),s.forEach(a=>this.broadenPromises.set(a,o))),await Promise.all([...o?[o]:[],...i.map(a=>this.broadenPromises.get(a))])}static extractLangRegionFromBCP47(e){return q(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 n=new Map;for(const r of e){if(!r?.name||!r?.lang)continue;const i=`${r.lang.toLowerCase()}_${this.normalizeVoiceName(r.name)}`;n.set(i,(n.get(i)||0)+1)}return n}updateSystemLocale(e){if(!e?.length)return;const n=e.map(i=>i.name),r=Lo(n,"apple");r&&(this.systemLocale=r)}inferVoiceQuality(e,n,r){const i=e.voiceURI?Ur(e.voiceURI):void 0;if(i)return i;if(n?.nativeID&&Array.isArray(n.nativeID))for(const s of n.nativeID){const o=Ur(s);if(o)return o}if(n?.localizedName&&e.voiceURI&&e.lang){const s=Po(e.voiceURI,this.systemLocale,n.localizedName);if(s)return s}if(n?.quality&&n.quality.length>0){const s=Math.min(r-1,n.quality.length-1),o=n.quality[s];if(o)return o}return null}findMatchingJsonVoice(e,n){return e.find(r=>this.normalizeVoiceName(r.name)===n||r.altNames?.some(i=>this.normalizeVoiceName(i)===n))}removeDuplicates(e){const n=new Map;for(const r of e){const i=`${r.language.toLowerCase()}_${this.normalizeVoiceName(r.name)}`,s=n.get(i);if(!s)n.set(i,r);else if(Bo(r,s)){const o=_o(r,s);n.set(i,o)}else{const o=Nt(s.quality);Nt(r.quality)>=o&&n.set(i,r)}}return Array.from(n.values())}getTestUtterance(e){if(!e)return"";const n=_r(e);if(n)return n;const[r]=P.extractLangRegionFromBCP47(e);if(r&&r!==e){const i=_r(r);if(i)return i}return""}getVoices(e={}){if(!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");return this.filterVoices(e,[...this.voices])}getLanguages(e,n,r){if(!r&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=r??this.voices,s=n?this.filterVoices(n,i):i,o=[],a=new Set;for(const c of s){const u=J(c.language).split("-")[0];if(!a.has(u)){const h=An(u,e),d=s.filter(g=>J(g.language).split("-")[0]===u).length;o.push({code:u,label:h,count:d}),a.add(u)}}return r?o:o.sort((c,l)=>c.label.localeCompare(l.label))}getRegions(e,n,r){if(!r&&!this.isInitialized)throw new Error("WebSpeechVoiceManager not initialized. Call initialize() first.");const i=r??this.voices,s=n?this.filterVoices(n,i):i,o=[],a=new Set,c=new Map;for(const l of s){const[,u]=P.extractLangRegionFromBCP47(l.language);u&&c.set(u,(c.get(u)||0)+1)}for(const l of s){const[,u]=P.extractLangRegionFromBCP47(l.language);if(u&&!a.has(u)){let h=l.language;try{const d=e||navigator.language;h=new Intl.DisplayNames([d],{type:"region"}).of(u)||l.language}catch(d){console.warn(`Failed to get display name for region ${u}`,d)}o.push({code:u,label:h,count:c.get(u)||0}),a.add(u)}}return r?o:o.sort((l,u)=>l.label.localeCompare(u.label))}async getDefaultVoice(e,n){if(!e)return null;const r=Array.isArray(e)?e:[e];let i=n||this.getVoices({languages:r});return i.length?(i=await this.sortVoicesByRegions(r,i),i[0]):null}getBrowserVoices(e=1e4,n=10){const r=()=>window.speechSynthesis?.getVoices()||[];if(!window.speechSynthesis)return Promise.resolve([]);const i=r();return Array.isArray(i)&&i.length?Promise.resolve(i):new Promise((s,o)=>{let a=Math.floor(e/n),c=!1;const l=()=>{if(c)return;c=!0;const u=()=>{if(a<1)return s([]);--a;const h=r();if(Array.isArray(h)&&h.length)return s(h);setTimeout(u,n)};setTimeout(u,n)};window.speechSynthesis.onvoiceschanged!==void 0?window.speechSynthesis.onvoiceschanged=()=>{const u=r();Array.isArray(u)&&u.length?s(u):l()}:l(),setTimeout(()=>s([]),e)})}async parseToReadiumSpeechVoices(e){const n=this.countVoiceDuplicates(e);return await Promise.all(e.filter(i=>i?.name&&i?.lang).map(async i=>{const s=J(i.lang),[o]=P.extractLangRegionFromBCP47(s),a=this.normalizeVoiceName(i.name),c=`${i.lang.toLowerCase()}_${a}`,l=n.get(c)||1;let u=await On(s);(!u||u.length===0)&&(u=await On(o));const h=this.findMatchingJsonVoice(u,a),d=this.inferVoiceQuality(i,h,l);return h?{...h,label:h.label??this.cleanVoiceName(i.name),source:"json",originalName:i.name,language:h.language??s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}:{source:"browser",label:this.cleanVoiceName(i.name),name:i.name,originalName:i.name,language:s,voiceURI:i.voiceURI,quality:d,isDefault:i.default||!1,offlineAvailability:i.localService||!1,isNovelty:Rn(i.name,i.voiceURI),isLowQuality:Nn(i.name,d)}}))}convertToSpeechSynthesisVoice(e){if(e)return this.browserVoices.find(n=>n.voiceURI===e.voiceURI||n.name===e.originalName||this.normalizeVoiceName(n.name)===this.normalizeVoiceName(e.name))}filterVoices(e,n){let r=n?[...n]:[...this.voices];const i={excludeNovelty:!0,excludeVeryLowQuality:!0,removeDuplicates:!0,...e};if(i.languages){const s=Array.isArray(i.languages)?i.languages:[i.languages];r=r.filter(o=>s.some(a=>{const c=a.toLowerCase(),l=o.language?.toLowerCase(),u=o.altLanguage?.toLowerCase();if(l===c||u===c)return!0;const[h]=c.split("-");return l&&l.startsWith(h)||u&&u.startsWith(h)}))}if(i.source&&(r=r.filter(s=>s.source===i.source)),i.gender&&(r=r.filter(s=>s.gender===i.gender)),i.quality){const s=Array.isArray(i.quality)?i.quality:[i.quality];r=r.filter(o=>o.quality&&s.includes(o.quality))}return i.offlineOnly&&(r=r.filter(s=>s.offlineAvailability===!0)),i.provider&&(r=r.filter(s=>s.provider?.toLowerCase()===i.provider?.toLowerCase())),i.excludeNovelty&&(r=Br(r)),i.excludeVeryLowQuality&&(r=qr(r)),i.removeDuplicates&&(r=this.removeDuplicates(r)),r}filterOutNoveltyVoices(e){const n=e??this.voices;return Br(n)}filterOutVeryLowQualityVoices(e){const n=e??this.voices;return qr(n)}async sortVoicesByQuality(e){const n=e||this.voices;if(!n?.length)return[];const r=await Le(n);return[...n].sort((i,s)=>pe(i,s,r))}static async sortByDefaultRegion(e,n){const r=await Le(e),i=Wt(n);e.sort((s,o)=>{const[,a]=P.extractLangRegionFromBCP47(s.language),[,c]=P.extractLangRegionFromBCP47(o.language),l=i&&a===i.split("-")[1],u=i&&c===i.split("-")[1];return l&&!u?-1:!l&&u?1:pe(s,o,r,n)})}async sortVoicesByLanguages(e,n){const r=n||this.voices;if(!r?.length)return[];if(!e?.length){const c=[...r];return await Tn(c),c}const i=Gt(e),{voicesByLang:s,otherLangVoices:o}=Kt(r,i),a=[];for(const c of i){const l=s.get(c.baseLang);l&&(await P.sortByDefaultRegion(l,c.baseLang),a.push(...l))}return await Tn(o),a.push(...o),a}async sortVoicesByRegions(e,n){return Co(e,n||this.voices)}groupVoices(e,n){const r={},i=n||this.voices;for(const s of i){let o="Unknown";switch(e){case"languages":o=P.extractLangRegionFromBCP47(s.language)[0];break;case"gender":o=s.gender||"unknown";break;case"quality":o=s.quality||"unknown";break;case"region":const[,a]=P.extractLangRegionFromBCP47(s.language);o=a||"unknown";break}r[o]||(r[o]=[]),r[o].push(s)}return r}}const qo=["webKit","moz","ms","o"],Uo=["boundary","end","error","mark","pause","resume","start"],Vo=t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`,He=(t={},e)=>Object.hasOwnProperty.call(t,e)||e in t||!!t[e],zo=t=>typeof window<"u"&&t in window,Mo=t=>{const e=Vo(t),n=qo.map(i=>`${i}${e}`),r=[t,e].concat(n).find(zo);return r&&typeof window<"u"?window[r]:void 0},jo=()=>{const t={};["speechSynthesis","speechSynthesisUtterance","speechSynthesisVoice","speechSynthesisEvent","speechSynthesisErrorEvent"].forEach(n=>{t[n]=Mo(n)}),t.onvoiceschanged=He(t.speechSynthesis,"onvoiceschanged"),t.speechSynthesisSpeaking=He(t.speechSynthesis,"speaking"),t.speechSynthesisPaused=He(t.speechSynthesis,"paused");const e=t.speechSynthesisUtterance?He(t.speechSynthesisUtterance,"prototype"):!1;return Uo.forEach(n=>{const r=`on${n}`;t[r]=e&&t.speechSynthesisUtterance?He(t.speechSynthesisUtterance.prototype,r):!1}),t},Ho=()=>{const e=typeof window<"u"&&(window.navigator||{}).userAgent||"",n=()=>/android/i.test(e),r=()=>/kaios/i.test(e),i=()=>typeof window.InstallTrigger<"u"?!0:/firefox/i.test(e),s=()=>typeof window.GestureEvent<"u"||/safari/i.test(e);return{isAndroid:n(),isFirefox:i()||r(),isSafari:s(),isKaiOS:r()}};let Jt=class{listeners=new Map;on(e,n){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(n),()=>{const r=this.listeners.get(e);if(r){const i=r.indexOf(n);i>-1&&r.splice(i,1)}}}emit(e,n){const r=this.listeners.get(e);r&&[...r].forEach(i=>{try{i(n)}catch(s){console.error(`Error in "${String(e)}" listener:`,s)}})}clear(){this.listeners.clear()}};const kt=(t,e)=>Math.min(Math.max(t,0),Math.max(e-1,0));function me(t,e,n,r){return Number.isFinite(t)?Math.max(e,Math.min(n,t)):r}function Wo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var an,Vr;function Go(){if(Vr)return an;Vr=1,an=e;function t(r){return r instanceof Buffer?Buffer.from(r):new r.constructor(r.buffer.slice(),r.byteOffset,r.length)}function e(r){if(r=r||{},r.circles)return n(r);const i=new Map;if(i.set(Date,l=>new Date(l)),i.set(Map,(l,u)=>new Map(o(Array.from(l),u))),i.set(Set,(l,u)=>new Set(o(Array.from(l),u))),r.constructorHandlers)for(const l of r.constructorHandlers)i.set(l[0],l[1]);let s=null;return r.proto?c:a;function o(l,u){const h=Object.keys(l),d=new Array(h.length);for(let g=0;g<h.length;g++){const p=h[g],m=l[p];typeof m!="object"||m===null?d[p]=m:m.constructor!==Object&&(s=i.get(m.constructor))?d[p]=s(m,u):ArrayBuffer.isView(m)?d[p]=t(m):d[p]=u(m)}return d}function a(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,a);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,a);const u={};for(const h in l){if(Object.hasOwnProperty.call(l,h)===!1)continue;const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,a):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=a(d)}return u}function c(l){if(typeof l!="object"||l===null)return l;if(Array.isArray(l))return o(l,c);if(l.constructor!==Object&&(s=i.get(l.constructor)))return s(l,c);const u={};for(const h in l){const d=l[h];typeof d!="object"||d===null?u[h]=d:d.constructor!==Object&&(s=i.get(d.constructor))?u[h]=s(d,c):ArrayBuffer.isView(d)?u[h]=t(d):u[h]=c(d)}return u}}function n(r){const i=[],s=[],o=new Map;if(o.set(Date,h=>new Date(h)),o.set(Map,(h,d)=>new Map(c(Array.from(h),d))),o.set(Set,(h,d)=>new Set(c(Array.from(h),d))),r.constructorHandlers)for(const h of r.constructorHandlers)o.set(h[0],h[1]);let a=null;return r.proto?u:l;function c(h,d){const g=Object.keys(h),p=new Array(g.length);for(let m=0;m<g.length;m++){const b=g[m],x=h[b];if(typeof x!="object"||x===null)p[b]=x;else if(x.constructor!==Object&&(a=o.get(x.constructor)))p[b]=a(x,d);else if(ArrayBuffer.isView(x))p[b]=t(x);else{const A=i.indexOf(x);A!==-1?p[b]=s[A]:p[b]=d(x)}}return p}function l(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,l);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,l);const d={};i.push(h),s.push(d);for(const g in h){if(Object.hasOwnProperty.call(h,g)===!1)continue;const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,l);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=l(p)}}return i.pop(),s.pop(),d}function u(h){if(typeof h!="object"||h===null)return h;if(Array.isArray(h))return c(h,u);if(h.constructor!==Object&&(a=o.get(h.constructor)))return a(h,u);const d={};i.push(h),s.push(d);for(const g in h){const p=h[g];if(typeof p!="object"||p===null)d[g]=p;else if(p.constructor!==Object&&(a=o.get(p.constructor)))d[g]=a(p,u);else if(ArrayBuffer.isView(p))d[g]=t(p);else{const m=i.indexOf(p);m!==-1?d[g]=s[m]:d[g]=u(p)}}return i.pop(),s.pop(),d}}return an}var Ko=Go();const ss=Wo(Ko);ss();function Fn(t){if(t==null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:!(Symbol.iterator in t)&&!(Symbol.toStringTag in t)}function Oe(t){return typeof t=="string"}function Jo(t){return Number.isFinite(t)}function xe(t){return Number.isSafeInteger(t)&&t>=0}function se(t){return t!=null}function Xo(t,e){return Fn(t)&&Oe(e)&&e in t}var Yo=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,Qo=typeof self=="object"&&self&&self.Object===Object&&self,sr=Yo||Qo||Function("return this")(),$e=sr.Symbol,as=Object.prototype,Zo=as.hasOwnProperty,el=as.toString,We=$e?$e.toStringTag:void 0;function tl(t){var e=Zo.call(t,We),n=t[We];try{t[We]=void 0;var r=!0}catch{}var i=el.call(t);return r&&(e?t[We]=n:delete t[We]),i}var nl=Object.prototype,rl=nl.toString;function il(t){return rl.call(t)}var sl="[object Null]",al="[object Undefined]",zr=$e?$e.toStringTag:void 0;function os(t){return t==null?t===void 0?al:sl:zr&&zr in Object(t)?tl(t):il(t)}function ls(t){return t!=null&&typeof t=="object"}var ol="[object Symbol]";function ll(t){return typeof t=="symbol"||ls(t)&&os(t)==ol}function cl(t,e){for(var n=-1,r=t==null?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}var ul=Array.isArray,Mr=$e?$e.prototype:void 0,jr=Mr?Mr.toString:void 0;function ar(t){if(typeof t=="string")return t;if(ul(t))return cl(t,ar)+"";if(ll(t))return jr?jr.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var hl=/\s/;function dl(t){for(var e=t.length;e--&&hl.test(t.charAt(e)););return e}var fl=/^\s+/;function gl(t){return t&&t.slice(0,dl(t)+1).replace(fl,"")}function cs(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function us(t){return t}var pl="[object AsyncFunction]",ml="[object Function]",yl="[object GeneratorFunction]",bl="[object Proxy]";function hs(t){if(!cs(t))return!1;var e=os(t);return e==ml||e==yl||e==pl||e==bl}var on=sr["__core-js_shared__"],Hr=(function(){var t=/[^.]+$/.exec(on&&on.keys&&on.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function Sl(t){return!!Hr&&Hr in t}var vl=Function.prototype,wl=vl.toString;function xl(t){if(t!=null){try{return wl.call(t)}catch{}try{return t+""}catch{}}return""}var El=/[\\^$.*+?()[\]{}|]/g,Cl=/^\[object .+?Constructor\]$/,kl=Function.prototype,Ol=Object.prototype,Al=kl.toString,Tl=Ol.hasOwnProperty,Rl=RegExp("^"+Al.call(Tl).replace(El,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Nl(t){if(!cs(t)||Sl(t))return!1;var e=hs(t)?Rl:Cl;return e.test(xl(t))}function Dl(t,e){return t?.[e]}function or(t,e){var n=Dl(t,e);return Nl(n)?n:void 0}function Fl(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var Il=800,Pl=16,Ll=Date.now;function $l(t){var e=0,n=0;return function(){var r=Ll(),i=Pl-(r-n);if(n=r,i>0){if(++e>=Il)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function _l(t){return function(){return t}}var Wr=(function(){try{var t=or(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Bl=Wr?function(t,e){return Wr(t,"toString",{configurable:!0,enumerable:!1,value:_l(e),writable:!0})}:us,ql=$l(Bl);function Ul(t,e,n,r){for(var i=t.length,s=n+-1;++s<i;)if(e(t[s],s,t))return s;return-1}function Vl(t){return t!==t}function zl(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function lr(t,e,n){return e===e?zl(t,e,n):Ul(t,Vl,n)}function Ml(t,e){var n=t==null?0:t.length;return!!n&&lr(t,e,0)>-1}function jl(t,e){return t===e||t!==t&&e!==e}var Gr=Math.max;function Hl(t,e,n){return e=Gr(e===void 0?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=Gr(r.length-e,0),o=Array(s);++i<s;)o[i]=r[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=r[i];return a[e]=n(o),Fl(t,this,a)}}function Wl(t,e){return ql(Hl(t,e,us),t+"")}var Gl=9007199254740991;function Kl(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Gl}function Jl(t){return t!=null&&Kl(t.length)&&!hs(t)}var st=or(Object,"create");function Xl(){this.__data__=st?st(null):{},this.size=0}function Yl(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",Zl=Object.prototype,ec=Zl.hasOwnProperty;function tc(t){var e=this.__data__;if(st){var n=e[t];return n===Ql?void 0:n}return ec.call(e,t)?e[t]:void 0}var nc=Object.prototype,rc=nc.hasOwnProperty;function ic(t){var e=this.__data__;return st?e[t]!==void 0:rc.call(e,t)}var sc="__lodash_hash_undefined__";function ac(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=st&&e===void 0?sc:e,this}function ye(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}ye.prototype.clear=Xl;ye.prototype.delete=Yl;ye.prototype.get=tc;ye.prototype.has=ic;ye.prototype.set=ac;function oc(){this.__data__=[],this.size=0}function Xt(t,e){for(var n=t.length;n--;)if(jl(t[n][0],e))return n;return-1}var lc=Array.prototype,cc=lc.splice;function uc(t){var e=this.__data__,n=Xt(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():cc.call(e,n,1),--this.size,!0}function hc(t){var e=this.__data__,n=Xt(e,t);return n<0?void 0:e[n][1]}function dc(t){return Xt(this.__data__,t)>-1}function fc(t,e){var n=this.__data__,r=Xt(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function Me(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}Me.prototype.clear=oc;Me.prototype.delete=uc;Me.prototype.get=hc;Me.prototype.has=dc;Me.prototype.set=fc;var gc=or(sr,"Map");function pc(){this.size=0,this.__data__={hash:new ye,map:new(gc||Me),string:new ye}}function mc(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Yt(t,e){var n=t.__data__;return mc(e)?n[typeof e=="string"?"string":"hash"]:n.map}function yc(t){var e=Yt(this,t).delete(t);return this.size-=e?1:0,e}function bc(t){return Yt(this,t).get(t)}function Sc(t){return Yt(this,t).has(t)}function vc(t,e){var n=Yt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function je(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}je.prototype.clear=pc;je.prototype.delete=yc;je.prototype.get=bc;je.prototype.has=Sc;je.prototype.set=vc;function wc(t){return t==null?"":ar(t)}function xc(t,e,n){var r=-1,i=t.length;e<0&&(e=-e>i?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var s=Array(i);++r<i;)s[r]=t[r+e];return s}function Ec(t,e,n){var r=t.length;return n=n===void 0?r:n,!e&&n>=r?t:xc(t,e,n)}var Cc="\\ud800-\\udfff",kc="\\u0300-\\u036f",Oc="\\ufe20-\\ufe2f",Ac="\\u20d0-\\u20ff",Tc=kc+Oc+Ac,Rc="\\ufe0e\\ufe0f",Nc="\\u200d",Dc=RegExp("["+Nc+Cc+Tc+Rc+"]");function Fc(t){return Dc.test(t)}function Ic(t){return t.split("")}var ds="\\ud800-\\udfff",Pc="\\u0300-\\u036f",Lc="\\ufe20-\\ufe2f",$c="\\u20d0-\\u20ff",_c=Pc+Lc+$c,Bc="\\ufe0e\\ufe0f",qc="["+ds+"]",In="["+_c+"]",Pn="\\ud83c[\\udffb-\\udfff]",Uc="(?:"+In+"|"+Pn+")",fs="[^"+ds+"]",gs="(?:\\ud83c[\\udde6-\\uddff]){2}",ps="[\\ud800-\\udbff][\\udc00-\\udfff]",Vc="\\u200d",ms=Uc+"?",ys="["+Bc+"]?",zc="(?:"+Vc+"(?:"+[fs,gs,ps].join("|")+")"+ys+ms+")*",Mc=ys+ms+zc,jc="(?:"+[fs+In+"?",In,gs,ps,qc].join("|")+")",Hc=RegExp(Pn+"(?="+Pn+")|"+jc+Mc,"g");function Wc(t){return t.match(Hc)||[]}function Kr(t){return Fc(t)?Wc(t):Ic(t)}var Gc="__lodash_hash_undefined__";function Kc(t){return this.__data__.set(t,Gc),this}function Jc(t){return this.__data__.has(t)}function Dt(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new je;++e<n;)this.add(t[e])}Dt.prototype.add=Dt.prototype.push=Kc;Dt.prototype.has=Jc;function Xc(t,e){return t.has(e)}function Yc(t){return ls(t)&&Jl(t)}var Qc=200;function Zc(t,e,n,r){var i=-1,s=Ml,o=!0,a=t.length,c=[],l=e.length;if(!a)return c;e.length>=Qc&&(s=Xc,o=!1,e=new Dt(e));e:for(;++i<a;){var u=t[i],h=u;if(u=u!==0?u:0,o&&h===h){for(var d=l;d--;)if(e[d]===h)continue e;c.push(u)}else s(e,h,r)||c.push(u)}return c}function eu(t,e){for(var n=t.length;n--&&lr(e,t[n],0)>-1;);return n}function tu(t,e){for(var n=-1,r=t.length;++n<r&&lr(e,t[n],0)>-1;);return n}function Jr(t,e,n){if(t=wc(t),t&&e===void 0)return gl(t);if(!t||!(e=ar(e)))return t;var r=Kr(t),i=Kr(e),s=tu(r,i),o=eu(r,i)+1;return Ec(r,s,o).join("")}var nu=Wl(function(t,e){return Yc(t)?Zc(t,e):[]}),Ne=function(){return Ne=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},Ne.apply(this,arguments)},ru="~",iu="~~";function cr(t,e){for(var n={},r={},i=t.split(iu),s=!1,o=0;i.length>o;o++){for(var a=i[o].split(ru),c=0;c<a.length;c+=2){var l=a[c],u=a[c+1],h="&"+l+";";n[h]=u,s&&(n["&"+l]=u),r[u]=h}s=!0}return e?{entities:Ne(Ne({},n),e.entities),characters:Ne(Ne({},r),e.characters)}:{entities:n,characters:r}}var ln={xml:/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html4:/&notin;|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g,html5:/&centerdot;|&copysr;|&divideontimes;|&gtcc;|&gtcir;|&gtdot;|&gtlPar;|&gtquest;|&gtrapprox;|&gtrarr;|&gtrdot;|&gtreqless;|&gtreqqless;|&gtrless;|&gtrsim;|&ltcc;|&ltcir;|&ltdot;|&lthree;|&ltimes;|&ltlarr;|&ltquest;|&ltrPar;|&ltri;|&ltrie;|&ltrif;|&notin;|&notinE;|&notindot;|&notinva;|&notinvb;|&notinvc;|&notni;|&notniva;|&notnivb;|&notnivc;|&parallel;|&timesb;|&timesbar;|&timesd;|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g},_e={};_e.xml=cr(`lt~<~gt~>~quot~"~apos~'~amp~&`);_e.html4=cr(`apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~‌~zwj~‍~lrm~‎~rlm~‏~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~­~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~"~amp~&~lt~<~gt~>`);_e.html5=cr('Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~⁡~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~⁣~InvisibleTimes~⁢~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~​~NegativeThickSpace~​~NegativeThinSpace~​~NegativeVeryThinSpace~​~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~⁠~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~ ~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~  ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~​~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~⁡~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~⁣~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~⁢~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~"~REG~®',_e.html4);var su={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376},au=String.fromCodePoint||function(t){return String.fromCharCode(Math.floor((t-65536)/1024)+55296,(t-65536)%1024+56320)},Be=function(){return Be=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},Be.apply(this,arguments)},ou=Be(Be({},_e),{all:_e.html5}),lu={scope:"body",level:"all"},cn=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g,un=/&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g,Xr={xml:{strict:cn,attribute:un,body:ln.xml},html4:{strict:cn,attribute:un,body:ln.html4},html5:{strict:cn,attribute:un,body:ln.html5}},cu=Be(Be({},Xr),{all:Xr.html5}),bs=String.fromCharCode,uu=bs(65533);function hu(t,e,n,r){var i=t,s=t[t.length-1];if(n&&s==="=")i=t;else if(r&&s!==";")i=t;else{var o=e[t];if(o)i=o;else if(t[0]==="&"&&t[1]==="#"){var a=t[2],c=a=="x"||a=="X"?parseInt(t.substr(3),16):parseInt(t.substr(2));i=c>=1114111?uu:c>65535?au(c):bs(su[c]||c)}}return i}function Yr(t,e){var n=e===void 0?lu:e,r=n.level,i=r===void 0?"all":r,s=n.scope,o=s===void 0?i==="xml"?"strict":"body":s;if(!t)return"";var a=cu[i][o],c=ou[i].entities,l=o==="attribute",u=o==="strict";return t.replace(a,function(h){return hu(h,c,l,u)})}var du={strictlyTwoElementsInRangeArrays:!1,progressFn:null};function Ft(t,e){if(!Array.isArray(t)||!t.length)return t;let n={...du,...e},r,i;if(n.strictlyTwoElementsInRangeArrays&&!t.every((a,c)=>!Array.isArray(a)||a.length!==2?(r=c,i=a.length,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_03] The first argument should be an array and must consist of arrays which are natural number indexes representing TWO string index ranges. However, ${r}th range (${JSON.stringify(t[r],null,4)}) has not two but ${i} elements!`);if(!t.every((a,c)=>!Array.isArray(a)||!Number.isInteger(a[0])||a[0]<0||!Number.isInteger(a[1])||a[1]<0?(r=c,!1):!0))throw new TypeError(`ranges-sort: [THROW_ID_04] The first argument should be an array and must consist of arrays which are natural number indexes representing string index ranges. However, ${r}th range (${JSON.stringify(t[r],null,4)}) does not consist of only natural numbers!`);let s=t.length**2,o=0;return Array.from(t).sort((a,c)=>(n.progressFn&&(o+=1,n.progressFn(Math.floor(o*100/s))),a[0]===c[0]?a[1]<c[1]?-1:a[1]>c[1]?1:0:a[0]<c[0]?-1:1))}var Qr={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function fu(t,e){function n(l){return!!l&&typeof l=="object"&&!Array.isArray(l)}if(!Array.isArray(t)||!t.length)return null;let r;if(e)if(n(e)){if(r={...Qr,...e},r.progressFn&&n(r.progressFn)&&!Object.keys(r.progressFn).length)r.progressFn=null;else if(r.progressFn&&typeof r.progressFn!="function")throw new Error(`ranges-merge: [THROW_ID_01] opts.progressFn must be a function! It was given of a type: "${typeof r.progressFn}", equal to ${JSON.stringify(r.progressFn,null,4)}`);if(![1,2,"1","2"].includes(r.mergeType))throw new Error(`ranges-merge: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof r.mergeType}", equal to ${JSON.stringify(r.mergeType,null,4)}`);if(typeof r.joinRangesThatTouchEdges!="boolean")throw new Error(`ranges-merge: [THROW_ID_04] opts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof r.joinRangesThatTouchEdges}", equal to ${JSON.stringify(r.joinRangesThatTouchEdges,null,4)}`)}else throw new Error(`emlint: [THROW_ID_03] the second input argument must be a plain object. It was given as:
2
- ${JSON.stringify(e,null,4)} (type ${typeof e})`);else r={...Qr};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;r.progressFn?s=Ft(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,r.progressFn(a))}}):s=Ft(i);let c=s.length-1;for(let l=c;l>0;l--)r.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,r.progressFn(a))),(s[l][0]<=s[l-1][0]||!r.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||r.joinRangesThatTouchEdges&&s[l][0]<=s[l-1][1])&&(s[l-1][0]=Math.min(s[l][0],s[l-1][0]),s[l-1][1]=Math.max(s[l][1],s[l-1][1]),s[l][2]!==void 0&&(s[l-1][0]>=s[l][0]||s[l-1][1]<=s[l][1])&&s[l-1][2]!==null&&(s[l][2]===null&&s[l-1][2]!==null?s[l-1][2]=null:s[l-1][2]!=null?+r.mergeType==2&&s[l-1][0]===s[l][0]?s[l-1][2]=s[l][2]:s[l-1][2]+=s[l][2]:s[l-1][2]=s[l][2]),s.splice(l,1),l=s.length);return s.length?s:null}var gu={},pu=gu.NODE_ENV==="production",Zr="Invariant failed";function mu(t,e){if(!t){if(pu)throw new Error(Zr);var n=Zr;throw new Error(n)}}function yu(t,e,n){if(arguments.length===0)throw new Error("ranges-apply: [THROW_ID_01] inputs missing!");if(typeof t!="string")throw new TypeError(`ranges-apply: [THROW_ID_02] first input argument must be a string! Currently it's: ${typeof t}, equal to: ${JSON.stringify(t,null,4)}`);if(e&&!Array.isArray(e))throw new TypeError(`ranges-apply: [THROW_ID_03] second input argument must be an array (or null)! Currently it's: ${typeof e}, equal to: ${JSON.stringify(e,null,4)}`);if(!e?.filter(o=>o).length)return t;let r;Array.isArray(e)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?r=[Array.from(e)]:r=Array.from(e),r.length,r.filter(o=>o).forEach((o,a)=>{if(!Array.isArray(o))throw new TypeError(`ranges-apply: [THROW_ID_05] ranges array, second input arg., has ${a}th element not an array: ${JSON.stringify(o,null,4)}, which is ${typeof o}`);if(!Number.isInteger(o[0])){if(!Number.isInteger(+o[0])||+o[0]<0)throw new TypeError(`ranges-apply: [THROW_ID_06] ranges array, second input arg. has ${a}th element, array ${JSON.stringify(o,null,0)}. Its first element is not an integer, string index, but ${typeof o[0]}, equal to: ${JSON.stringify(o[0],null,4)}.`);r[a][0]=+r[a][0]}if(!Number.isInteger(o[1])){if(!Number.isInteger(+o[1])||+o[1]<0)throw new TypeError(`ranges-apply: [THROW_ID_07] ranges array, second input arg. has ${a}th element, array ${JSON.stringify(o,null,0)}. Its second element is not an integer, string index, but ${typeof o[1]}, equal to: ${JSON.stringify(o[1],null,4)}.`);r[a][1]=+r[a][1]}});let i=fu(r,{progressFn:o=>{}});mu(i);let s=i.length;if(s>0){let o=t.slice(i[s-1][1]);t=i.reduce((a,c,l,u)=>{let h=l===0?0:u[l-1][1],d=u[l][0];return`${a}${t.slice(h,d)}${u[l][2]||""}`},""),t+=o}return t}function hn(t,e=1){let n=" ";function r(s){return Array.from(s).reverse().join("")}function i(s,o,a){let c=a?`
3
- `:"\r",l=a?"\r":`
4
- `;if(!s)return s;let u=0,h="";for(let d=0,g=s.length;d<g;d++)(s[d]===c||s[d]===l&&s[d-1]!==c)&&u++,`\r
5
- `.includes(s[d])||s[d]===n?s[d]===n?h+=s[d]:s[d]===c?u<=o&&(h+=s[d],s[d+1]===l&&(h+=s[d+1],d++)):s[d]===l&&s?.[d-1]!==c&&u<=o&&(h+=s[d]):!s[d+1]&&!u&&(h+=" ");return h}if(typeof t=="string"&&t.length){let s=1;typeof+e=="number"&&Number.isInteger(+e)&&+e>=0&&(s=+e);let o="",a="";if(!t.trim())o=t;else if(!t[0].trim()){for(let c=0,l=t.length;c<l;c++)if(t[c].trim()){o=t.slice(0,c);break}}if(t.trim()&&(t.slice(-1).trim()===""||t.slice(-1)===n)){for(let c=t.length;c--;)if(t[c].trim()){a=t.slice(c+1);break}}return`${i(o,s,!1)}${t.trim()}${r(i(r(a),s,!0))}`}return t}var ei={mergeType:1,progressFn:null,joinRangesThatTouchEdges:!0};function bu(t,e){function n(l){return!!l&&typeof l=="object"&&!Array.isArray(l)}if(!Array.isArray(t)||!t.length)return null;let r;if(e)if(n(e)){if(r={...ei,...e},r.progressFn&&n(r.progressFn)&&!Object.keys(r.progressFn).length)r.progressFn=null;else if(r.progressFn&&typeof r.progressFn!="function")throw new Error(`ranges-merge: [THROW_ID_01] resolvedOpts.progressFn must be a function! It was given of a type: "${typeof r.progressFn}", equal to ${JSON.stringify(r.progressFn,null,4)}`);if(![1,2,"1","2"].includes(r.mergeType))throw new Error(`ranges-merge: [THROW_ID_02] resolvedOpts.mergeType was customised to a wrong thing! It was given of a type: "${typeof r.mergeType}", equal to ${JSON.stringify(r.mergeType,null,4)}`);if(typeof r.joinRangesThatTouchEdges!="boolean")throw new Error(`ranges-merge: [THROW_ID_04] resolvedOpts.joinRangesThatTouchEdges was customised to a wrong thing! It was given of a type: "${typeof r.joinRangesThatTouchEdges}", equal to ${JSON.stringify(r.joinRangesThatTouchEdges,null,4)}`)}else throw new Error(`ranges-merge: [THROW_ID_03] the second input argument must be a plain object. It was given as:
6
- ${JSON.stringify(e,null,4)} (type ${typeof e})`);else r={...ei};let i=t.filter(l=>Array.isArray(l)).map(l=>[...l]).filter(l=>l[2]!==void 0||l[0]!==l[1]),s,o,a;r.progressFn?s=Ft(i,{progressFn:l=>{a=Math.floor(l/5),a!==o&&(o=a,r.progressFn!=null&&r.progressFn(a))}}):s=Ft(i);let c=s.length-1;for(let l=c;l>0;l--)r.progressFn&&(a=Math.floor((1-l/c)*78)+21,a!==o&&a>o&&(o=a,r.progressFn(a))),(s[l][0]<=s[l-1][0]||!r.joinRangesThatTouchEdges&&s[l][0]<s[l-1][1]||r.joinRangesThatTouchEdges&&s[l][0]<=s[l-1][1])&&(s[l-1][0]=Math.min(s[l][0],s[l-1][0]),s[l-1][1]=Math.max(s[l][1],s[l-1][1]),s[l][2]!==void 0&&(s[l-1][0]>=s[l][0]||s[l-1][1]<=s[l][1])&&s[l-1][2]!==null&&(s[l][2]===null&&s[l-1][2]!==null?s[l-1][2]=null:s[l-1][2]!=null?+(r||{})?.mergeType==2&&s[l-1][0]===s[l][0]?s[l-1][2]=s[l][2]:s[l-1][2]+=s[l][2]:s[l-1][2]=s[l][2]),s.splice(l,1),l=s.length);return s.length?s:null}var Su={limitToBeAddedWhitespace:!1,limitLinebreaksCount:1,mergeType:1},vu=class{constructor(e){let n={...Su,...e};if(n.mergeType&&n.mergeType!==1&&n.mergeType!==2)if(Oe(n.mergeType)&&n.mergeType.trim()==="1")n.mergeType=1;else if(Oe(n.mergeType)&&n.mergeType.trim()==="2")n.mergeType=2;else throw new Error(`ranges-push: [THROW_ID_02] opts.mergeType was customised to a wrong thing! It was given of a type: "${typeof n.mergeType}", equal to ${JSON.stringify(n.mergeType,null,4)}`);this.opts=n,this.ranges=[]}ranges;opts;add(e,n,r){if(e==null&&n==null)return;if(se(e)&&!se(n)){if(Array.isArray(e)){if(e.length){if(e.some(o=>Array.isArray(o))){e.forEach(o=>{Array.isArray(o)&&this.add(...o)});return}e.length&&xe(+e[0])&&xe(+e[1])&&this.add(...e)}return}throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_12] the first input argument, "from" is set (${JSON.stringify(e,null,0)}) but second-one, "to" is not (${JSON.stringify(n,null,0)})`)}else if(!se(e)&&se(n))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_13] the second input argument, "to" is set (${JSON.stringify(n,null,0)}) but first-one, "from" is not (${JSON.stringify(e,null,0)})`);let i=+e,s=+n;if(xe(i)&&xe(s)){if(se(r)&&!Oe(r)&&!Jo(r))throw new TypeError(`ranges-push/Ranges/add(): [THROW_ID_08] The third argument, the value to add, was given not as string but ${typeof r}, equal to:
7
- ${JSON.stringify(r,null,4)}`);if(se(this.ranges)&&Array.isArray(this.last())&&i===this.last()[1]){if(this.last()[1]=s,this.last()[2],this.last()[2]!==null&&se(r)){let o=this.last()[2]&&this.last()[2].length&&(!this.opts?.mergeType||this.opts.mergeType===1)?`${this.last()[2]}${r}`:r;this.opts.limitToBeAddedWhitespace&&(o=hn(o,this.opts.limitLinebreaksCount)),Oe(o)&&!o.length||(this.last()[2]=o)}}else{this.ranges||(this.ranges=[]);let o=r!==void 0&&!(Oe(r)&&!r.length)?[i,s,r&&this.opts.limitToBeAddedWhitespace?hn(r,this.opts.limitLinebreaksCount):r]:[i,s];this.ranges.push(o)}}else throw xe(i)&&i>=0?new TypeError(`ranges-push/Ranges/add(): [THROW_ID_10] "to" value, the second input argument, must be a natural number or zero! Currently it's of a type "${typeof s}" equal to: ${JSON.stringify(s,null,4)}`):new TypeError(`ranges-push/Ranges/add(): [THROW_ID_09] "from" value, the first input argument, must be a natural number or zero! Currently it's of a type "${typeof i}" equal to: ${JSON.stringify(i,null,4)}`)}push(e,n,r){this.add(e,n,r)}current(){return Array.isArray(this.ranges)&&this.ranges.length?(this.ranges=bu(this.ranges,{mergeType:this.opts.mergeType}),this.ranges&&this.opts.limitToBeAddedWhitespace?this.ranges.map(e=>se(e[2])?[e[0],e[1],hn(e[2],this.opts.limitLinebreaksCount)]:e):this.ranges):null}wipe(){this.ranges=[]}replace(e){if(Array.isArray(e)&&e.length)if(Array.isArray(e[0])&&xe(e[0][0]))this.ranges=Array.from(e);else throw new Error(`ranges-push/Ranges/replace(): [THROW_ID_11] Single range was given but we expected array of arrays! The first element, ${JSON.stringify(e[0],null,4)} should be an array and its first element should be an integer, a string index.`);else this.ranges=[]}last(){return Array.isArray(this.ranges)&&this.ranges.length?this.ranges[this.ranges.length-1]:null}};ss();var dn=" ";function wu({str:t,idx:e=0,stopAtNewlines:n=!1,stopAtRawNbsp:r=!1}){if(typeof t!="string"||!t.length||((!e||typeof e!="number")&&(e=0),!t[e+1]))return null;if(t[e+1]&&(t[e+1].trim()||n&&`
8
- \r`.includes(t[e+1])||r&&t[e+1]===dn))return e+1;if(t[e+2]&&(t[e+2].trim()||n&&`
9
- \r`.includes(t[e+2])||r&&t[e+2]===dn))return e+2;for(let i=e+1,s=t.length;i<s;i++)if(t[i].trim()||n&&`
10
- \r`.includes(t[i])||r&&t[i]===dn)return i;return null}function Y(t,e=0){return wu({str:t,idx:e,stopAtNewlines:!1,stopAtRawNbsp:!1})}function xu(t){return/[-_A-Za-z0-9]/.test(t)}function ti(t,e){if(!t)return[];if(Array.isArray(t))return t.filter(n=>typeof n=="string"&&n.trim());if(typeof t=="string")return t.trim()?[t]:[];throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_05] ${e} must be array containing zero or more strings or something falsey. Currently it's equal to: ${t}, that a type of ${typeof t}.`)}function pt(t,e,n,r){for(let i=e,s=t.length;i<s;i++){if(t.startsWith(n,i))return!0;if(t.startsWith(r,i))return!1}return!1}function ni(t,e,n){return t?.quotes,t?.quotes?.value&&pt(e,n+1,t.quotes.value,">"),t?.quotes?.next,pt(e,t?.quotes?.next-1,t?.quotes?.value,">"),!t?.quotes||!pt(e,n+1,t.quotes.value,">")&&t?.quotes?.next!==-1&&pt(e,t?.quotes?.next-1,t?.quotes?.value,">")}function Eu(t,e){return(e.match(new RegExp(t,"g"))||[]).length}var Ge=new Set(["!doctype","abbr","address","area","article","aside","audio","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","doctype","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","math","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","param","picture","pre","progress","rb","rp","rt","rtc","ruby","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","ul","var","video","wbr","xml"]),fn=new Set(["a","b","i","p","q","s","u"]),gn=new Set([".",",",";","!","?"]),ri=new Set([".",",","?",";",")","…",'"',"»"]),Cu=new Set(["a","abbr","acronym","audio","b","bdi","bdo","big","button","canvas","cite","code","data","datalist","del","dfn","em","embed","i","iframe","input","ins","kbd","label","map","mark","meter","noscript","object","output","picture","progress","q","ruby","s","samp","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","tt","var","video","wbr"]),ii={ignoreTags:[],ignoreTagsWithTheirContents:[],onlyStripTags:[],stripTogetherWithTheirContents:["script","style","xml"],skipHtmlDecoding:!1,trimOnlySpaces:!1,stripRecognisedHTMLOnly:!1,dumpLinkHrefsNearby:{enabled:!1,putOnNewLine:!1,wrapHeads:"",wrapTails:""},ignoreIndentations:!1,cb:null,reportProgressFunc:null,reportProgressFuncFrom:0,reportProgressFuncTo:100};function Ss(t,e){let n=Date.now(),r=[],i=[],s=[],o=[],a={};function c(){a={attributes:[]}}c();let l=null,u=null,h=null,d=!1,g={},p={tagName:"",hrefValue:"",openingTagEnds:void 0},m="",b=!1,x=null,A=!0;function S(f,v,C){if(Array.isArray(v.stripTogetherWithTheirContents)&&(v.stripTogetherWithTheirContents.includes(a.name)||v.stripTogetherWithTheirContents.includes("*")))if(a.slashPresent&&Array.isArray(r)&&r.some(E=>E.name===a.name)){for(let E=r.length;E--;)if(r[E].name===a.name){o=o.filter(([N,B])=>(N<r[E].lastOpeningBracketAt||N>=f+1)&&(B<=r[E].lastOpeningBracketAt||B>f+1));let I=f+1;a.lastClosingBracketAt&&(I=a.lastClosingBracketAt+1),o.push([r[E].lastOpeningBracketAt,I]),ri.has(t[f])&&v.cb?v.cb({tag:a,deleteFrom:r[E].lastOpeningBracketAt,deleteTo:f+1,insert:null,rangesArr:C,proposedReturn:[r[E].lastOpeningBracketAt,f,null]}):v.cb&&v.cb({tag:a,deleteFrom:r[E].lastOpeningBracketAt,deleteTo:f,insert:"",rangesArr:C,proposedReturn:[r[E].lastOpeningBracketAt,f,""]}),r.splice(E,1);break}}else a.slashPresent||r.push(a);else Array.isArray(v.ignoreTagsWithTheirContents)&&X(f,v,a)&&(A=!1)}function w(f,v,C,E,I,N){if(Array.isArray(k.current())&&typeof C=="number"&&k.current()[0][0]===0&&k.current()[0][1]>=C)return"";if(t.length===E&&N&&!y?.dumpLinkHrefsNearby?.enabled)return null;let B="";if(Number.isInteger(C)&&C<I&&(B+=f.slice(C,I)),Number.isInteger(E)&&E>N+1){let Z=f.slice(N+1,E);E&&!Y(t,E-1)&&(Z=Z.trimEnd()),Z.includes(`
11
- `)&&F(E,f)?B+=" ":B+=Z}let we=!ri.has(f[v]),Pr=f[E-1]!==">"||!f[C].trim(),Lr=!['"',"("].includes(f[I-1]),mo=![";",".",":","!"].includes(f[v]);if((we||Pr&&Lr&&mo)&&(Pr||Lr)&&f[v]!=="!"&&(!Cu.has(a.name)||typeof C=="number"&&C<I||typeof E=="number"&&E>N+1)){let Z=B.match(/\n/g);return Array.isArray(Z)&&Z.length?Z.length===1?`
12
- `:Z.length===2?`
13
-
14
- `:`
15
-
16
-
17
- `:" "}return""}function T(f,v){if(f.dumpLinkHrefsNearby?.enabled&&p.tagName&&p.tagName===a.name&&a.lastOpeningBracketAt&&(p.openingTagEnds&&a.lastOpeningBracketAt>p.openingTagEnds||!p.openingTagEnds)&&(b=!0),b){let C=f.dumpLinkHrefsNearby?.putOnNewLine?`
18
-
19
- `:"";m=`${C}${p.hrefValue}`,(typeof v!="number"||Y(t,v-1))&&(m+=C)}}function F(f,v){return v?v[f]==="<"&&v[f+1]!=="%":t[f]==="<"&&t[f+1]!=="%"}function L(f){return t[f]===">"&&t[f-1]!=="%"}function X(f,v,C){if(v.ignoreTagsWithTheirContents.includes("*"))return!0;let E=t.indexOf(`<${C.name}`,f),I=t.indexOf(`</${C.name}`,f);return!C.slashPresent&&I===-1||C.slashPresent&&!i.some(N=>N.name===C.name)||I>-1&&E>-1&&E<I?!1:v.ignoreTagsWithTheirContents.includes(C.name)}if(typeof t!="string")throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_01] Input must be string! Currently it's: ${(typeof t).toLowerCase()}, equal to:
20
- ${JSON.stringify(t,null,4)}`);if(e)if(Fn(e)){if(e.reportProgressFunc&&typeof e.reportProgressFunc!="function")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_03] The Optional Options Object's key reportProgressFunc, callback function, should be a function but it was given as type ${typeof e.reportProgressFunc}, equal to ${JSON.stringify(e.reportProgressFunc,null,4)}`);if(typeof e.dumpLinkHrefsNearby=="boolean"&&e.dumpLinkHrefsNearby!=null)throw new Error(`string-strip-html/stripHtml(): [THROW_ID_04] The Optional Options Object's key should be a plain object but it was given as type ${typeof e.dumpLinkHrefsNearby}, equal to ${JSON.stringify(e.dumpLinkHrefsNearby,null,4)}`)}else throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_02] Optional Options Object must be a plain object! Currently it's: ${(typeof e).toLowerCase()}, equal to:
21
- ${JSON.stringify(e,null,4)}`);function M(){b&&(p={tagName:"",hrefValue:"",openingTagEnds:void 0},b=!1)}let y={...ii,...e,dumpLinkHrefsNearby:Object.assign({},ii.dumpLinkHrefsNearby,e?.dumpLinkHrefsNearby)};if(Xo(y,"returnRangesOnly"))throw new TypeError("string-strip-html/stripHtml(): [THROW_ID_05] The Optional Options Object's key returnRangesOnly has been removed from the API since v.5 release.");if(y.reportProgressFunc){if(typeof y.reportProgressFuncFrom!="number")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_06] The Optional Options Object's key reportProgressFuncFrom, callback function's "from" range, should be a number but it was given as type ${typeof y.reportProgressFuncFrom}, equal to ${JSON.stringify(y.reportProgressFuncFrom,null,4)}`);if(typeof y.reportProgressFuncTo!="number")throw new Error(`string-strip-html/stripHtml(): [THROW_ID_07] The Optional Options Object's key reportProgressFuncTo, callback function's "to" range, should be a number but it was given as type ${typeof y.reportProgressFuncTo}, equal to ${JSON.stringify(y.reportProgressFuncTo,null,4)}`)}y.ignoreTags=ti(y.ignoreTags,"resolvedOpts.ignoreTags"),y.onlyStripTags=ti(y.onlyStripTags,"resolvedOpts.onlyStripTags");let gt=!!y.onlyStripTags.length;y.onlyStripTags.length&&y.ignoreTags.length&&(y.onlyStripTags=nu(y.onlyStripTags,...y.ignoreTags)),y.stripTogetherWithTheirContents?typeof y.stripTogetherWithTheirContents=="string"&&y.stripTogetherWithTheirContents.length&&(y.stripTogetherWithTheirContents=[y.stripTogetherWithTheirContents]):y.stripTogetherWithTheirContents=[];let ce={};if(y.stripTogetherWithTheirContents&&Array.isArray(y.stripTogetherWithTheirContents)&&y.stripTogetherWithTheirContents.length&&!y.stripTogetherWithTheirContents.every((f,v)=>typeof f!="string"?(ce.el=f,ce.i=v,!1):!0))throw new TypeError(`string-strip-html/stripHtml(): [THROW_ID_08] Optional Options Object's key stripTogetherWithTheirContents was set to contain not just string elements! For example, element at index ${ce.i} has a value ${ce.el} which is not string but ${(typeof ce.el).toLowerCase()}.`);y.cb||(y.cb=({rangesArr:f,proposedReturn:v})=>{v&&f.push(...v)});let k=new vu({limitToBeAddedWhitespace:!0,limitLinebreaksCount:2});if(!y.skipHtmlDecoding)for(;t!==Yr(t,{scope:"strict"});)t=Yr(t,{scope:"strict"});let _=!1,G=!1,V=0,H=0,U=t.length,ve=Math.floor(U/2);for(let f=0;f<U;f++){if(y.reportProgressFunc&&(U>1e3&&U<2e3?f===ve&&y.reportProgressFunc(Math.floor((y.reportProgressFuncTo-y.reportProgressFuncFrom)/2)):U>=2e3&&(V=y.reportProgressFuncFrom+Math.floor(f/U*(y.reportProgressFuncTo-y.reportProgressFuncFrom)),V!==H&&(H=V,y.reportProgressFunc(V)))),Object.keys(a).length>1&&a.lastClosingBracketAt&&a.lastClosingBracketAt<f&&t[f]!==" "&&x===null&&(x=f),!_&&t[f]==="%"&&t[f-1]==="{"&&t.includes("%}",f+1)){h=null;let v=t.indexOf("%}",f)-1;if(v>f){f=v;continue}}if(!_&&L(f)&&(!a||Object.keys(a).length<2)&&f>1){for(let v=f;v--;)if(t[v-1]===void 0||L(v)){let C=t[v-1]===void 0?v:v+1,E=t.slice(C,f+1)||"";if((E.includes("/>")||E.includes("/ >")||E.includes('="')||E.includes("='"))&&t!==`<${Jr(E.trim(),"/>")}>`&&[...Ge].some(I=>Jr(E.trim().split(/\s+/).filter(N=>N.trim()).filter((N,B)=>B===0),"/>").toLowerCase()===I)&&Ss(`<${E.trim()}>`,y).result===""){(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([C,f+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([C,f+1]);let I=w(t,f,C,f+1,C,f+1),N=f+1;if(t[N]&&!t[N].trim()){for(let B=N;B<U;B++)if(t[B].trim()){N=B;break}}y.cb({tag:a,deleteFrom:C,deleteTo:N,insert:I,rangesArr:k,proposedReturn:[C,N,I]})}break}}if(!G&&t[f]==="/"&&!a.quotes?.value&&Number.isInteger(a.lastOpeningBracketAt)&&!Number.isInteger(a.lastClosingBracketAt)&&(a.slashPresent=f),t[f]==='"'||t[f]==="'")if(!G&&a.nameStarts&&a?.quotes?.value===t[f])if(g.valueStarts===void 0)g={},delete a.quotes;else{g.valueEnds=f,g.value=t.slice(g.valueStarts,f),a.attributes.push(g),g={},delete a.quotes;let v;y.dumpLinkHrefsNearby?.enabled&&!r.length&&a.attributes.some(C=>{if(typeof C.name=="string"&&C.name.toLowerCase()==="href")return v=`${y.dumpLinkHrefsNearby?.wrapHeads||""}${C.value}${y.dumpLinkHrefsNearby?.wrapTails||""}`,!0})&&(p={tagName:a.name,hrefValue:v,openingTagEnds:void 0})}else!G&&!a.quotes&&a.nameStarts&&(a.quotes={},a.quotes.value=t[f],a.quotes.start=f,a.quotes.next=t.indexOf(t[f],f+1),g.nameStarts&&g.nameEnds&&g.nameEnds<f&&g.nameStarts<f&&!g.valueStarts&&(g.name=t.slice(g.nameStarts,g.nameEnds)));if(a.nameStarts!==void 0&&a.nameEnds===void 0&&(!t[f].trim()||!xu(t[f]))){if(a.nameEnds=f,a.name=t.slice(a.nameStarts,a.nameEnds+(!L(f)&&t[f]!=="/"&&t[f+1]===void 0?1:0)),t[a.nameStarts-1]!=="!"&&!a.name.replace(/-/g,"").length||/^\d+$/.test(a.name[0])){a={};continue}if(typeof a.name=="string"&&a.name.toLowerCase()==="doctype"&&(G=!0),F(f)){T(y);let v=w(t,f,a.leftOuterWhitespace,f,a.lastOpeningBracketAt,f);(y.stripTogetherWithTheirContents.includes(a.name)||y.stripTogetherWithTheirContents.includes("*"))&&(o=o.filter(([C,E])=>!(C===a.leftOuterWhitespace&&E===f))),y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f,insert:`${v}${m}${v}`,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f,`${v}${m}${v}`]}),M(),S(f,y,k)}}if(a.quotes?.start&&a.quotes.start<f&&!a.quotes.end&&g.nameEnds&&g.equalsAt&&!g.valueStarts&&(g.valueStarts=f),!a.quotes&&g.nameEnds&&t[f]==="="&&!g.valueStarts&&!g.equalsAt&&(g.equalsAt=f),!a.quotes&&g.nameStarts&&g.nameEnds&&!g.valueStarts&&t[f].trim()&&t[f]!=="="&&(a.attributes.push(g),g={}),!a.quotes&&g.nameStarts&&!g.nameEnds&&(G&&`'"`.includes(t[g.nameStarts])?g.nameStarts<f&&t[f]===t[g.nameStarts]&&(g.nameEnds=f+1,g.name=t.slice(g.nameStarts,g.nameEnds)):t[f].trim()?t[f]==="="?g.equalsAt||(g.nameEnds=f,g.equalsAt=f,g.name=t.slice(g.nameStarts,g.nameEnds)):t[f]==="/"||L(f)?(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds),a.attributes.push(g),g={}):F(f)&&(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds),a.attributes.push(g),g={}):(g.nameEnds=f,g.name=t.slice(g.nameStarts,g.nameEnds))),!a.quotes&&a.nameEnds<f&&!t[f-1].trim()&&t[f].trim()&&!"<>/!".includes(t[f])&&!g.nameStarts&&!a.lastClosingBracketAt&&(g.nameStarts=f),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<f&&t[f]==="/"&&a.onlyPlausible&&(a.onlyPlausible=!1),a.lastOpeningBracketAt!==null&&a.lastOpeningBracketAt<f&&t[f]!=="/"&&(a.onlyPlausible===void 0&&((!t[f].trim()||F(f))&&!a.slashPresent?a.onlyPlausible=!0:a.onlyPlausible=!1),t[f].trim()&&a.nameStarts===void 0&&!F(f)&&t[f]!=="/"&&!L(f)&&t[f]!=="!"&&(a.nameStarts=f,a.nameContainsLetters=!1)),a.nameStarts&&!a.quotes&&typeof t[f]=="string"&&t[f].toLowerCase()!==t[f].toUpperCase()&&(a.nameContainsLetters=!0),L(f)&&(ni(a,t,f)||a.quotes.value&&typeof a.lastOpeningBracketAt=="number"&&Eu(a.quotes.value,t.slice(a.lastOpeningBracketAt,f))%2===1&&!t.slice(a.lastOpeningBracketAt+1,f).includes("<")&&!t.slice(a.lastOpeningBracketAt+1,f).includes(">"))&&a.lastOpeningBracketAt!==void 0&&(a.lastClosingBracketAt=f,x=null,Object.keys(g).length&&(a.attributes.push(g),g={}),y.dumpLinkHrefsNearby?.enabled&&p.tagName&&!p.openingTagEnds&&(p.openingTagEnds=f)),(!G||t[f]===">")&&a.lastOpeningBracketAt!==void 0){if(a.lastClosingBracketAt===void 0){if(a.lastOpeningBracketAt<f&&!F(f)&&(t[f+1]===void 0||F(f+1)&&!a?.quotes?.value)&&a.nameContainsLetters&&typeof a.nameStarts=="number"){if(a.name=t.slice(a.nameStarts,a.nameEnds||f+1).toLowerCase(),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,f+1]),y.ignoreTags.includes(a.name)||X(f,y,a)||!Ge.has(a.name)&&(a.onlyPlausible||y.stripRecognisedHTMLOnly)){a={},g={};continue}if((Ge.has(a.name)||fn.has(a.name))&&(a.onlyPlausible===!1||a.onlyPlausible===!0&&a.attributes.length)||t[f+1]===void 0){T(y);let v=w(t,f,a.leftOuterWhitespace,f+1,a.lastOpeningBracketAt,a.lastClosingBracketAt);_&&a.name==="script"&&a.slashPresent&&(_=!1);let C;v===null||m===null?C=null:C=`${v}${m}${v}`,y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f+1,insert:C,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f+1,C]}),M(),S(f,y,k)}if(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt&&o[o.length-1][1]!==f+1)if(y.stripTogetherWithTheirContents.includes(a.name)||y.stripTogetherWithTheirContents.includes("*")){let v;for(let C=r.length;C--;)r[C].name===a.name&&(v=r[C]);v?(o=o.filter(([C])=>C!==v.lastOpeningBracketAt),o.push([v.lastOpeningBracketAt,f+1])):o.push([a.lastOpeningBracketAt,f+1])}else o.push([a.lastOpeningBracketAt,f+1])}}else if(f>a.lastClosingBracketAt&&t[f].trim()||t[f+1]===void 0||y.ignoreIndentations&&`\r
22
- `.includes(t[f])){let v=a.lastClosingBracketAt===f?f+1:f;y.trimOnlySpaces&&v===U-1&&x!==null&&x<f&&(v=x),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let C=y.ignoreTags.includes(a.name),E=X(f,y,a);if(!A||y.stripRecognisedHTMLOnly&&typeof a.name=="string"&&!Ge.has(a.name.toLowerCase())&&!fn.has(a.name.toLowerCase())||!gt&&(C||E)||gt&&!y.onlyStripTags.includes(a.name)||y.ignoreTagsWithTheirContents.includes(a.name)){if(E)if(a.slashPresent){for(let I=i.length;I--;)if(i[I].name===a.name){i.splice(I,1);break}i.length||(A=!0)}else A&&(A=!1),i.push(a);y.cb({tag:a,deleteFrom:null,deleteTo:null,insert:null,rangesArr:k,proposedReturn:null}),a={},g={}}else if(!a.onlyPlausible||a.attributes.length===0&&a.name&&(Ge.has(a.name.toLowerCase())||fn.has(a.name.toLowerCase()))||a.attributes?.some(I=>I.equalsAt)){(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,a.lastClosingBracketAt+1]);let I=w(t,f,a.leftOuterWhitespace,v,a.lastOpeningBracketAt,a.lastClosingBracketAt);m="",b=!1,T(y,v);let N;typeof m=="string"&&m.length?(N=`${I}${m}${I===`
23
-
24
- `?`
25
- `:I}`,v===a.lastClosingBracketAt+1&&(!t[v]||!gn.has(t[v]))&&(N+=" "),a.leftOuterWhitespace===a.lastOpeningBracketAt&&k.last()&&k.last()[1]<a.lastOpeningBracketAt&&(!y?.dumpLinkHrefsNearby?.putOnNewLine||!gn.has(t[v]))&&(N=" "+N)):N=I,N!==null&&(a.leftOuterWhitespace===0||!Y(t,v-1))&&(!y.dumpLinkHrefsNearby?.enabled||a.name!=="a")&&(N=void 0);let B=0;if(b&&gn.has(t[v])){y.dumpLinkHrefsNearby?.putOnNewLine&&(N=`${t[v]}${N||""}`);let we=Y(t,v);we&&N?.endsWith(`
26
- `)?B+=we-f:(!we||we>f)&&B++}y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:v+B,insert:N,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,v+B,N]}),M(),S(f,y,k)}else a={};L(f)||(a={})}G&&(G=!1)}if((!_||t[f]==="<"&&Y(t,Y(t,f))&&t[Y(t,f)]==="/"&&t.startsWith("script",Y(t,Y(t,f))))&&F(f)&&!F(f-1)&&!`'"`.includes(t[f+1])&&(!`'"`.includes(t[f+2])||/\w/.test(t[f+1]))&&!(t[f+1]==="c"&&t[f+2]===":")&&!(t[f+1]==="f"&&t[f+2]==="m"&&t[f+3]==="t"&&t[f+4]===":")&&!(t[f+1]==="s"&&t[f+2]==="q"&&t[f+3]==="l"&&t[f+4]===":")&&!(t[f+1]==="x"&&t[f+2]===":")&&!(t[f+1]==="f"&&t[f+2]==="n"&&t[f+3]===":")&&ni(a,t,f)){if(L(Y(t,f)))continue;if(a.nameEnds&&a.nameEnds<f&&!a.lastClosingBracketAt&&(a.onlyPlausible===!0&&a.attributes?.length||a.onlyPlausible===!1)){let v=w(t,f,a.leftOuterWhitespace,f,a.lastOpeningBracketAt,f);y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:f,insert:v,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,f,v]}),S(f,y,k),a={},g={}}if(a.lastOpeningBracketAt!==void 0&&a.onlyPlausible&&a.name&&!a.quotes&&(a.lastOpeningBracketAt=void 0,a.name=void 0,a.onlyPlausible=!1),(a.lastOpeningBracketAt===void 0||!a.onlyPlausible)&&!a.quotes&&(a.lastOpeningBracketAt=f,a.slashPresent=!1,a.attributes=[],l===null?a.leftOuterWhitespace=f:y.trimOnlySpaces&&l===0?a.leftOuterWhitespace=u||f:a.leftOuterWhitespace=l,`${t[f+1]}${t[f+2]}${t[f+3]}`=="!--"||`${t[f+1]}${t[f+2]}${t[f+3]}${t[f+4]}${t[f+5]}${t[f+6]}${t[f+7]}${t[f+8]}`=="![CDATA[")){let v=!0;t[f+2]==="-"&&(v=!1);let C;for(let E=f;E<U;E++)if((!C&&v&&`${t[E-2]}${t[E-1]}${t[E]}`=="]]>"||!v&&`${t[E-2]}${t[E-1]}${t[E]}`=="-->")&&(C=E),C&&(C<E&&t[E].trim()||t[E+1]===void 0)){let I=E;(t[E+1]===void 0&&!t[E].trim()||t[E]===">")&&(I+=1),(!s.length||s[s.length-1][0]!==a.lastOpeningBracketAt)&&s.push([a.lastOpeningBracketAt,C+1]),(!o.length||o[o.length-1][0]!==a.lastOpeningBracketAt)&&o.push([a.lastOpeningBracketAt,C+1]);let N=w(t,E,a.leftOuterWhitespace,I,a.lastOpeningBracketAt,C);y.cb({tag:a,deleteFrom:a.leftOuterWhitespace,deleteTo:I,insert:N,rangesArr:k,proposedReturn:[a.leftOuterWhitespace,I,N]}),f=E-1,t[E]===">"&&(f=E),a={},g={};break}}}!t[f].trim()||t[f].charCodeAt(0)===847?(l===null&&(l=f,a.lastOpeningBracketAt!==void 0&&a.lastOpeningBracketAt<f&&a.nameStarts&&a.nameStarts<a.lastOpeningBracketAt&&f===a.lastOpeningBracketAt+1&&!r.some(v=>v.name===a.name)&&(a.onlyPlausible=!0,a.name=void 0,a.nameStarts=void 0)),(t[f]===`
27
- `||t[f]==="\r")&&(h=f,d&&(d=!1))):(l!==null&&(!a.quotes&&g.equalsAt>l-1&&g.nameEnds&&g.equalsAt>g.nameEnds&&t[f]!=='"'&&t[f]!=="'"&&(Fn(g)&&a.attributes.push(g),g={},a.equalsSpottedAt=void 0),l=null),d||(d=!0,A&&!_&&typeof h=="number"&&f&&h<f-1&&(t.slice(h+1,f).trim()?h=null:y.ignoreIndentations||k.push([h+1,f])))),t[f]===" "?u===null&&(u=f):u!==null&&(u=null),a.name==="script"&&(_=!a.slashPresent)}if(t&&!y.ignoreIndentations&&(y.trimOnlySpaces&&t[0]===" "||!y.trimOnlySpaces&&!t[0].trim()))for(let f=0;f<U;f++)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([0,f]);break}else t[f+1]||k.push([0,f+1]);if(t&&(y.trimOnlySpaces&&t[~-t.length]===" "||!y.trimOnlySpaces&&!t[~-t.length].trim())){for(let f=t.length;f--;)if(y.trimOnlySpaces&&t[f]!==" "||!y.trimOnlySpaces&&t[f].trim()){k.push([f+1,U]);break}}let K=k.current();if(!e?.cb&&K&&(K[0]&&!K[0][0]&&(K[0][1],k.ranges[0]=[k.ranges[0][0],k.ranges[0][1]]),K[K.length-1]?.[1]===t.length&&(K[K.length-1][0],k.ranges))){let f=k.ranges[k.ranges.length-1][0];t[f-1]&&(y.trimOnlySpaces&&t[f-1]===" "||!y.trimOnlySpaces&&!t[f-1].trim())&&(f-=1);let v=k.ranges[k.ranges.length-1][2];k.ranges[k.ranges.length-1]=[f,k.ranges[k.ranges.length-1][1]],v?.trim()&&k.ranges[k.ranges.length-1].push(v.trimEnd())}return{log:{timeTakenInMilliseconds:Date.now()-n},result:yu(t,k.current()),ranges:k.current(),allTagLocations:s,filteredTagLocations:o}}class Ln{speechSynthesis;speechSynthesisUtterance;currentVoice=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;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=jo(),this.patches=Ho(),!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,n=!!(e?.name&&typeof e.name=="string"&&e.name.toLocaleLowerCase().includes("(natural)"));return this.patches.isAndroid!==!0&&!this.patches.isFirefox&&!this.patches.isSafari&&!n}createUtterance(e){return new this.speechSynthesisUtterance(e)}async initialize(e={}){const{languages:n,maxTimeout:r,interval:i,maxLengthExceeded:s="warn"}=e;if(this.initialized)return!1;this.maxLengthExceeded=s;try{this.voiceManager=await P.initialize({languages:n,maxTimeout:r,interval:i}),this.voices=this.voiceManager.getVoices();const o=n||[...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 r="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: ${r}`);default:console.warn(`WebSpeechEngine: ${r}`)}}}getCurrentVoiceForUtterance(e){return e&&typeof e=="object"?e:typeof e=="string"?this.voices.find(n=>n.name===e||n.language===e)||null:this.currentVoice||this.defaultVoice}voiceMatchesLanguage(e,n){const[r,i]=q(n),[s,o]=q(e.language);return s===r&&(!i||o===i)}voiceForUtteranceSync(e){const n=this.getCurrentVoiceForUtterance(this.currentVoice);if(!this.speakInContentLanguage||!e.language)return n;const r=J(e.language);if(n&&this.voiceMatchesLanguage(n,r))return n;if(this.languageVoiceCache.has(r))return this.languageVoiceCache.get(r)??n}async voiceForUtterance(e){const n=this.voiceForUtteranceSync(e);return n!==void 0?n:(await this.warmLanguageVoiceCache([e]),this.voiceForUtteranceSync(e)??this.getCurrentVoiceForUtterance(this.currentVoice))}async warmLanguageVoiceCache(e){if(!this.speakInContentLanguage||!this.voiceManager)return;const n=new Set(e.map(o=>o.language).filter(o=>!!o).map(o=>J(o)).filter(o=>!this.languageVoiceCache.has(o))),r=[...n].filter(o=>this.warmingLanguages.has(o)),s=[...n].filter(o=>!this.warmingLanguages.has(o)).map(o=>{const a=(async()=>{await P.initialize({languages:[o]}),this.voices=this.voiceManager.getVoices();const c=this.voices.filter(h=>this.voiceMatchesLanguage(h,o)),u=(await this.voiceManager.sortVoicesByQuality(c))[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([...s,...r.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(n=>({...n,plain:n.plain??(n.ssml?Ss(n.ssml).result:"")}))}loadUtterances(e,n){this.currentUtterances=this.toPlainText(e),this.currentUtteranceIndex=kt(n??0,e.length),this.warmLanguageVoiceCache(this.currentUtterances),this.playbackState="ready",this.emitEvent({type:"ready"})}async setVoice(e){const n=this.currentVoice;if(typeof e=="string"){const r=this.voices.find(i=>i.name===e||i.language===e);r?(this.currentVoice=r,n&&n.name!==r.name&&(this.currentUtteranceIndex=0)):console.warn(`Voice "${e}" not found`)}else this.currentVoice=e,n&&n.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 n=++this.speakGeneration;this.isSpeakingInternal=!0,this.isPausedInternal=!1,this.setState("playing"),this.emitEvent({type:"start"}),this.stopResumeInfinity(),this.currentUtteranceIndex>=this.currentUtterances.length&&(this.currentUtteranceIndex=0),this.speakCurrentUtterance(n)}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 n=this.currentUtterances[this.currentUtteranceIndex],r=n.plain??"";this.validateText(r);const i=this.createUtterance(r),s=await this.voiceForUtterance(n);if(e===this.speakGeneration){if(s&&this.voiceManager){const o=this.voiceManager.convertToSpeechSynthesisVoice(s);o&&(i.voice=o,i.lang=o.lang)}n.language&&(i.lang=n.language),i.rate=this.rate,i.pitch=this.pitch,i.volume=this.volume,i.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(i)},i.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"}))},i.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}`}})},i.onpause=()=>{this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.emitEvent({type:"pause"})},i.onresume=()=>{this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.emitEvent({type:"resume"})},i.onboundary=o=>{this.emitEvent({type:"boundary",detail:{charIndex:o.charIndex,charLength:o.charLength,elapsedTime:o.elapsedTime,name:o.name}})},i.onmark=o=>{this.emitEvent({type:"mark",detail:{name:o.name}})},this.speechSynthesis.speak(i)}}startResumeInfinity(e){this.shouldUseResumeInfinity()&&(this.resumeInfinityTimer=window.setTimeout(()=>{if(e){const{paused:r,speaking:i}=this.speechSynthesis,s=i||this.isSpeakingInternal,o=r||this.isPausedInternal;s&&!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.patches.isAndroid?(this.isAndroidPaused=!0,this.speechSynthesis.cancel()):this.speechSynthesis.pause(),this.isPausedInternal=!0,this.isSpeakingInternal=!1,this.setState("paused"),this.emitEvent({type:"pause"}))}resume(){this.playbackState==="paused"&&this.currentUtteranceIndex<this.currentUtterances.length&&(this.isPausedInternal=!1,this.isSpeakingInternal=!0,this.setState("playing"),this.emitEvent({type:"resume"}),this.patches.isAndroid||this.pausedAtUtteranceIndex!==this.currentUtteranceIndex?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 n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,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,n){if(e<0||e>=this.currentUtterances.length){n?.(!1);return}e!==this.currentUtteranceIndex&&(!this.isPausedInternal&&this.isSpeakingInternal&&this.cancelCurrentSpeech(),this.currentUtteranceIndex=e,n?.(!0))}getUtteranceCount(){return this.currentUtterances.length}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const n=this.playbackState;if(this.playbackState=e,n!==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 ku{id="webspeech";name="Web Speech API";voiceEngine=null;async getVoices(){return this.voiceEngine||(this.voiceEngine=new Ln,await this.voiceEngine.initialize()),this.voiceEngine.getAvailableVoices()}async createEngine(e){const n=new Ln;return await n.initialize(),e&&await n.setVoice(e),n}async destroy(){this.voiceEngine&&(await this.voiceEngine.destroy(),this.voiceEngine=null)}}const De="\\p{Pe}\\p{Pf}.,;:!?,。、;:!?،؛؟",$n="\\p{Ps}\\p{Pi}¿¡",Ou=new RegExp(`^[${De}]`,"u"),Au=new RegExp(`^[${$n}]`,"u");function Qt(t){return Ou.test(t)}function Tu(t){return Au.test(t)}function vs(t,e){const n=[];let r=-1,i=-1;const s=()=>{r!==-1&&(n.push({text:Ru(t,r,i),offset:t[r].offset}),r=-1,i=-1)};for(let o=0;o<t.length;o++){const a=t[o];if(a.text.length>e){s(),n.push({text:a.text,offset:a.offset});continue}const c=a.offset+a.text.length,l=r===-1?a.text.length:c-t[r].offset;r!==-1&&l>e&&s(),r===-1&&(r=o),i=o}return s(),n}function Ru(t,e,n){const r=t[e],i=t[n];return r===i?r.text:t.slice(e,n+1).map(s=>s.text).join("")}const ws=new RegExp(`[^${De}]*[${De}]+\\s*|[^${De}]+$`,"gu"),Nu=/\S+\s*|\s+/g;function ur(t,e,n){const r=[];for(const i of t.matchAll(n))i[0].length!==0&&r.push({text:i[0],offset:e+i.index,atomic:!1});return r}function hr(t,e){if(t.text.length<=e||t.atomic)return[t];const n=ur(t.text,t.offset,Nu);if(n.length>1)return n.flatMap(o=>hr(o,e));const r=[];let i=t.offset,s="";for(const o of t.text)s.length>0&&s.length+o.length>e&&(r.push({text:s,offset:i,atomic:!1}),i+=s.length,s=""),s+=o;return s.length>0&&r.push({text:s,offset:i,atomic:!1}),r}function xs(t,e){if(t.length<=e)return[{text:t,offset:0}];const r=ur(t,0,ws).flatMap(i=>hr(i,e));return vs(r,e)}const Du=/<([a-zA-Z][\w-]*)\b[^>]*>[\s\S]*?<\/\1>|<[a-zA-Z][\w-]*\b[^>]*\/>|[^<]+/g;function Es(t,e){if(t.length<=e)return[{text:t,offset:0}];const n=[];for(const i of t.matchAll(Du))i[0][0]==="<"?n.push({text:i[0],offset:i.index,atomic:!0}):n.push(...ur(i[0],i.index,ws));const r=n.flatMap(i=>hr(i,e));return vs(r,e)}const Fu={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 Cs(t){return Fu[t]??`audio/${t}`}const Iu=["flac","wav","opus","aac","ogg","webm","mp3"],Pu=["opus","aac","webm","ogg","mp3","wav","flac"];function ks(t,e,n){const r=a=>n(Cs(a))!=="",i=t.formats.filter(r);if(e.preferredFormat&&i.includes(e.preferredFormat))return e.preferredFormat;const s=e.strategy==="bandwidth"?Pu:Iu,o=[...s,...i.filter(a=>!s.includes(a))];for(const a of o)if(i.includes(a))return a;return t.default}const Lu=new Set(["wav","flac"]),$u={mp3:48e3,opus:24e3,aac:48e3,ogg:48e3,webm:32e3};function Os(t,e,n){return Lu.has(t)||!e||!n?void 0:n.saveData===!0||/2g/.test(n.effectiveType??"")?$u[t]:void 0}function dr(t,e){return{source:"server",label:t.name,name:t.name,originalName:t.originalName,language:t.language,otherLanguages:t.otherLanguages,gender:t.gender??void 0,quality:t.quality,provider:t.provider,identifier:t.identifier,controls:e}}class qe extends Error{status;type;title;instance;constructor(e,n){super(e),this.name="SpeechServerError",this.status=n.status,this.type=n.type,this.title=n.title,this.instance=n.instance}}class fr extends qe{constructor(e){super(e,{status:408,type:"https://readium.org/speech-server/error#stall",title:"Synthesis Stalled"}),this.name="SpeechServerStallError"}}class gr extends Error{constructor(e){super(e),this.name="SpeechServerAudioDecodeError"}}class pr extends Error{constructor(e){super(e),this.name="SpeechServerNetworkError"}}async function Fe(t){if((t.headers.get("content-type")??"").includes("application/problem+json"))try{const n=await t.json();return new qe(n.detail||n.title||`Request failed with status ${t.status}`,{status:n.status??t.status,type:n.type,title:n.title,instance:n.instance})}catch{}return new qe(`Request failed with status ${t.status}`,{status:t.status})}const _u=3,Bu=400;function qu(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n.buffer}function Uu(t){return me(t,.25,4,1)}function mt(t){return t?.plain??t?.ssml??void 0}function si(t){return t instanceof fr?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!0}:t instanceof qe?{message:t.message,status:t.status,type:t.type,title:t.title,instance:t.instance,recoverable:!1}:t instanceof gr?{message:t.message,recoverable:!1}:t instanceof pr?{message:t.message,recoverable:!0}:t instanceof Error?{message:t.message,recoverable:!1}:{message:String(t),recoverable:!1}}class As{endpoints;fetchImpl;currentVoice=null;voices=[];serviceInfo=null;serviceInfoPromise=null;currentUtterances=[];currentUtteranceIndex=0;playbackState="idle";events=new Jt;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??_u,this.readyBufferChars=e.readyBufferChars??Bu,this.overLengthText=e.overLengthText??"split",this.timeoutMs=e.timeoutMs,this.formatOptions=e.format??{},this.canPlayType=typeof Audio<"u"?n=>new Audio().canPlayType(n):()=>""}setAvailableVoices(e){this.voices=e}async fetchNetwork(e,n){try{return await this.fetchImpl(e,n)}catch(r){throw r instanceof TypeError?new pr(r.message):r}}loadUtterances(e,n){this.abortLiveControllers(),this.clearPrefetchCache(),this.currentUtterances=e,this.currentUtteranceIndex=kt(n??0,e.length),this.setState("loading"),this.bufferUntilReady(++this.loadGeneration)}async bufferUntilReady(e){const n=kt(this.currentUtteranceIndex,this.currentUtterances.length),r=Math.min(this.indexCoveringChars(this.readyBufferChars,n),n+this.prefetchWindow),i=[];for(let s=n;s<=r;s++){this.queuePrefetch(s);const o=this.prefetchCache.get(s);o&&i.push(o.then(a=>a[0].promise))}try{await Promise.all(i)}catch{}e!==this.loadGeneration||this.playbackState!=="loading"||this.setState("ready")}indexCoveringChars(e,n){if(this.currentUtterances.length===0)return-1;const r=kt(n,this.currentUtterances.length);let i=0;for(let s=r;s<this.currentUtterances.length;s++)if(i+=(mt(this.currentUtterances[s])??"").length,i>=e)return s;return this.currentUtterances.length-1}setVoice(e){if(typeof e=="string"){const n=this.voices.find(r=>r.identifier===e||r.name===e);n?this.currentVoice=n:(this.currentVoice={source:"server",label:e,name:e,originalName:e,language:"",identifier:e},this.getAvailableVoices().then(r=>{if(this.currentVoice?.identifier!==e)return;const i=r.find(s=>s.identifier===e||s.name===e);i&&(this.currentVoice=i)}).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,n]=await Promise.all([this.fetchNetwork(this.endpoints.voices),this.getServiceInfo()]);if(!e.ok)throw await Fe(e);const r=await e.json(),i=new Map(n.providers.map(s=>[s.id,s.controls]));return this.voices=r.map(s=>dr(s,i.get(s.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 Fe(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 n=++this.speakGeneration;this.isSpeakingInternal=!0,this.setState("loading"),this.synthesizeAndPlay(n)}async synthesizeAndPlay(e){const n=this.currentUtteranceIndex;try{const r=await this.resolveSynthesisStream(n);if(e!==this.speakGeneration)return;await this.scheduleChunksStreaming(r,e),this.fillPrefetchWindow(n)}catch(r){if(e!==this.speakGeneration)return;this.isSpeakingInternal=!1,this.setState("idle"),this.emitEvent({type:"error",detail:si(r)})}}async resolveSynthesisStream(e){const n=this.prefetchCache.get(e);if(n){this.prefetchCache.delete(e);try{const r=await n;for(const{controller:i}of r)this.activeControllers.delete(i),this.liveControllers.add(i);return r}catch{}}return this.synthesizeStream(e,!1)}fillPrefetchWindow(e){const n=Math.min(e+this.prefetchWindow,this.currentUtterances.length-1);for(let r=e+1;r<=n;r++)this.queuePrefetch(r)}queuePrefetch(e){if(this.prefetchCache.has(e))return;const n=this.prefetchChainTail.then(()=>this.synthesizeStream(e,!0));this.prefetchCache.set(e,n),this.prefetchChainTail=n.then(r=>Promise.all(r.map(i=>i.promise))).then(()=>{},()=>{}),n.catch(()=>{}),n.then(r=>r.forEach(i=>i.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,n){const r=this.currentUtterances[e],i=!r.plain&&!!r.ssml,s=this.speakInContentLanguage?r.language:void 0,o=mt(r)??"",a=mt(this.currentUtterances[e-1]),c=mt(this.currentUtterances[e+1]),l=await this.getServiceInfo(),u=ks(l.output,this.formatOptions,this.canPlayType),h=navigator.connection,d=Os(u,this.formatOptions.adaptBitrateToNetwork??!1,h);if(o.length<=l.limits.maxTextLength){const x=new AbortController;return(n?this.activeControllers:this.liveControllers).add(x),[{promise:this.synthesizeChunk(r,o,0,i,s,a,c,u,d,x),controller:x}]}if(this.overLengthText==="error")throw new qe(`Text exceeds this server's maximum length of ${l.limits.maxTextLength} characters`,{status:413,type:"https://readium.org/speech-server/error#payload_too_large",title:"Payload Too Large"});const g=Math.min(l.limits.maxTextLength,this.readyBufferChars),p=i?Es(o,g):xs(o,g),m=[];let b=Promise.resolve();for(let x=0;x<p.length;x++){const A=x===0?a:p[x-1].text,S=x===p.length-1?c:p[x+1].text,w=p[x],T=new AbortController;(n?this.activeControllers:this.liveControllers).add(T);const F=b.then(()=>this.synthesizeChunk(r,w.text,w.offset,i,s,A,S,u,d,T));m.push({promise:F,controller:T}),b=F}return m}async synthesizeChunk(e,n,r,i,s,o,a,c,l,u){try{const h=await this.fetchNetwork(this.endpoints.synthesize,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id,text:n,ssml:i,language:s,voice:this.currentVoice?.identifier??this.currentVoice?.name,prev_utterance:o,next_utterance:a,boundary:!0,output:{format:c,bitrate:l,speed:this.rate,pitch:this.pitch}}),signal:u.signal});if(!h.ok)throw await Fe(h);const d=await h.json(),g=qu(d.audio);let p;try{p=await this.ensureAudioContext().decodeAudioData(g)}catch{throw new gr("Audio playback failed")}return{audioBuffer:p,format:d.format,boundaries:d.boundaries,textOffset:r}}finally{this.activeControllers.delete(u),this.liveControllers.delete(u)}}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,n,r){if(this.timeoutMs===void 0)return e;const i=r+this.timeoutMs;return new Promise((s,o)=>{const a=setTimeout(()=>{n.abort(),o(new fr(`No audio chunk arrived within ${i.toFixed(0)}ms of the playback buffer running dry`))},i);e.then(c=>{clearTimeout(a),s(c)},c=>{clearTimeout(a),o(c)})})}async scheduleChunksStreaming(e,n){const r=await this.awaitWithStallDeadline(e[0].promise,e[0].controller,0);if(n!==this.speakGeneration)return;const i=this.ensureAudioContext(),s=this.masterGain,a=this.currentVoice?.controls?.speed===!0?1:Uu(this.rate);this.scheduledChunks=[],this.setState("playing"),this.emitEvent({type:"start"});let c=i.currentTime,l=null;const u=h=>{const d=i.createBufferSource();d.buffer=h.audioBuffer,d.playbackRate.value=a,d.connect(s),d.start(c),l&&(l.onended=null),d.onended=()=>this.handleUtteranceEnded(n),l=d,this.scheduledChunks.push({chunk:h,startTime:c,node:d,nextBoundaryIndex:0,rate:a}),c+=h.audioBuffer.duration/a};u(r),this.startBoundaryPolling(n);for(let h=1;h<e.length;h++){let d;try{const g=Math.max(0,(c-i.currentTime)*1e3);d=await this.awaitWithStallDeadline(e[h].promise,e[h].controller,g)}catch(g){n===this.speakGeneration&&this.emitEvent({type:"error",detail:si(g)});return}if(n!==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 n=()=>{e===this.speakGeneration&&(this.checkBoundaries(),this.boundaryRafHandle=requestAnimationFrame(n))};this.boundaryRafHandle=requestAnimationFrame(n)}stopBoundaryPolling(){this.boundaryRafHandle!==null&&(cancelAnimationFrame(this.boundaryRafHandle),this.boundaryRafHandle=null)}checkBoundaries(){if(!this.audioContext)return;const e=this.audioContext.currentTime;for(const n of this.scheduledChunks){const r=n.chunk.boundaries??[];for(;n.nextBoundaryIndex<r.length&&e>=n.startTime+r[n.nextBoundaryIndex].elapsedTime/n.rate;){const i=r[n.nextBoundaryIndex];this.emitEvent({type:"boundary",detail:{name:i.name,charIndex:i.charIndex+n.chunk.textOffset,charLength:i.charLength,elapsedTime:i.elapsedTime}}),n.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 n=me(e,.1,10,this.rate);n!==this.rate&&(this.rate=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getRate(){return this.rate}setPitch(e){const n=me(e,0,2,this.pitch);n!==this.pitch&&(this.pitch=n,this.clearPrefetchCache(),this.scheduleRestartIfSpeaking())}getPitch(){return this.pitch}setVolume(e){const n=me(e,0,1,this.volume);n!==this.volume&&(this.volume=n,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,n){if(e<0||e>=this.currentUtterances.length){n?.(!1);return}if(e===this.currentUtteranceIndex){n?.(!0);return}this.stopAudio(),this.currentUtteranceIndex=e,n?.(!0)}getUtteranceCount(){return this.currentUtterances.length}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}setState(e){const n=this.playbackState;if(this.playbackState=e,n!==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 Vu{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[n,r]=await Promise.all([this.fetchImpl(this.options.endpoints.voices),this.fetchImpl(this.options.endpoints.service)]);if(!n.ok)throw await Fe(n);if(!r.ok)throw await Fe(r);const i=await n.json(),s=await r.json(),o=new Map(s.providers.map(a=>[a.id,a.controls]));return this.voices=i.map(a=>dr(a,o.get(a.provider))),this.voices}async createEngine(e){const n=new As(this.options);return this.voices.length>0&&n.setAvailableVoices(this.voices),e&&n.setVoice(e),n}async destroy(){this.voices=[]}}function Ts(t){return t.detail?.recoverable===!0}const zu=3e4,Mu=["start","pause","resume","end","stop","skip","boundary","mark","idle","loading","ready","voiceschanged","languagefallback"];class Rs{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 Jt;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??zu,this.lastVoiceRequest=e.primaryEngine.getCurrentVoice()??void 0,this.bindActiveEngine()}async initialize(){return this.activeEngine.initialize?.()}loadUtterances(e,n){this.loadToken++,this.currentUtterances=e,this.desiredIndex=n??0,this.desiredPlaying=!1,!this.swapInFlight&&(this.engineStarted=!0,this.activeEngine.loadUtterances(e,n))}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,n){if(this.desiredIndex=e,!this.isEngineTrusted()){n?.(!0);return}this.activeEngine.setCurrentUtteranceIndex(e,n)}getUtteranceCount(){return this.activeEngine.getUtteranceCount()}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}bindActiveEngine(){const e=this.activeEngine,n=Mu.map(r=>e.on(r,i=>{this.emitEvent(i),this.maybeRecoverNow()}));n.push(e.on("error",r=>this.handleError(r))),this.unbindActiveEngine=()=>n.forEach(r=>r())}handleError(e){if(this.hasFallenBack||this.swapInFlight||this.onFailure==="error"||!Ts(e)){this.emitEvent(e);return}this.swapToFallback(e)}copyPlaybackParameters(e,n){n.setRate(e.getRate()),n.setPitch(e.getPitch()),n.setVolume(e.getVolume()),n.setSpeakInContentLanguage(e.getSpeakInContentLanguage())}startEngineWhenReady(e){const n=this.loadToken,r=e.on("ready",()=>{r(),n===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 n=null;await this.performSwap(async()=>{const i=this.activeEngine.getCurrentVoice()??(typeof this.lastVoiceRequest=="object"?this.lastVoiceRequest:null),s=i?.language||this.currentUtterances[this.desiredIndex]?.language||(typeof navigator<"u"?navigator.language:"en");if(n=await this.pickBestFallbackVoice(s,i?.gender),!n)throw new Error("no offline-available fallback voice found");return this.fallbackProvider.createEngine(n)},()=>(this.hasFallenBack=!0,this.onFailure==="fallbackAndRecover"&&this.startHealthCheck(),{type:"enginefallback",detail:{reason:e.detail,voice:n}}),()=>{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,n,r){this.swapInFlight=!0;const i=this.teardownEpoch,s=this.activeEngine;let o;try{o=await e()}catch{this.swapInFlight=!1,r();return}if(i!==this.teardownEpoch){this.swapInFlight=!1,await o.destroy();return}this.copyPlaybackParameters(s,o),this.unbindActiveEngine?.(),this.activeEngine=o,this.engineStarted=!1,this.swapInFlight=!1,this.bindActiveEngine(),this.emitEvent(n(o)),this.startEngineWhenReady(o),o.loadUtterances(this.currentUtterances,this.desiredIndex),await s.destroy()}async pickBestFallbackVoice(e,n){const r=await this.fallbackProvider.getVoices(),s=typeof navigator<"u"&&navigator.onLine===!0?r:r.filter(d=>d.offlineAvailability===!0);if(s.length===0)return null;const[o]=Gt([e]),{voicesByLang:a}=Kt(s,[o]),c=a.get(o.baseLang)??[],l=c.length>0?c:s,u=n?l.filter(d=>d.gender===n):[],h=u.length>0?u:l;return ko(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 ju{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(n){if(this.onFailure==="error")throw n;return this.fallback.getVoices(e)}}async createEngine(e){let n;try{n=await this.primary.createEngine(e)}catch(r){if(this.onFailure==="error")throw r;return this.fallback.createEngine(e)}return new Rs({primaryEngine:n,primaryProvider:this.primary,fallbackProvider:this.fallback,onFailure:this.onFailure,healthCheckIntervalMs:this.healthCheckIntervalMs})}async destroy(){await Promise.all([this.primary.destroy(),this.fallback.destroy()])}}let Hu=class{};function Wu(t){return(t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode)==="vertical-lr"}function Gu(t){const e=t.getComputedStyle(t.document.documentElement).writingMode||t.getComputedStyle(t.document.body).writingMode;return e==="vertical-rl"||e==="vertical-lr"}function Ee(t){const e=Gu(t),n=e&&Wu(t),r=t.innerWidth,i=t.innerHeight,s=t.document.scrollingElement,o=s.scrollLeft,a=s.scrollTop,c=parseInt(t.getComputedStyle(t.document.documentElement).getPropertyValue("column-count")),l=e&&!n?s.scrollWidth-r+o:o,u=a;return{isVertical:e,isVertLR:n,viewportInlineSize:e?i:r,viewportBlockSize:e?r:i,pageInlineSize:e?i:r/(c||1),xDocOffset:l,yDocOffset:u,inlineScrollOffset:e?u:l,blockScrollOffset:e?l: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,g,p,m,b){h.style.position="absolute",e?(h.style.top=`${d*b}px`,h.style.left=`${g*b}px`,h.style.height=`${p*b}px`,h.style.width=`${m*b}px`):(h.style.left=`${d*b}px`,h.style.top=`${g*b}px`,h.style.width=`${p*b}px`,h.style.height=`${m*b}px`)},toRect(h,d,g,p){return e?new DOMRect(d,h,p,g):new DOMRect(h,d,g,p)}}}function ai(t,e){return t.document.documentElement.style.getPropertyValue(e)}function Ku(t){return t&&Array.isArray(t)?t:void 0}function Ju(t){return t&&typeof t=="string"?[t]:Ku(t)}function Ot(t){return isNaN(t)?void 0:t}function pn(t){return Ot(t)!==void 0&&Math.sign(t)>=0?t:void 0}let It=class Ns{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let n=pn(e.textNodeIndex);if(n===void 0)return;let r=pn(e.charOffset);return r===void 0&&(r=pn(e.offset)),new Ns({cssSelector:e.cssSelector,textNodeIndex:n,charOffset:r})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}},Ds=class Fs{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let n=It.deserialize(e.start);if(n)return new Fs({start:n,end:It.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}},yt=null,mn=null,Ke=0;const Ae={r:255,g:255,b:255,a:1},Ce=new Map,Xu=()=>{if(!yt)if(typeof OffscreenCanvas<"u")yt=new OffscreenCanvas(5,5),mn=yt.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const t=document.createElement("canvas");t.width=5,t.height=5,yt=t,mn=t.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return mn},Yu=t=>{if(!t)return!0;const e=t.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(n=>e.includes(n))},bt=(t,e)=>{console.warn(`[Decorator] Could not parse color: "${t}". ${e} Falling back to ${JSON.stringify(Ae)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},be=(t,e=null)=>{const n=e?`${t}|${e}`:t,r=Ce.get(n);if(r!==void 0)return r??Ae;if(Yu(t))return bt(t,"Unsupported color format or special value."),Ce.set(n,null),Ae;const i=Xu();if(!i)return bt(t,"Could not get canvas context."),Ce.set(n,null),Ae;try{Ke===0&&i.clearRect(0,0,5,5);const s=Ke%5,o=Math.floor(Ke/5);i.clearRect(s,o,1,1),e&&(i.fillStyle=e,i.fillRect(s,o,1,1)),i.fillStyle=t,i.fillRect(s,o,1,1);const a=i.getImageData(s,o,1,1);Ke=(Ke+1)%25;const[c,l,u,h]=a.data;if(h===0)return bt(t,"Fully transparent color."),Ce.set(n,null),Ae;const d={r:c,g:l,b:u,a:h/255};return Ce.set(n,d),d}catch(s){return bt(t,`Error: ${s instanceof Error?s.message:String(s)}`),Ce.set(n,null),Ae}},yn=t=>{const e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},_n=t=>{const e=yn(t.r),n=yn(t.g),r=yn(t.b);return .2126*e+.7152*n+.0722*r},Pt=(t,e)=>{const n=typeof t=="string"?be(t):t,r=typeof e=="string"?be(e):e,i=_n(n),s=_n(r),o=Math.max(i,s),a=Math.min(i,s);return(o+.05)/(a+.05)},Is=(t,e=null)=>{const n=be(t,e),r=Pt(n,{r:255,g:255,b:255,a:1}),i=Pt(n,{r:0,g:0,b:0,a:1});return r>i},oi=(t,e=null)=>Is(t,e)?"white":"black",Qu=t=>{const e=t.a!==void 0?t.a:1;return`rgba(${Math.round(t.r)}, ${Math.round(t.g)}, ${Math.round(t.b)}, ${e})`},Zu=(t,e)=>({r:Math.min(255,t.r+(255-t.r)*e),g:Math.min(255,t.g+(255-t.g)*e),b:Math.min(255,t.b+(255-t.b)*e),a:t.a??1}),eh=(t,e)=>({r:Math.max(0,t.r*(1-e)),g:Math.max(0,t.g*(1-e)),b:Math.max(0,t.b*(1-e)),a:t.a??1}),ke=(t,e=null,n=3)=>{const r=be(t),i=e?be(e):{r:255,g:255,b:255,a:1};let s=Pt(r,i);if(s>=n)return t;const o=_n(i)<.5;let a={...r,a:r.a??1};const c=20,l=.1;for(let u=0;u<c&&(o?a=Zu(a,l):a=eh(a,l),s=Pt(a,i),!(s>=n));u++);return Qu(a)},Ps=()=>typeof navigator>"u"?"":navigator.userAgent||"",Ls=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;let $s=class{constructor(){const e=Ls(),n=Ps(),r=s=>(typeof s=="string"||typeof s=="number")&&s?String(s).replace(/_/g,".").split(".").map(o=>parseInt(o)||0):[],i=(s="")=>{if(!s)return[];const o=new RegExp("^.*"+s+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return o.test(n)?r(n.replace(o,"$1")):[]};this.OS=(s=>(/(macOS|Mac OS X)/.test(n)?(/\(iP(hone|od touch);/.test(n)&&(s.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(n)?s.iOS=s.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(n)&&(document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(n)?s.Windows=(o=>o[0]!==6||!o[1]?o:o[1]===1?[7]:o[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(n)?s.Android=i("Android"):/CrOS/.test(n)?s.ChromeOS=i():/X11;/.test(n)&&(s.Linux=i()),s))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(s=>(o=>{const a=s.platform,c=s.platformVersion;if(!(!a||!c)){if(/^i(OS|P(hone|od touch))$/.test(a))o.iOS=r(c);else if(/^iPad(OS)?$/.test(a))o.iOS=o.iPadOS=r(c);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?o.iOS=o.iPadOS=r():o.macOS=r(c);else if(/^(Microsoft )?Windows$/.test(a))o.Windows=r(c);else if(/^(Google )?Android$/.test(a))o.Android=r(c);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))o.ChromeOS=r(c);else if(/^(Linux|Ubuntu|X11)$/.test(a))o.Linux=r(c);else return;Object.keys(this.OS).forEach(l=>delete this.OS[l]),Object.assign(this.OS,o)}})({})),this.UA=(s=>{let o=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((c,l)=>(c[l.brand]=[l.version*1],c),{});a["Google Chrome"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Edge=a["Microsoft Edge"]):a.Opera&&(o=!0,s.Blink=s.Chromium=a.Chromium||[],s.Opera=a.Opera)}return o||(/ Gecko\/\d/.test(n)?(s.Gecko=i("rv"),/ Waterfox\/\d/.test(n)?s.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(n)&&(s.Firefox=i("Firefox"))):/ Edge\/\d/.test(n)?(s.EdgeHTML=i("Edge"),s.Edge=s.EdgeHTML):/ Chrom(ium|e)\/\d/.test(n)?(s.Blink=s.Chromium=(a=>a[0]?a:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(n)?s.Edge=(a=>a[0]?a:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(n)?s.Opera=i("OPR"):/ Vivaldi\/\d/.test(n)?s.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(n)?s.Silk=i("Silk"):/ UCBrowser\/\d/.test(n)?s.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(n)?s.Phoebe=i("Phoebe"):s.Chrome=(a=>a[0]?a:s.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(n)?(s.WebKit=i("AppleWebKit"),/ CriOS \d/.test(n)?s.Chrome=i("CriOS"):/ FxiOS \d/.test(n)?s.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(n)?s.Edge=i("EdgiOS"):/ Version\/\d/.test(n)&&(s.Safari=i("Version"))):/ Trident\/\d/.test(n)&&(s.Trident=i("Trident"),s.InternetExplorer=(a=>a[0]?a:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(n)&&(s.Facebook=i("FBAV")),/ Line\/\d/.test(n)&&(s.LINE=i("Line")),s})({}),this.Env={get:()=>[this.OS,this.UA].reduce((s,o)=>{for(const a in o)o[a]&&s.push(a);return s},[])}}},th=class extends $s{get iOSRequest(){const e=Ls(),n=Ps();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(n)||e&&/^iPad(OS)?$/.test(e.platform)?"mobile":"desktop"}};const nh=new $s;new th;const li=":~:text=";function rh(t){if(!t)return;const e=t.indexOf(li);if(e===-1)return;const n=t.slice(e+li.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r.length>1&&r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>1&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}const _s=["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"],Qe=/[\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,ih=/[^\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,Bs=(t,e,n)=>{const r=[],i=e.createRange();for(i.selectNodeContents(n??e);!i.collapsed&&r.length<2;){let s;if(t.prefix){const o=Ze(t.prefix,i);if(o==null)break;St(i,o.startContainer,o.startOffset);const a=e.createRange();if(a.setStart(o.endContainer,o.endOffset),a.setEnd(i.endContainer,i.endOffset),qs(a),a.collapsed||(s=Ze(t.textStart,a),s==null))break;if(s.compareBoundaryPoints(Range.START_TO_START,a)!==0)continue}else{if(s=Ze(t.textStart,i),s==null)break;St(i,s.startContainer,s.startOffset)}if(t.textEnd){const o=e.createRange();o.setStart(s.endContainer,s.endOffset),o.setEnd(i.endContainer,i.endOffset);let a=!1;for(;!o.collapsed&&r.length<2;){const c=Ze(t.textEnd,o);if(c==null)break;if(St(o,c.startContainer,c.startOffset),s.setEnd(c.endContainer,c.endOffset),t.suffix){const l=ci(t.suffix,s,i,e);if(l===te.NO_SUFFIX_MATCH)break;if(l===te.SUFFIX_MATCH){a=!0,r.push(s.cloneRange());continue}else if(l===te.MISPLACED_SUFFIX)continue}else a=!0,r.push(s.cloneRange())}if(!a)break}else if(t.suffix){const o=ci(t.suffix,s,i,e);if(o===te.NO_SUFFIX_MATCH)break;if(o===te.SUFFIX_MATCH){r.push(s.cloneRange()),St(i,i.startContainer,i.startOffset);continue}else if(o===te.MISPLACED_SUFFIX)continue}else r.push(s.cloneRange())}return r},te={NO_SUFFIX_MATCH:0,SUFFIX_MATCH:1,MISPLACED_SUFFIX:2},ci=(t,e,n,r)=>{const i=r.createRange();i.setStart(e.endContainer,e.endOffset),i.setEnd(n.endContainer,n.endOffset),qs(i);const s=Ze(t,i);return s==null?te.NO_SUFFIX_MATCH:s.compareBoundaryPoints(Range.START_TO_START,i)!==0?te.MISPLACED_SUFFIX:te.SUFFIX_MATCH},St=(t,e,n)=>{try{t.setStart(e,n+1)}catch{t.setStartAfter(e)}},qs=t=>{const e=Us(t);let n=e.nextNode();for(;!t.collapsed&&n!=null;){if(n!==t.startContainer&&t.setStart(n,0),n.textContent.length>t.startOffset&&!n.textContent[t.startOffset].match(/\s/))return;try{t.setStart(n,t.startOffset+1)}catch{n=e.nextNode(),n==null?t.collapse():t.setStart(n,0)}}},Us=t=>(t.commonAncestorContainer.ownerDocument??t.commonAncestorContainer).createTreeWalker(t.commonAncestorContainer,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:e=>ah(e,t)}),sh=t=>{if(t.hidden==="until-found")return!0;const e=t.attributes;return!!(e&&e.hidden&&e.hidden.value==="until-found")},mr=t=>{let e=t;for(;e!=null&&!(e instanceof HTMLElement);)e=e.parentNode;const n=e?.ownerDocument?.defaultView;if(e!=null&&n!=null){if(sh(e))return!0;const r=n.getComputedStyle(e);if(r.visibility==="hidden"||r.display==="none"||parseInt(r.height,10)===0&&r.overflowY!="visible"||parseInt(r.width,10)===0&&r.overflowX!="visible"||parseInt(r.opacity,10)===0)return!1}return!0},Vs=(t,e)=>e!=null&&!e.intersectsNode(t)?NodeFilter.FILTER_REJECT:mr(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT,ah=(t,e)=>e!=null&&!e.intersectsNode(t)||!mr(t)?NodeFilter.FILTER_REJECT:t.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,oh=(t,e)=>{const n=[];let r=[];const i=Array.from(ch(t,s=>Vs(s,e)));for(const s of i)s.nodeType===Node.TEXT_NODE?r.push(s):s instanceof HTMLElement&&_s.includes(s.tagName.toUpperCase())&&r.length>0&&(n.push(r),r=[]);return r.length>0&&n.push(r),n},lh=(t,e,n)=>{let r="";return t.length===1?r=t[0].textContent.substring(e,n):r=t[0].textContent.substring(e)+t.slice(1,-1).reduce((i,s)=>i+s.textContent,"")+t.slice(-1)[0].textContent.substring(0,n),r.replace(/[\t\n\r ]+/g," ")};function*ch(t,e){const n=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e}),r=new Set;for(;Ms(n,r)!==null;)yield n.currentNode}const Ze=(t,e)=>{const n=oh(e.commonAncestorContainer,e),r=zs(e.commonAncestorContainer.ownerDocument??void 0);for(const i of n){const s=uh(t,e,i,r);if(s!==void 0)return s}},uh=(t,e,n,r)=>{if(!t||!e||!(n||[]).length)return;const i=n[0]===e.startContainer?e.startOffset:0,s=ae(lh(n,i,void 0)),o=ae(t);let a=0,c,l;for(;a<s.length;){const u=s.indexOf(o,a);if(u===-1)return;if(hh(s,u,o.length,r)){const h=ae(n[0].data.slice(0,i)).length;c=ui(h+u,n,!1),l=ui(h+u+o.length,n,!0)}if(c!=null&&l!=null){const h=new Range;if(h.setStart(c.node,c.offset),h.setEnd(l.node,l.offset),e.compareBoundaryPoints(Range.START_TO_START,h)<=0&&e.compareBoundaryPoints(Range.END_TO_END,h)>=0)return h}a=u+1}},ui=(t,e,n)=>{let r=0,i;for(let s=0;s<e.length;s++){const o=e[s];i||(i=ae(o.data));let a=r+i.length;if(n&&(a+=1),a>t){const c=t-r;let l=Math.min(t-r,o.data.length);const u=n?i.substring(0,c):i.substring(c);let h=ae(n?o.data.substring(0,l):o.data.substring(l));const d=(n?-1:1)*(u.length>h.length?-1:1);for(;l>=0&&l<=o.data.length;){if(h.length===u.length)return{node:o,offset:l};l+=d,h=ae(n?o.data.substring(0,l):o.data.substring(l))}}if(r+=i.length,s+1<e.length){const c=ae(e[s+1].data);i.slice(-1)===" "&&c.slice(0,1)===" "&&(r-=1),i=c}}},hh=(t,e,n,r)=>{if(e<0||e>=t.length||n<=0||e+n>t.length)return!1;if(r){const i=r.segment(t),s=i.containing(e);if(!s||s.isWordLike&&s.index!=e)return!1;const o=e+n,a=i.containing(o);if(a&&a.isWordLike&&a.index!=o)return!1}else if(t[e].match(Qe)&&(++e,--n,!n)||t[e+n-1].match(Qe)&&(--n,!n)||e!==0&&!t[e-1].match(Qe)||e+n!==t.length&&!t[e+n].match(Qe))return!1;return!0},ae=t=>(t||"").normalize("NFKD").replace(/\s+/g," ").replace(/[\u0300-\u036f]/g,"").toLowerCase(),zs=t=>{if(Intl.Segmenter){const e=t?.documentElement?.lang||t?.defaultView?.navigator?.language||void 0;return new Intl.Segmenter(e,{granularity:"word"})}},Ms=(t,e)=>{if(!e.has(t.currentNode)){const i=t.firstChild();if(i!==null)return i}const n=t.nextSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},dh=(t,e)=>{if(!e.has(t.currentNode)){const i=t.lastChild();if(i!==null)return i}const n=t.previousSibling();if(n!==null)return n;const r=t.parentNode();return r!==null&&e.add(r),r},D={BLOCK_ELEMENTS:_s,BOUNDARY_CHARS:Qe,NON_BOUNDARY_CHARS:ih,acceptNodeIfVisibleInRange:Vs,normalizeString:ae,makeNewSegmenter:zs,forwardTraverse:Ms,backwardTraverse:dh,makeTextNodeWalker:Us,isNodeVisible:mr},fh=300,js=20,gh=1,hi=3,di=1;let ph=500,Hs;class Ws extends Error{constructor(){super(...arguments),this.isTimeout=!0}}const de={SUCCESS:0,INVALID_SELECTION:1,AMBIGUOUS:2,TIMEOUT:3,EXECUTION_FAILED:4},mh=(t,e=Date.now())=>{try{return yh(t,e)}catch(n){return n instanceof Ws?{status:de.TIMEOUT}:{status:de.EXECUTION_FAILED}}},yh=(t,e)=>{Sh(e);const n=t.startContainer.ownerDocument,r=bh(n);Oh(t),Rh(t);const i=t.cloneRange();if(Ah(t),t.collapsed)return{status:de.INVALID_SELECTION};let s;if(wh(t)){const h=D.normalizeString(t.toString()),d={textStart:h};if(h.length>=js&&Ks(d,n,r))return{status:de.SUCCESS,fragment:d};s=new bn(n,r).setExactTextMatch(h)}else{const h=fi(t),d=gi(t);h&&d?s=new bn(n,r).setStartAndEndSearchSpace(h,d):s=new bn(n,r).setSharedSearchSpace(t.toString().trim())}const o=n.createRange();o.selectNodeContents(r);const a=o.cloneRange();o.setEnd(i.startContainer,i.startOffset),a.setStart(i.endContainer,i.endOffset);const c=gi(o),l=fi(a);(c||l)&&s.setPrefixAndSuffixSearchSpace(c,l),s.useSegmenter(D.makeNewSegmenter(n));let u=!1;do{j(),u=s.embiggen();const h=s.tryToMakeUniqueFragment();if(h!=null)return{status:de.SUCCESS,fragment:h}}while(u);return{status:de.AMBIGUOUS}},bh=t=>t.querySelector("body")??t.documentElement,j=()=>{const t=Date.now()-Hs;if(t>ph)throw new Ws(`Fragment generation timed out after ${t} ms.`)},Sh=t=>{Hs=t},fi=t=>{let e=ut(t);const n=Se(e,t.endContainer);if(!n)return;const r=new Set;t.startContainer.nodeType===Node.ELEMENT_NODE&&t.startOffset===t.startContainer.childNodes.length&&r.add(t.startContainer);const i=e,s=new Gs(t,!0),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setStartAfter(e):o.setStartBefore(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.forwardTraverse(n,r)}},gi=t=>{let e=Zt(t);const n=Se(e,t.startContainer);if(!n)return;const r=new Set;t.endContainer.nodeType===Node.ELEMENT_NODE&&t.endOffset===0&&r.add(t.endContainer);const i=e,s=new Gs(t,!1),o=t.cloneRange();for(;!o.collapsed&&e!=null;){if(j(),e.contains?.(i)?o.setEnd(e,0):o.setEndAfter(e),s.appendNode(e),s.textInBlock!==null)return s.textInBlock;e=D.backwardTraverse(n,r)}},vh={ALL_PARTS:1,SHARED_START_AND_END:2,CONTEXT_ONLY:3};let bn=class{constructor(e,n){this.Mode=vh,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=n}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 n=this.getPrefixSearchSpace().substring(this.prefixOffset).trim();n&&(e.prefix=n)}if(this.suffixOffset!=null){const n=this.getSuffixSearchSpace().substring(0,this.suffixOffset).trim();n&&(e.suffix=n)}return Ks(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 r=this.getNumberOfRangeWordsToAdd();if(this.startOffset<this.getStartSearchSpace().length){let i=0;if(this.getStartSegments()!=null)for(;i<r&&this.startOffset<this.getStartSearchSpace().length;)this.startOffset=this.getNextOffsetForwards(this.getStartSegments(),this.startOffset,this.getStartSearchSpace()),i++;else{let s=this.startOffset;do{j();const o=this.getStartSearchSpace().substring(this.startOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.startOffset=this.getStartSearchSpace().length:this.startOffset=this.startOffset+1+o,this.getStartSearchSpace().substring(s,this.startOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.startOffset,i++)}while(this.startOffset<this.getStartSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.startOffset=Math.min(this.startOffset,this.endOffset))}if(this.backwardsEndOffset()<this.getEndSearchSpace().length){let i=0;if(this.getEndSegments()!=null)for(;i<r&&this.endOffset>0;)this.endOffset=this.getNextOffsetBackwards(this.getEndSegments(),this.endOffset),i++;else{let s=this.backwardsEndOffset();do{j();const o=this.getBackwardsEndSearchSpace().substring(this.backwardsEndOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsEndOffset(this.getEndSearchSpace().length):this.setBackwardsEndOffset(this.backwardsEndOffset()+1+o),this.getBackwardsEndSearchSpace().substring(s,this.backwardsEndOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsEndOffset(),i++)}while(this.backwardsEndOffset()<this.getEndSearchSpace().length&&i<r)}this.mode===this.Mode.SHARED_START_AND_END&&(this.endOffset=Math.max(this.startOffset,this.endOffset))}}let n=!1;if((!e||this.startOffset+this.backwardsEndOffset()<js||this.numIterations>=gh)&&(this.backwardsPrefixOffset()!=null&&this.backwardsPrefixOffset()!==this.getPrefixSearchSpace().length||this.suffixOffset!=null&&this.suffixOffset!==this.getSuffixSearchSpace().length)&&(n=!0),n){const r=this.getNumberOfContextWordsToAdd();if(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length){let i=0;if(this.getPrefixSegments()!=null)for(;i<r&&this.prefixOffset>0;)this.prefixOffset=this.getNextOffsetBackwards(this.getPrefixSegments(),this.prefixOffset),i++;else{let s=this.backwardsPrefixOffset();do{j();const o=this.getBackwardsPrefixSearchSpace().substring(this.backwardsPrefixOffset()+1).search(D.BOUNDARY_CHARS);o===-1?this.setBackwardsPrefixOffset(this.getBackwardsPrefixSearchSpace().length):this.setBackwardsPrefixOffset(this.backwardsPrefixOffset()+1+o),this.getBackwardsPrefixSearchSpace().substring(s,this.backwardsPrefixOffset()).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.backwardsPrefixOffset(),i++)}while(this.backwardsPrefixOffset()<this.getPrefixSearchSpace().length&&i<r)}}if(this.suffixOffset<this.getSuffixSearchSpace().length){let i=0;if(this.getSuffixSegments()!=null)for(;i<r&&this.suffixOffset<this.getSuffixSearchSpace().length;)this.suffixOffset=this.getNextOffsetForwards(this.getSuffixSegments(),this.suffixOffset,this.getSuffixSearchSpace()),i++;else{let s=this.suffixOffset;do{j();const o=this.getSuffixSearchSpace().substring(this.suffixOffset+1).search(D.BOUNDARY_CHARS);o===-1?this.suffixOffset=this.getSuffixSearchSpace().length:this.suffixOffset=this.suffixOffset+1+o,this.getSuffixSearchSpace().substring(s,this.suffixOffset).search(D.NON_BOUNDARY_CHARS)!==-1&&(s=this.suffixOffset,i++)}while(this.suffixOffset<this.getSuffixSearchSpace().length&&i<r)}}}return this.numIterations++,e||n}setStartAndEndSearchSpace(e,n){return this.startSearchSpace=e,this.endSearchSpace=n,this.backwardsEndSearchSpace=At(n),this.startOffset=0,this.endOffset=n.length,this.mode=this.Mode.ALL_PARTS,this}setSharedSearchSpace(e){return this.sharedSearchSpace=e,this.backwardsSharedSearchSpace=At(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,n){return e&&(this.prefixSearchSpace=e,this.backwardsPrefixSearchSpace=At(e),this.prefixOffset=e.length),n&&(this.suffixSearchSpace=n,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?hi:di}getNumberOfRangeWordsToAdd(){return this.startOffset===0&&this.backwardsEndOffset()===0?hi:di}getNextOffsetForwards(e,n,r){let i=e.containing(n);for(;i!=null;){j();const s=i.index+i.segment.length;if(i.isWordLike)return s;i=e.containing(s)}return r.length}getNextOffsetBackwards(e,n){let r=e.containing(n);for((!r||n==r.index)&&(r=e.containing(n-1));r!=null;){if(j(),r.isWordLike)return r.index;r=e.containing(r.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 Gs{constructor(e,n){this.textFound=!1,this.textNodes=[],this.textInBlock=null,this.searchRange=e,this.isForwardTraversal=n}appendNode(e){if(this.textInBlock!==null)return;if(le(e)){this.textFound?(this.isForwardTraversal||this.textNodes.reverse(),this.textInBlock=this.textNodes.map(r=>r.textContent).join("").trim()):this.textNodes=[];return}if(!yr(e))return;const n=this.getNodeIntersectionWithRange(e);this.textFound=this.textFound||(n.textContent??"").trim()!=="",this.textNodes.push(n)}getNodeIntersectionWithRange(e){let n=null,r=null;const i=(e.textContent??"").length;return e===this.searchRange.startContainer&&this.searchRange.startOffset!==0&&(n=this.searchRange.startOffset),e===this.searchRange.endContainer&&this.searchRange.endOffset!==i&&(r=this.searchRange.endOffset),n!==null||r!==null?{textContent:(e.textContent??"").substring(n??0,r??i)}:e}}const Ks=(t,e,n)=>Bs(t,e,n).length===1,At=t=>[...t||""].reverse().join(""),wh=t=>t.toString().length>fh?!1:!Ch(t),ut=t=>{let e=t.startContainer;return e.nodeType==Node.ELEMENT_NODE&&t.startOffset<e.childNodes.length&&(e=e.childNodes[t.startOffset]),e},Zt=t=>{let e=t.endContainer;return e.nodeType==Node.ELEMENT_NODE&&t.endOffset>0&&(e=e.childNodes[t.endOffset-1]),e},xh=t=>{const e=ut(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,n.nextNode()},Eh=t=>{const e=Zt(t);if(yr(e)&&D.isNodeVisible(e))return e;const n=D.makeTextNodeWalker(t);return n.currentNode=e,D.backwardTraverse(n,new Set)},Ch=t=>{const e=t.cloneRange();let n=ut(e);const r=Se(n);if(!r)return!1;const i=new Set;for(;!e.collapsed&&n!=null;){if(le(n))return!0;n!=null&&e.setStartAfter(n),n=D.forwardTraverse(r,i),j()}return!1},pi=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??n.data.length;if(r<n.data.length&&D.BOUNDARY_CHARS.test(n.data[r]))return r;const i=n.data.substring(0,r),s=At(i).search(D.BOUNDARY_CHARS);return s!==-1?r-s:-1},kh=(t,e)=>{if(t.nodeType!==Node.TEXT_NODE)return-1;const n=t,r=e??0;if(r<n.data.length&&r>0&&D.BOUNDARY_CHARS.test(n.data[r-1]))return r;const i=n.data.substring(r).search(D.BOUNDARY_CHARS);return i!==-1?r+i:-1},Se=(t,e)=>{if(!t)return;let n=t;const r=e??t;for(;!n.contains?.(r)||!le(n);)n.parentNode&&(n=n.parentNode);const i=(n.ownerDocument??n).createTreeWalker(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:s=>D.acceptNodeIfVisibleInRange(s)});return i.currentNode=t,i},Oh=t=>{const e=D.makeNewSegmenter(t.startContainer.ownerDocument??void 0);if(e){const n=ut(t);n!==t.startContainer&&t.setStartBefore(n),Js(e,!1,t)}else{const n=pi(t.startContainer,t.startOffset);if(n!==-1){t.setStart(t.startContainer,n);return}if(le(t.startContainer)&&t.startOffset===0)return;const r=Se(t.startContainer);if(!r)return;const i=new Set;let s=D.backwardTraverse(r,i);for(;s!=null;){const o=pi(s);if(o!==-1){t.setStart(s,o);return}if(le(s)){s.contains?.(t.startContainer)?t.setStart(s,0):t.setStartAfter(s);return}s=D.backwardTraverse(r,i),t.collapse()}}},Ah=t=>{const e=xh(t);if(e==null){t.collapse();return}ut(t)!==e&&t.setStart(e,0);const n=Zt(t),r=Eh(t);n!==r&&t.setEnd(r,(r.textContent??"").length)},Js=(t,e,n)=>{const r=e?{node:n.endContainer,offset:n.endOffset}:{node:n.startContainer,offset:n.startOffset},i=Th(r.node);if(!i)return;const s=i.preNodes.reduce((p,m)=>p.concat(m.textContent??""),""),o=i.innerNodes.reduce((p,m)=>p.concat(m.textContent??""),"");let a=s.length;r.node.nodeType===Node.TEXT_NODE?a+=r.offset:e&&(a+=o.length);const c=i.postNodes.reduce((p,m)=>p.concat(m.textContent??""),""),l=[...i.preNodes,...i.innerNodes,...i.postNodes];if(l.length==0)return;const u=s.concat(o,c),h=t.segment(u).containing(a);if(!h){e?n.setEndAfter(l[l.length-1]):n.setEndBefore(l[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 g=0;for(const p of l){const m=(p.textContent??"").length;if(g<=d&&d<g+m){const b=d-g;e?b>=m?n.setEndAfter(p):n.setEnd(p,b):b>=m?n.setStartAfter(p):n.setStart(p,b);return}g+=m}e?n.setEndAfter(l[l.length-1]):n.setStartBefore(l[0])},Th=t=>{const e=[],n=Se(t);if(!n)return;const r=new Set;let i=D.backwardTraverse(n,r);for(;i!=null&&!le(i);)j(),i.nodeType===Node.TEXT_NODE&&e.push(i),i=D.backwardTraverse(n,r);e.reverse();const s=[];if(t.nodeType===Node.TEXT_NODE)s.push(t);else{const u=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:d=>D.acceptNodeIfVisibleInRange(d)});u.currentNode=t;let h=u.nextNode();for(;h!=null;)j(),h.nodeType===Node.TEXT_NODE&&s.push(h),h=u.nextNode()}const o=[],a=Se(t);if(!a)return;const c=new Set([t]);let l=D.forwardTraverse(a,c);for(;l!=null&&!le(l);)j(),l.nodeType===Node.TEXT_NODE&&o.push(l),l=D.forwardTraverse(a,c);return{preNodes:e,innerNodes:s,postNodes:o}},Rh=t=>{const e=D.makeNewSegmenter(t.endContainer.ownerDocument??void 0);if(e){const n=Zt(t);n!==t.endContainer&&t.setEndAfter(n),Js(e,!0,t)}else{let n=t.endOffset,r=t.endContainer;r.nodeType===Node.ELEMENT_NODE&&t.endOffset<r.childNodes.length&&(r=r.childNodes[t.endOffset]);const i=Se(r);if(!i)return;const s=new Set([r]);for(;r!=null;){j();const o=kh(r,n);if(n=null,o!==-1){t.setEnd(r,o);return}if(le(r)){r.contains?.(t.endContainer)?t.setEnd(r,r.childNodes.length):t.setEndBefore(r);return}r=D.forwardTraverse(i,s)}t.collapse()}},le=t=>t.nodeType===Node.ELEMENT_NODE&&(D.BLOCK_ELEMENTS.includes(t.tagName.toUpperCase())||t.tagName.toUpperCase()==="HTML"||t.tagName.toUpperCase()==="BODY"),yr=t=>t.nodeType===Node.TEXT_NODE;function Bn(t){return t.otherLocations?.get("cssSelector")}function Nh(t){return Ds.deserialize(t.otherLocations?.get("domRange"))}function Dh(t){for(const e of t.fragments){const n=rh(e);if(n)return n}}let ue=class Xs{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 n=Ot(e.progression),r=Ot(e.totalProgression),i=Ot(e.position),s=new Map,o=new Set(["fragment","fragments","progression","totalProgression","position","otherLocations"]);return Object.entries(e).forEach(([a,c])=>{o.has(a)||s.set(a,c)}),e.otherLocations instanceof Map&&e.otherLocations.forEach((a,c)=>s.set(c,a)),new Xs({fragments:Ju(e.fragments||e.fragment),progression:n!==void 0&&n>=0&&n<=1?n:void 0,totalProgression:r!==void 0&&r>=0&&r<=1?r:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:s.size===0?void 0:s})}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((n,r)=>e[r]=n),e}},br=class Ys{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new Ys({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}},Sr=class qn{constructor(e){const n=e.href.indexOf("#"),r=n>=0?e.href.slice(n+1):void 0;this.href=n>=0?e.href.slice(0,n):e.href,this.type=e.type,this.title=e.title;const i=e.locations?.fragments,s=r&&(!i||i.length===0);this.locations=e.locations?s?new ue({...e.locations,fragments:[r]}):e.locations:r?new ue({fragments:[r]}):new ue({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new qn({href:e.href,type:e.type,title:e.title,locations:ue.deserialize(e.locations),text:br.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 qn({href:this.href,type:this.type,title:this.title,text:this.text,locations:new ue({...this.locations,...e})})}};function mi(t){return t.split("").reverse().join("")}function Fh(t,e,n){const r=mi(e);return n.map(i=>{const s=Math.max(0,i.end-e.length-i.errors),o=mi(t.slice(s,i.end));return{start:Qs(o,r,i.errors).reduce((a,c)=>i.end-c.end<a?i.end-c.end:a,i.end),end:i.end,errors:i.errors}})}function Sn(t){return(t|-t)>>31&1}function yi(t,e,n,r){let i=t.P[n],s=t.M[n];const o=r>>>31,a=e[n]|o,c=a|s,l=(a&i)+i^i|a;let u=s|~(l|i),h=i&l;const d=Sn(u&t.lastRowMask[n])-Sn(h&t.lastRowMask[n]);return u<<=1,h<<=1,h|=o,u|=Sn(r)-o,i=h|~(c|u),s=u&c,t.P[n]=i,t.M[n]=s,d}function Qs(t,e,n){if(e.length===0)return[];n=Math.min(n,e.length);const r=[],i=32,s=Math.ceil(e.length/i)-1,o={P:new Uint32Array(s+1),M:new Uint32Array(s+1),lastRowMask:new Uint32Array(s+1)};o.lastRowMask.fill(1<<31),o.lastRowMask[s]=1<<(e.length-1)%i;const a=new Uint32Array(s+1),c=new Map,l=[];for(let d=0;d<256;d++)l.push(a);for(let d=0;d<e.length;d+=1){const g=e.charCodeAt(d);if(c.has(g))continue;const p=new Uint32Array(s+1);c.set(g,p),g<l.length&&(l[g]=p);for(let m=0;m<=s;m+=1){p[m]=0;for(let b=0;b<i;b+=1){const x=m*i+b;x>=e.length||e.charCodeAt(x)===g&&(p[m]|=1<<b)}}}let u=Math.max(0,Math.ceil(n/i)-1);const h=new Uint32Array(s+1);for(let d=0;d<=u;d+=1)h[d]=(d+1)*i;h[s]=e.length;for(let d=0;d<=u;d+=1)o.P[d]=-1,o.M[d]=0;for(let d=0;d<t.length;d+=1){const g=t.charCodeAt(d);let p;g<l.length?p=l[g]:(p=c.get(g),typeof p>"u"&&(p=a));let m=0;for(let b=0;b<=u;b+=1)m=yi(o,p,b,m),h[b]+=m;if(h[u]-m<=n&&u<s&&(p[u+1]&1||m<0)){u+=1,o.P[u]=-1,o.M[u]=0;let b;if(u===s){const x=e.length%i;b=x===0?i:x}else b=i;h[u]=h[u-1]+b-m+yi(o,p,u,m)}else for(;u>0&&h[u]>=n+i;)u-=1;u===s&&h[u]<=n&&(h[u]<n&&r.splice(0,r.length),r.push({start:-1,end:d+1,errors:h[u]}),n=h[u])}return r}function Ih(t,e,n){const r=Qs(t,e,n);return Fh(t,e,r)}function Zs(t,e,n){let r=0;const i=[];for(;r!==-1;)r=t.indexOf(e,r),r!==-1&&(i.push({start:r,end:r+e.length,errors:0}),r+=1);return i.length>0?i:Ih(t,e,n)}function bi(t,e){return e.length===0||t.length===0?0:1-Zs(t,e,e.length)[0].errors/e.length}function Ph(t,e,n={}){if(e.length===0)return null;const r=Math.min(256,e.length/2),i=Zs(t,e,r);if(i.length===0)return null;const s=a=>{const c=1-a.errors/e.length,l=n.prefix?bi(t.slice(Math.max(0,a.start-n.prefix.length),a.start),n.prefix):1,u=n.suffix?bi(t.slice(a.end,a.end+n.suffix.length),n.suffix):1;let h=1;return typeof n.hint=="number"&&(h=1-Math.abs(a.start-n.hint)/t.length),(50*c+20*l+20*u+2*h)/92},o=i.map(a=>({start:a.start,end:a.end,score:s(a)}));return o.sort((a,c)=>c.score-a.score),o[0]}function Un(t,e,n){const r=n===1?e:e-1;if(t.charAt(r).trim()!=="")return e;let i,s;if(n===2?(i=t.substring(0,e),s=i.trimEnd()):(i=t.substring(e),s=i.trimStart()),!s.length)return-1;const o=i.length-s.length;return n===2?e-o:e+o}function Si(t,e){const n=t.commonAncestorContainer.ownerDocument.createNodeIterator(t.commonAncestorContainer,NodeFilter.SHOW_TEXT),r=e===1?t.startContainer:t.endContainer,i=e===1?t.endContainer:t.startContainer;let s=n.nextNode();for(;s&&s!==r;)s=n.nextNode();e===2&&(s=n.previousNode());let o=-1;const a=()=>{if(s=e===1?n.nextNode():n.previousNode(),s){const c=s.textContent,l=e===1?0:c.length;o=Un(c,l,e)}};for(;s&&o===-1&&s!==i;)a();if(s&&o>=0)return{node:s,offset:o};throw new RangeError("No text nodes with non-whitespace text found in range")}function Lh(t){if(!t.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(t.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(t.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=t.cloneRange();let n=!1,r=!1;const i={start:Un(t.startContainer.textContent,t.startOffset,1),end:Un(t.endContainer.textContent,t.endOffset,2)};if(i.start>=0&&(e.setStart(t.startContainer,i.start),n=!0),i.end>0&&(e.setEnd(t.endContainer,i.end),r=!0),n&&r)return e;if(!n){const{node:s,offset:o}=Si(e,1);s&&o>=0&&e.setStart(s,o)}if(!r){const{node:s,offset:o}=Si(e,2);s&&o>0&&e.setEnd(s,o)}return e}function ea(t){switch(t.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return t.textContent?.length??0;default:return 0}}function vi(t){let e=t.previousSibling,n=0;for(;e;)n+=ea(e),e=e.previousSibling;return n}function ta(t,...e){let n=e.shift();const r=t.ownerDocument.createNodeIterator(t,NodeFilter.SHOW_TEXT),i=[];let s=r.nextNode(),o,a=0;for(;n!==void 0&&s;)o=s,a+o.data.length>n?(i.push({node:o,offset:n-a}),n=e.shift()):(s=r.nextNode(),a+=o.data.length);for(;n!==void 0&&o&&a===n;)i.push({node:o,offset:o.data.length}),n=e.shift();if(n!==void 0)throw new RangeError("Offset exceeds text length");return i}let vt=class Te{constructor(e,n){if(n<0)throw new Error("Offset is invalid");this.element=e,this.offset=n}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let n=this.element,r=this.offset;for(;n!==e;)r+=vi(n),n=n.parentElement;return new Te(n,r)}resolve(e={}){try{return ta(this.element,this.offset)[0]}catch(n){if(this.offset===0&&e.direction!==void 0){const r=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);r.currentNode=this.element;const i=e.direction===1,s=i?r.nextNode():r.previousNode();if(!s)throw n;return{node:s,offset:i?0:s.data.length}}else throw n}}static fromCharOffset(e,n){switch(e.nodeType){case Node.TEXT_NODE:return Te.fromPoint(e,n);case Node.ELEMENT_NODE:return new Te(e,n);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,n){switch(e.nodeType){case Node.TEXT_NODE:{if(n<0||n>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 r=vi(e)+n;return new Te(e.parentElement,r)}case Node.ELEMENT_NODE:{if(n<0||n>e.childNodes.length)throw new Error("Child node offset is out of range");let r=0;for(let i=0;i<n;i++)r+=ea(e.childNodes[i]);return new Te(e,r)}default:throw new Error("Point is not in an element or text node")}}},Vn=class et{constructor(e,n){this.start=e,this.end=n}relativeTo(e){return new et(this.start.relativeTo(e),this.end.relativeTo(e))}toRange(){let e,n;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[e,n]=ta(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),n=this.end.resolve({direction:2}));const r=new Range;return r.setStart(e.node,e.offset),r.setEnd(n.node,n.offset),r}static fromRange(e){const n=vt.fromPoint(e.startContainer,e.startOffset),r=vt.fromPoint(e.endContainer,e.endOffset);return new et(n,r)}static fromOffsets(e,n,r){return new et(new vt(e,n),new vt(e,r))}static trimmedRange(e){return Lh(et.fromRange(e).toRange())}},$h=class zn{constructor(e,n,r){this.root=e,this.start=n,this.end=r}static fromRange(e,n){const r=Vn.fromRange(n).relativeTo(e);return new zn(e,r.start.offset,r.end.offset)}static fromSelector(e,n){return new zn(e,n.start,n.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return Vn.fromOffsets(this.root,this.start,this.end).toRange()}},_h=class Mn{constructor(e,n,r={}){this.root=e,this.exact=n,this.context=r}static fromRange(e,n){const r=e.textContent,i=Vn.fromRange(n).relativeTo(e),s=i.start.offset,o=i.end.offset,a=32;return new Mn(e,r.slice(s,o),{prefix:r.slice(Math.max(0,s-a),s),suffix:r.slice(o,Math.min(r.length,o+a))})}static fromSelector(e,n){const{prefix:r,suffix:i}=n;return new Mn(e,n.exact,{prefix:r,suffix:i})}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 n=this.root.textContent,r=Ph(n,this.exact,{...this.context,hint:e.hint});if(!r)throw new Error("Quote not found");return new $h(this.root,r.start,r.end)}};function Bh(t){const e=t.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function wi(t,e){const n=e&&Bn(e);let r=null;if(n)try{r=t.querySelector(n)}catch(i){console.warn(`Invalid cssSelector: ${n}`,i)}return r??t.body??t.documentElement}function xi(t,e){let n;try{n=t.querySelector(e.cssSelector)}catch(i){return console.error(`Invalid domRange cssSelector: ${e.cssSelector}`,i),null}if(!n)return console.error(`Can't resolve domRange cssSelector: ${e.cssSelector}`),null;let r=0;for(const i of n.childNodes)if(i.nodeType===Node.TEXT_NODE){if(r===e.textNodeIndex)return{node:i,offset:e.charOffset};r++}return console.error(`Can't resolve domRange textNodeIndex ${e.textNodeIndex} for selector: ${e.cssSelector}`),null}function qh(t,e){try{const n=e.locations,r=e.text;if(n){const i=Nh(n);if(i){const s=xi(t,i.start),o=i.end?xi(t,i.end):s;if(s&&o)try{const a=t.createRange();return s.offset!==void 0?a.setStart(s.node,s.offset):a.setStartBefore(s.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(n){const i=Dh(n);if(i){const s=wi(t,n),o=Bs(i,t,s);if(o.length>0)return o[0]}}if(r&&r.highlight){const i=wi(t,n),s=new _h(i,r.highlight,{prefix:r.before,suffix:r.after});try{return s.toRange()}catch{return console.warn("Quote not found:",s),null}}if(n){let i=null;if(!i&&Bn(n)&&(i=t.querySelector(Bn(n))),!i&&n.fragments){for(const s of n.fragments)if(i=t.getElementById(s),i)break}if(i){const s=t.createRange();return i.childNodes.length===0||Bh(i)?(s.selectNode(i),s):(s.setStartBefore(i),s.setEndAfter(i),s)}}}catch(n){console.error(n)}return null}function Uh(t,e){const n=e.map(c=>c.toUpperCase()),r=[],i=t.commonAncestorContainer,s=i.nodeType===Node.TEXT_NODE?i.parentNode:i,o=t.startContainer.ownerDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT);let a=o.nextNode();for(;a;){if(t.intersectsNode(a)){let c=a.parentNode,l=!1;for(;c;){if(c.nodeType===Node.ELEMENT_NODE&&n.includes(c.tagName.toUpperCase())){l=!0;break}c=c.parentNode}if(!l){const u=t.cloneRange();u.selectNode(a),u.compareBoundaryPoints(Range.START_TO_START,t)<0&&u.setStart(t.startContainer,t.startOffset),u.compareBoundaryPoints(Range.END_TO_END,t)>0&&u.setEnd(t.endContainer,t.endOffset);for(const h of u.getClientRects())r.push({left:h.left,right:h.right,top:h.top,bottom:h.bottom,width:h.width,height:h.height})}}a=o.nextNode()}return r}function Je(t,e,n=!1,r=0){let i;if(Array.isArray(t))i=t;else{let l=t.getClientRects();l.length||t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(l=t.commonAncestorContainer.getClientRects()),i=[];for(const u of l)i.push({bottom:u.bottom,height:u.height,left:u.left,right:u.right,top:u.top,width:u.width})}if(r)for(const l of i)l.left-=r,l.top-=r,l.right+=r,l.bottom+=r,l.width+=r*2,l.height+=r*2;const s=na(i,1,e,n),o=zh(s,1),a=ra(o),c=4;for(let l=a.length-1;l>=0;l--){const u=a[l];if(!(u.width*u.height>c))if(a.length>1)a.splice(l,1);else break}return a}function na(t,e,n,r=!1){for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const o=t[i],a=t[s];if(o===a)continue;const c=W(o.top,a.top,e)&&W(o.bottom,a.bottom,e),l=W(o.left,a.left,e)&&W(o.right,a.right,e);if((l&&!n&&!r||c&&!l)&&ia(o,a,e)){const u=t.filter(d=>d!==o&&d!==a),h=Vh(o,a);return u.push(h),na(u,e,n,r)}}return t}function Vh(t,e){const n=Math.min(t.left,e.left),r=Math.max(t.right,e.right),i=Math.min(t.top,e.top),s=Math.max(t.bottom,e.bottom);return{bottom:s,height:s-i,left:n,right:r,top:i,width:r-n}}function zh(t,e){const n=new Set(t);for(const r of t){if(!(r.width>1&&r.height>1)){n.delete(r);continue}for(const i of t)if(r!==i&&n.has(i)&&Mh(i,r,e)){n.delete(r);break}}return Array.from(n)}function Mh(t,e,n){return oe(t,e.left,e.top,n)&&oe(t,e.right,e.top,n)&&oe(t,e.left,e.bottom,n)&&oe(t,e.right,e.bottom,n)}function oe(t,e,n,r){return(t.left<e||W(t.left,e,r))&&(t.right>e||W(t.right,e,r))&&(t.top<n||W(t.top,n,r))&&(t.bottom>n||W(t.bottom,n,r))}function ra(t){for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){const r=t[e],i=t[n];if(r!==i&&ia(r,i,-1)){let s=[],o;const a=Ei(r,i);if(a.length===1)s=a,o=r;else{const l=Ei(i,r);a.length<l.length?(s=a,o=r):(s=l,o=i)}const c=t.filter(l=>l!==o);return Array.prototype.push.apply(c,s),ra(c)}}return t}function Ei(t,e){const n=jh(e,t);if(n.height===0||n.width===0)return[t];const r=[];{const i={bottom:t.bottom,height:0,left:t.left,right:n.left,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:n.top,height:0,left:n.left,right:n.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:t.bottom,height:0,left:n.left,right:n.right,top:n.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{const i={bottom:t.bottom,height:0,left:n.right,right:t.right,top:t.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}return r}function jh(t,e){const n=Math.max(t.left,e.left),r=Math.min(t.right,e.right),i=Math.max(t.top,e.top),s=Math.min(t.bottom,e.bottom);return{bottom:s,height:Math.max(0,s-i),left:n,right:r,top:i,width:Math.max(0,r-n)}}function ia(t,e,n){return(t.left<e.right||n>=0&&W(t.left,e.right,n))&&(e.left<t.right||n>=0&&W(e.left,t.right,n))&&(t.top<e.bottom||n>=0&&W(t.top,e.bottom,n))&&(e.top<t.bottom||n>=0&&W(e.top,t.bottom,n))}function W(t,e,n){return Math.abs(t-e)<=n}const Ci=["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"],Hh=/^on/i,Wh=new Set(["href","src","action","formaction","xlink:href"]),Gh=/^\s*(javascript|data):/i;function Kh(t,e){const n=t.document.createElement("div");if("Sanitizer"in t&&typeof n.setHTML=="function")try{const i=new t.Sanitizer({allowElements:Ci});return n.setHTML(e,{sanitizer:i}),n.firstElementChild}catch{}const r=t.document.implementation.createHTMLDocument("");for(r.body.innerHTML=e,Jh(r.body,new Set(Ci));r.body.firstChild;)n.appendChild(t.document.adoptNode(r.body.firstChild));return n.firstElementChild}function Jh(t,e){const n=Array.from(t.querySelectorAll("*")).reverse();for(const r of n){if(!e.has(r.localName)){r.replaceWith(...Array.from(r.childNodes));continue}for(const{name:i,value:s}of Array.from(r.attributes))(Hh.test(i)||Wh.has(i)&&Gh.test(s))&&r.removeAttribute(i)}}function vn(t){switch(t){case R.Mask:return"rgba(255, 255, 255, 0.5)";case R.Highlight:case R.HighlightUnderline:return"#FFFF00";default:return"#FF0000"}}const R={Highlight:"highlight",HighlightUnderline:"highlightUnderline",Underline:"underline",Strikethrough:"strikethrough",Outline:"outline",TextColor:"textColor",Mask:"mask",Template:"template"};var sa=(t=>(t.Wrap="wrap",t.Viewport="viewport",t.Bounds="bounds",t.Page="page",t))(sa||{}),aa=(t=>(t.Boxes="boxes",t.Bounds="bounds",t))(aa||{});const Xh=()=>"Highlight"in window,ki=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Yh{constructor(e,n,r,i){this.wnd=e,this.comms=n,this.id=r,this.name=i,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,Xh()&&(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 n=this.hoveredItem.range.getBoundingClientRect(),r=this.wnd.devicePixelRatio;this.comms.send("decoration_pointer_leave",{decorationId:this.hoveredItem.decoration.id,group:this.name,rect:{top:n.top*r,left:n.left*r,width:n.width*r,height:n.height*r}}),this.hoveredItem=void 0}}add(e){const n=`${this.id}-${this.lastItemId++}`,r=qh(this.wnd.document,e.locator);if(!r){this.comms.log("Can't locate DOM range for decoration",e);return}const i=r.commonAncestorContainer;if(i.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(ki.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(n,!0),r.cloneContents().querySelector(ki.join(", ").toLowerCase())&&this.notTextFlag?.set(n,!0),(i.textContent?.trim()||"").length===0&&this.notTextFlag?.set(n,!0)),this.experimentalHighlights&&!this.notTextFlag?.has(n)){const o=a=>{for(;a&&a.nodeType===Node.ELEMENT_NODE;){if(a.namespaceURI?.includes("svg"))return!0;a=a.parentNode}return!1};(o(r.startContainer)||o(r.endContainer))&&this.notTextFlag?.set(n,!0)}if(this.experimentalHighlights){const{type:o}=e.style,{layout:a,width:c,expand:l}=e.style;o!==R.TextColor&&(o===R.Outline||o===R.Template||o===R.Mask||a!==void 0&&a!=="boxes"||c!==void 0&&c!=="wrap"||l)&&this.notTextFlag?.set(n,!0)}const s={decoration:e,id:n,range:r,hitRects:[],clickableElements:void 0,container:void 0};this.items.push(s),this.layout(s),s.hitRects=this.clientRectsToDocCoords(Je(s.range,!1,!1,(s.decoration.style.expand??0)+this.hitGap())),this.renderLayout([s])}remove(e){const n=this.items.findIndex(s=>s.decoration.id===e);if(n<0)return;const r=this.items[n],i=r.decoration.style?.type===R.Mask;if(this.items.splice(n,1),r.clickableElements=void 0,r.container&&(r.container.remove(),r.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(r.id)&&r.highlightSubKey){const s=this.wnd.CSS.highlights;s.get(r.highlightSubKey)?.delete(r.range),this.items.some(a=>a.highlightSubKey===r.highlightSubKey)||s.delete(r.highlightSubKey);const o=this.wnd.document.getElementById(`${this.id}-style`);o&&this._rebuildHighlightStylesheet(o)}this.notTextFlag?.delete(r.id),this.hoveredItem===r&&(this.hoveredItem=void 0),i&&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,n=Ee(this.wnd)){const r=n.xDocOffset,i=n.yDocOffset;return r===0&&i===0?e:e.map(s=>({left:s.left+r,top:s.top+i,right:s.right+r,bottom:s.bottom+i,width:s.width,height:s.height}))}pointerToDocCoords(e){const n=Ee(this.wnd);return{docX:e.clientX+n.xDocOffset,docY:e.clientY+n.yDocOffset}}effectiveZoom(){if(!nh.UA.Blink)return 1;const e=parseFloat(this.wnd.getComputedStyle(this.wnd.document.documentElement).zoom),n=parseFloat(this.wnd.getComputedStyle(this.wnd.document.body).zoom);return(e||1)*(n||1)}hitGap(){return 2*this.effectiveZoom()}handleActivation(e){if(!this._activatable)return;const{docX:n,docY:r}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;for(const s of this.items){let o;if(s.decoration.style.type===R.Template)for(const a of s.clickableElements??[]){const c=a.getBoundingClientRect();if(oe(c,e.clientX,e.clientY,0)){o=c;break}}else for(const a of s.hitRects)if(oe(a,n,r,0)){o=s.range.getBoundingClientRect();break}if(o){this.comms.send("decoration_activated",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}});return}}}handleHover(e){if(!this._hoverable)return;const{docX:n,docY:r}=this.pointerToDocCoords(e),i=this.wnd.devicePixelRatio;let s,o;for(const a of this.items){if(a.decoration.style.type===R.Template)for(const c of a.clickableElements??[]){const l=c.getBoundingClientRect();if(oe(l,e.clientX,e.clientY,0)){s=a,o=l;break}}else for(const c of a.hitRects)if(oe(c,n,r,0)){s=a,o=a.range.getBoundingClientRect();break}if(s)break}if(s!==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*i,left:a.left*i,width:a.width*i,height:a.height*i}:void 0,point:{x:e.clientX*i,y:e.clientY*i}})}this.hoveredItem=s,s&&o&&this.comms.send("decoration_pointer_enter",{decorationId:s.decoration.id,group:this.name,rect:{top:o.top*i,left:o.left*i,width:o.width*i,height:o.height*i},point:{x:e.clientX*i,y:e.clientY*i}})}}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(Je(e.range,!1,!1,(e.decoration.style.expand??0)+this.hitGap()))}),this.renderLayout(this.items),this.updateSharedMask()})})}repositionOverlays(){let e=!1;const n=[],r=Ee(this.wnd);this.items.forEach(i=>{if(!(this.experimentalHighlights&&!this.notTextFlag?.has(i.id))){if(i.decoration.style?.type===R.Mask){e=!0;return}this.repositionItem(i,r)||(i.container?.remove(),this.layout(i),n.push(i)),i.hitRects=this.clientRectsToDocCoords(Je(i.range,!1,!1,(i.decoration.style.expand??0)+this.hitGap()),r)}}),n.length&&this.renderLayout(n),e&&this.updateSharedMask()}experimentalLayout(e){const n=this.requireContainer(!0),r=this.wnd.CSS.highlights,i=e.decoration.style,s=i.type??R.Highlight,o=i.tint??vn(s),a=i.width,c=i.layout,l=this._getSubKey(s,o);e.highlightSubKey&&(r.get(e.highlightSubKey)?.delete(e.range),e.highlightSubKey!==l&&!this.items.some(m=>m!==e&&m.highlightSubKey===e.highlightSubKey)&&r.delete(e.highlightSubKey)),e.highlightSubKey=l;let u;r.has(l)?u=r.get(l):(u=new this.wnd.Highlight,r.set(l,u));const h=(m,b)=>this.wnd.document.caretPositionFromPoint?.(m,b)??null;if(s===R.TextColor&&(c==="bounds"||a==="bounds"||a==="page")){const m=Ee(this.wnd);if(m.isVertical)console.warn("Vertical writing detected: caretPositionFromPoint has known bugs, falling back to original range"),u.add(e.range);else{const b=e.range.getBoundingClientRect();let x,A;a==="page"?(x=Math.floor(m.inlineStart(b)/m.pageInlineSize)*m.pageInlineSize,A=m.pageInlineSize):(x=m.inlineStart(b),A=m.inlineSize(b));const S=h(x,m.blockStart(b)+1),w=h(x+A,m.blockStart(b)+m.blockSize(b)-1);if(S&&w){const T=this.wnd.document.createRange();T.setStart(S.offsetNode,S.offset),T.setEnd(w.offsetNode,w.offset),u.add(T),e.range=T}else u.add(e.range)}}else u.add(e.range);const d=this.getBackgroundColor(),g=i.enforceContrast!==!1?ke(o,d):o;let p;switch(s){case R.Underline:p=`::highlight(${l}) {
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(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&nbsp;/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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),jt=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),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("&lt;",s)?"<":n.startsWith("&gt;",s)?">":n.startsWith("&amp;",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(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/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(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/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}) {
28
2
  text-decoration: underline;
29
- text-decoration-color: ${g};
3
+ text-decoration-color: ${f};
30
4
  text-decoration-thickness: 0.1em;
31
- }`;break;case R.Strikethrough:p=`::highlight(${l}) {
5
+ }`;break;case E.Strikethrough:g=`::highlight(${c}) {
32
6
  text-decoration: line-through;
33
- text-decoration-color: ${g};
7
+ text-decoration-color: ${f};
34
8
  text-decoration-thickness: 0.1em;
35
- }`;break;case R.Outline:p=`::highlight(${l}) {
36
- outline: 2px solid ${g};
9
+ }`;break;case E.Outline:g=`::highlight(${c}) {
10
+ outline: 2px solid ${f};
37
11
  outline-offset: 1px;
38
- }`;break;case R.TextColor:p=`::highlight(${l}) {
39
- color: ${g};
40
- }`;break;case R.HighlightUnderline:{const{r:m,g:b,b:x}=be(g),A=`rgba(${m}, ${b}, ${x}, 0.3)`;p=`::highlight(${l}) {
41
- color: ${oi(g,d)};
42
- background-color: ${A};
12
+ }`;break;case E.TextColor:g=`::highlight(${c}) {
13
+ color: ${f};
14
+ }`;break;case E.HighlightUnderline:{const{r:p,g:m,b:y}=ce(f),w=`rgba(${p}, ${m}, ${y}, 0.3)`;g=`::highlight(${c}) {
15
+ color: ${yi(f,d)};
16
+ background-color: ${w};
43
17
  text-decoration: underline;
44
- text-decoration-color: ${g};
18
+ text-decoration-color: ${f};
45
19
  text-decoration-thickness: 0.1em;
46
- }`;break}case R.Highlight:default:p=`::highlight(${l}) {
47
- color: ${oi(g,d)};
48
- background-color: ${g};
49
- }`}e.highlightCSS=p,this._rebuildHighlightStylesheet(n)}_getSubKey(e,n){const r=`${e}::${n}`;let i=this._tintSubKeys.get(r);return i||(i=`${this.id}--${this._subKeyCounter++}`,this._tintSubKeys.set(r,i)),i}_rebuildHighlightStylesheet(e){const n=new Set,r=[];for(const i of this.items)i.highlightSubKey&&i.highlightCSS&&!n.has(i.highlightSubKey)&&(n.add(i.highlightSubKey),r.push(i.highlightCSS));e.innerHTML=r.join(`
50
- `)}positionElement(e,n,r,i,s,o,a=0){const c=e.decoration?.style?.width,l=s;switch(c){case"viewport":{const u=Math.floor(n.inlineStart(l)/n.viewportInlineSize)*n.viewportInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.viewportInlineSize-2*a,n.blockSize(l),r);break}case"page":{const u=Math.floor(n.inlineStart(l)/n.pageInlineSize)*n.pageInlineSize;n.applyPosition(i,u+n.inlineScrollOffset+a,n.blockStart(l)+n.blockScrollOffset,n.pageInlineSize-2*a,n.blockSize(l),r);break}case"bounds":{n.applyPosition(i,n.inlineStart(o)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(o),n.blockSize(l),r);break}default:n.applyPosition(i,n.inlineStart(l)+n.inlineScrollOffset,n.blockStart(l)+n.blockScrollOffset,n.inlineSize(l),n.blockSize(l),r)}}computeOverlayRects(e,n,r,i){if(e.decoration?.style?.layout==="bounds")return[i?{left:r.left-i,right:r.right+i,top:r.top-i,bottom:r.bottom+i,width:r.width+i*2,height:r.height+i*2}:r];const s=e.decoration.style.type,o=s===R.Underline||s===R.Strikethrough,a=s===R.Strikethrough,c=o?Uh(e.range,["rt","rp"]):e.range;let l=Je(c,!0,n.isVertical,o?0:i);return l=l.sort((u,h)=>n.isVertical?(n.isVertLR?1:-1)*(u.left-h.left):u.top-h.top),l.map(u=>{let h=u;if(a){const d=n.blockSize(u)*.1,g=n.blockStart(u)+n.blockSize(u)/2-d/2;h=n.isVertical?{left:g,right:g+d,top:u.top,bottom:u.bottom,width:d,height:u.height}:{top:g,bottom:g+d,left:u.left,right:u.right,height:d,width:u.width}}return i&&o&&(h=n.isVertical?{...h,top:h.top-i,bottom:h.bottom+i,height:h.height+i*2}:{...h,left:h.left-i,right:h.right+i,width:h.width+i*2}),h})}repositionItem(e,n){if(!e.container)return!0;const r=e.decoration.style;if(r.type!==R.Template){const u=r.type??R.Highlight;if(u===R.TextColor||u===R.Mask)return!0}const i=1/this.effectiveZoom(),s=r.expand??0,o=e.range.getBoundingClientRect(),a=(()=>{if(r.type!==R.Outline)return 0;const u=r.width;return u==="page"||u==="viewport"?3:0})(),c=this.computeOverlayRects(e,n,o,s),l=Array.from(e.container.children);return l.length!==c.length?!1:(l.forEach((u,h)=>this.positionElement(e,n,i,u,c[h],o,a)),!0)}layout(e){if(this.experimentalHighlights&&!this.notTextFlag?.has(e.id))return this.experimentalLayout(e);const n=this.wnd.document.createElement("div");n.setAttribute("id",e.id),n.dataset.highlightId=e.decoration.id,n.style.setProperty("pointer-events","none");const r=Ee(this.wnd),i=1/this.effectiveZoom(),s=e.decoration.style.expand??0,o=e.range.getBoundingClientRect(),a=e.decoration.style,c=(()=>{if(a.type!==R.Outline)return 0;const h=a.width;return h==="page"||h==="viewport"?3:0})();let l;if(a.type===R.Template){a.stylesheet&&this.injectCustomStylesheet(a.stylesheet);const h=Kh(this.wnd,a.element);if(!h){e.container=n,e.clickableElements=[];return}h.style.setProperty("pointer-events","none"),l=h}else{const h=a,d=h.type??R.Highlight,g=h.tint??vn(d);if(d===R.TextColor){e.container=n,e.clickableElements=[];return}if(d===R.Mask){e.container=n,e.clickableElements=[],this.updateSharedMask();return}const p=this.getCurrentDarkMode(),m=this.getBackgroundColor(),b=h.enforceContrast!==!1,x=(()=>{switch(d){case R.Underline:{const S=b?ke(g,m):g,w=h.layout==="bounds",[T,F]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[w?`${F}: 0.1em solid ${S} !important`:null,`${T}: 0.1em solid ${S} !important`,"background-color: transparent !important","box-sizing: border-box !important"].filter(Boolean).join("; ")}case R.Strikethrough:{const S=b?ke(g,m):g;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 R.Outline:return[`outline: 2px solid ${b?ke(g,m):g} !important`,"outline-offset: 1px !important","background-color: transparent !important","box-sizing: border-box !important"].join("; ");case R.HighlightUnderline:{const S=b?ke(g,m):g,{r:w,g:T,b:F}=be(S),L=`rgba(${w}, ${T}, ${F}, 0.3)`,X=h.layout==="bounds",[M,y]=r.isVertical?["border-right","border-left"]:["border-bottom","border-top"];return[`background-color: ${L} !important`,X?`${y}: 0.1em solid ${S} !important`:null,`${M}: 0.1em solid ${S} !important`,"box-sizing: border-box !important"].filter(Boolean).join("; ")}case R.Highlight:default:return[`background-color: ${b?ke(g,m):g} !important`,`mix-blend-mode: ${p?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important","transform: translateZ(0) !important"].join("; ")}})(),A=this.wnd.document.createElement("template");A.innerHTML=`<div data-readium="true" class="readium-${d}" style="${x}"></div>`.trim(),l=A.content.firstElementChild}const u=this.computeOverlayRects(e,r,o,s);for(const h of u){const d=l.cloneNode(!0);d.style.setProperty("pointer-events","none"),this.positionElement(e,r,i,d,h,o,c),n.append(d)}e.container=n,e.clickableElements=Array.from(n.querySelectorAll("[data-activable='1']")),e.clickableElements.length||(e.clickableElements=Array.from(n.children))}renderLayout(e){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{e=e.filter(n=>!this.experimentalHighlights||!!this.notTextFlag?.has(n.id)),!(!e||e.length===0)&&this.requireContainer().append(...e.map(n=>n.container).filter(n=>!!n))})}requireContainer(e=!1){if(e){let n;return this.wnd.document.getElementById(`${this.id}-style`)?n=this.wnd.document.getElementById(`${this.id}-style`):(n=this.wnd.document.createElement("style"),n.dataset.readium="true",n.id=`${this.id}-style`,this.wnd.document.head.appendChild(n)),n}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 ai(this.wnd,"--USER__appearance")==="readium-night-on"||Is(this.getBackgroundColor())}getBackgroundColor(){return ai(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===R.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 n=Ee(this.wnd),r=1/this.effectiveZoom(),i=this.wnd.document.documentElement,s=i.scrollWidth,o=i.scrollHeight,a=[];for(const d of e){const g=d.decoration.style,p=g.layout??"boxes",m=g.width??"wrap",b=g.expand??0,x=d.range.getBoundingClientRect(),A=p==="bounds"?[b?{left:x.left-b,top:x.top-b,right:x.right+b,bottom:x.bottom+b,width:x.width+b*2,height:x.height+b*2}:x]:Je(d.range,!1,!1,b);for(const S of A){let w;switch(m){case"viewport":{const T=Math.floor(n.inlineStart(S)/n.viewportInlineSize)*n.viewportInlineSize;w=n.toRect(T,n.blockStart(S),n.viewportInlineSize,n.blockSize(S));break}case"page":{const T=Math.floor(n.inlineStart(S)/n.pageInlineSize)*n.pageInlineSize;w=n.toRect(T,n.blockStart(S),n.pageInlineSize,n.blockSize(S));break}case"bounds":{w=n.toRect(n.inlineStart(x),n.blockStart(S),n.inlineSize(x),n.blockSize(S));break}default:w=n.toRect(n.inlineStart(S),n.blockStart(S),n.inlineSize(S),n.blockSize(S))}a.push(w)}}const c=[`M0 0 H${s} V${o} H0 Z`,...a.map(d=>{const g=(d.left+n.xDocOffset)*r,p=(d.top+n.yDocOffset)*r,m=(d.right+n.xDocOffset)*r,b=(d.bottom+n.yDocOffset)*r;return`M${g} ${p} H${m} V${b} H${g} Z`})].join(" "),l="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(l,"svg"),this.maskSvg.style.cssText=`position:absolute;top:0;left:0;width:${s}px;height:${o}px;pointer-events:none;z-index:9999`,this.maskSvg.dataset.readium="true";const d=this.wnd.document.createElementNS(l,"defs"),g=this.wnd.document.createElementNS(l,"clipPath"),p=`${this.id}-mask-clip`;g.setAttribute("id",p),g.setAttribute("clipPathUnits","userSpaceOnUse");const m=this.wnd.document.createElementNS(l,"path");m.setAttribute("clip-rule","evenodd"),g.appendChild(m),d.appendChild(g),this.maskSvg.appendChild(d);const b=this.wnd.document.createElementNS(l,"rect");b.setAttribute("id",`${this.id}-mask-rect`),b.setAttribute("clip-path",`url(#${p})`),b.style.pointerEvents="none",this.maskSvg.appendChild(b),this.shadowRoot.appendChild(this.maskSvg)}this.maskSvg.style.width=`${s}px`,this.maskSvg.style.height=`${o}px`;const u=this.maskSvg.querySelector("path");u&&u.setAttribute("d",c);const h=this.maskSvg.querySelector("rect");if(h){const d=e[0].decoration.style.tint,g=d??this.getBackgroundColor()??vn(R.Mask),p=d?"1":"0.5";h.setAttribute("x","0"),h.setAttribute("y","0"),h.setAttribute("width",String(s)),h.setAttribute("height",String(o)),h.setAttribute("fill",g),h.setAttribute("fill-opacity",p)}}injectCustomStylesheet(e){const n=`${this.id}-custom-style`;let r=this.wnd.document.getElementById(n);r||(r=this.wnd.document.createElement("style"),r.id=n,r.dataset.readium="true",this.wnd.document.head.appendChild(r)),r.innerHTML=e}clearContainer(){if(this.experimentalHighlights){const e=this.wnd.CSS.highlights;for(const n of this._tintSubKeys.values())e.delete(n);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 oa=class Re extends Hu{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,n){return this.wnd=e,n.register("decorate",Re.moduleName,(r,i)=>{const s=r;(s.action==="add"||s.action==="update")&&s.decoration.locator&&(s.decoration.locator=Sr.deserialize(s.decoration.locator)),this.groups.has(s.group)||this.groups.set(s.group,new Yh(e,n,`readium-decoration-${this.lastGroupId++}`,s.group));const o=this.groups.get(s.group);switch(s.action){case"add":o?.add(s.decoration);break;case"remove":o?.remove(s.decoration.id);break;case"clear":o?.clear();break;case"update":o?.update(s.decoration);break}i(!0)}),n.register("decoration_resize",Re.moduleName,(r,i)=>{const s=r;s.action==="watch"?this.addDecorationResizeTarget(s.selector):this.removeDecorationResizeTarget(s.selector),i(!0)}),n.register("decoration_activatable",Re.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.activatable=s.activatable),i(!0)}),n.register("decoration_hoverable",Re.moduleName,(r,i)=>{const s=r,o=this.groups.get(s.group);o&&(o.hoverable=s.hoverable),i(!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(r=>{r.some(i=>i.type==="attributes"&&i.attributeName==="style"&&i.oldValue!==i.target.getAttribute("style"))&&this.updateHighlightStyles()}),this.styleObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0}),n.log("Decorator Mounted"),!0}unmount(e,n){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),e.removeEventListener("scroll",this.handleScroller,{capture:!0}),n.unregisterAll(Re.moduleName),this.resizeObserver.disconnect(),this.styleObserver.disconnect(),this.cleanup(),n.log("Decorator Unmounted"),!0}addDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&this.resizeObserver.unobserve(n);const r=this.wnd.document.querySelector(e);r?(this.resizeObserver.observe(r),this.observedResizeTargets.set(e,r)):this.observedResizeTargets.delete(e)}removeDecorationResizeTarget(e){const n=this.observedResizeTargets.get(e);n&&(this.resizeObserver.unobserve(n),this.observedResizeTargets.delete(e))}};oa.moduleName="decorator";let la=oa;const ca=new Set(Object.values(R));function ua(t,e){return t===R.TextColor?typeof window<"u"&&"Highlight"in window:ca.has(t)?!0:!!e?.[t]}function jn(t,e){const{style:n}=t;if(n.type===R.Template){const r=n;return{...t,style:{...r,element:Oi(r,t)}}}if(n.type&&e?.[n.type]){const r=e[n.type];return{...t,style:{type:R.Template,layout:r.layout,width:r.width,stylesheet:r.stylesheet,element:Oi(r,t)}}}return t}function Oi(t,e){return typeof t.element=="function"?t.element(e):t.element}function Qh(t,e){if(t.type!==e.type)return!1;if(t.type===R.Template){const i=t,s=e;return i.layout===s.layout&&i.width===s.width&&i.stylesheet===s.stylesheet}const n=t,r=e;return n.tint===r.tint&&n.layout===r.layout&&n.width===r.width&&(n.enforceContrast??!0)===(r.enforceContrast??!0)&&(n.expand??0)===(r.expand??0)}function ha(t,e){return t.locator.href===e.locator.href&&JSON.stringify(t.locator.locations?.serialize?.()??t.locator.locations)===JSON.stringify(e.locator.locations?.serialize?.()??e.locator.locations)&&JSON.stringify(t.locator.text??null)===JSON.stringify(e.locator.text??null)&&Qh(t.style,e.style)&&JSON.stringify(t.extras??null)===JSON.stringify(e.extras??null)}class da{constructor(){this.queue=[],this.channel=typeof MessageChannel<"u"?new MessageChannel:void 0,this.channel&&(this.channel.port1.onmessage=()=>this.flush())}push(e){const n=this.queue.length===0;this.queue.push(e),n&&(this.channel?this.channel.port2.postMessage(null):setTimeout(()=>this.flush(),0))}flush(){const e=this.queue;this.queue=[],e.forEach(n=>n())}clear(){this.queue=[]}}class fa{constructor(){this.frame=new ga(this),this.host=new pa(this)}}class ga{constructor(e){this.channel=e,this.registrar=new Map,this.outbox=new da,this.ready=!0}register(e,n,r){(Array.isArray(e)?e:[e]).forEach(i=>{const s=this.registrar.get(i)??[];if(s.find(o=>o.module===n))throw new Error(`Duplicate callback for "${i}" in module "${n}"`);s.push({module:n,cb:r}),this.registrar.set(i,s)})}unregister(e,n){(Array.isArray(e)?e:[e]).forEach(r=>{const i=this.registrar.get(r);i&&this.registrar.set(r,i.filter(s=>s.module!==n))})}unregisterAll(e){this.registrar.forEach((n,r)=>{this.registrar.set(r,n.filter(i=>i.module!==e))})}_dispatch(e,n,r){const i=this.registrar.get(e);if(!i?.length){r(!1);return}i.forEach(s=>s.cb(n,r))}send(e,n){this.outbox.push(()=>this.channel.host._receive(e,n))}log(...e){this.outbox.push(()=>this.channel.host._receive("log",e))}destroy(){this.registrar.clear(),this.outbox.clear()}}class pa{constructor(e){this.channel=e,this.listeners=new Map,this.outbox=new da,this.ready=!0}send(e,n,r){this.outbox.push(()=>this.channel.frame._dispatch(e,n,r??(()=>{})))}on(e,n){const r=this.listeners.get(e)??[];r.push(n),this.listeners.set(e,r)}off(e,n){const r=this.listeners.get(e);r&&this.listeners.set(e,r.filter(i=>i!==n))}_receive(e,n){this.listeners.get(e)?.forEach(r=>r(n))}}class ma{constructor(e,n={}){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=n,n.resizeWatchSelectors?.forEach(r=>this.addDecorationResizeTarget(r)),e.on("decoration_activated",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationActivated?.({group:i.group,decoration:s,rect:i.rect,point:i.point}))}),e.on("decoration_pointer_enter",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId);s&&(this._hoveredDecorations.set(i.group,s),this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerEnter?.({group:i.group,decoration:s,rect:i.rect,point:i.point})))}),e.on("decoration_pointer_leave",r=>{const i=r,s=this._decorations.get(i.group)?.find(o=>o.id===i.decorationId)??this._hoveredDecorations.get(i.group);this._hoveredDecorations.delete(i.group),s&&this._observers.get(i.group)?.forEach(o=>o.onDecorationPointerLeave?.({group:i.group,decoration:s,rect:i.rect,point:i.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 ua(e,this._config.decorationTemplates)}applyDecorations(e,n){const r=this._decorations.get(n)??[],i=new Map(r.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id,c]));for(const[c,l]of i){const u=s.get(c);u?ha(l,u)||this.host.send("decorate",{group:n,action:"update",decoration:jn(u,this._config.decorationTemplates)}):this.host.send("decorate",{group:n,action:"remove",decoration:{id:c}})}for(const[c,l]of s)i.has(c)||this.host.send("decorate",{group:n,action:"add",decoration:jn(l,this._config.decorationTemplates)});this._decorations.set(n,e);const o=this._activationState.get(n);o!==void 0&&this.host.send("decoration_activatable",{group:n,activatable:o});const a=this._hoverState.get(n);a!==void 0&&this.host.send("decoration_hoverable",{group:n,hoverable:a})}registerDecorationObserver(e,n){this._observers.has(e)||this._observers.set(e,new Set),this._observers.get(e).add(n),n.onDecorationActivated&&(this._activationState.set(e,!0),this.host.send("decoration_activatable",{group:e,activatable:!0})),(n.onDecorationPointerEnter||n.onDecorationPointerLeave)&&(this._hoverState.set(e,!0),this.host.send("decoration_hoverable",{group:e,hoverable:!0}))}unregisterDecorationObserver(e){this._observers.forEach((n,r)=>{if(!n.has(e))return;n.delete(e);const i=[...n].some(o=>o.onDecorationActivated);this._activationState.has(r)&&!i&&(this._activationState.delete(r),this.host.send("decoration_activatable",{group:r,activatable:!1}));const s=[...n].some(o=>o.onDecorationPointerEnter||o.onDecorationPointerLeave);this._hoverState.has(r)&&!s&&(this._hoverState.delete(r),this.host.send("decoration_hoverable",{group:r,hoverable:!1}))})}destroy(){this._decorations.clear(),this._activationState.clear(),this._hoverState.clear(),this._observers.clear(),this._hoveredDecorations.clear()}}function Zh(t){return new Ds({start:new It(t.start),end:t.end?new It(t.end):void 0})}function ya(t,e=window){const{text:n,cssSelector:r,domRange:i,fragment:s}=t,o=n?new br(n):void 0,a=r||i?new Map:void 0;a&&(r&&a.set("cssSelector",r),i&&a.set("domRange",Zh(i).serialize()));const l=a!==void 0||s!==void 0?new ue({fragments:s?[s]:void 0,otherLocations:a}):void 0;return new Sr({href:e.location.href,type:"text/html",text:o,locations:l})}class ba extends ma{constructor(e,n,r,i={}){super(e.host,i),this.channel=e,this.wnd=n,this.decorator=r}decorate(e,n){this.applyDecorations(e.map(({id:r,style:i,...s})=>({id:r,style:i,locator:ya(s,this.wnd)})),n)}destroy(){super.destroy(),this.decorator.unmount(this.wnd,this.channel.frame),this.channel.frame.destroy()}}function ed(t=window,e={}){const n=new fa,r=new la;return r.mount(t,n.frame),new ba(n,t,r,e)}class td{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,n){return this.require(e).createEngine(n)}async destroy(){await Promise.all(this.list().map(e=>e.destroy())),this.providers.clear()}require(e){const n=this.providers.get(e);if(!n)throw new Error(`No provider registered under id "${e}"`);return n}}const Lt={range:[0,5e3],step:100},$t={range:[.1,10],step:.1},_t={range:[0,2],step:.1},Bt={range:[0,1],step:.05},vr=["none","few","some","most","custom"],wr=["none","block-level","always"],xr=["plain","ssml"],Er=["none","utterance","block"],Ai=["format","inlineContextualization","verbosity","skip","contextualize","language"];function Cr(t){return t==null||typeof t=="boolean"?t:void 0}function re(t,e){return t==null||e.includes(t)?t:void 0}function ie(t,e){if(t==null)return t;if(typeof t!="number"||Number.isNaN(t))return;const n=Math.min(...e),r=Math.max(...e);return t>=n&&t<=r?t:void 0}function at(t){return t==null||Array.isArray(t)&&t.every(e=>typeof e=="string")?t:void 0}class Sa{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=re(e.format,xr)??"plain",this.inlineContextualization=Cr(e.inlineContextualization)??!1,this.verbosity=re(e.verbosity,vr)??"few",this.skip=at(e.skip)??[],this.contextualize=at(e.contextualize)??[],this.language=re(e.language,wr)??"block-level",this.pauseDuration=ie(e.pauseDuration,Lt.range)??300,this.autoPause=re(e.autoPause,Er)??"none",this.rate=ie(e.rate,$t.range)??1,this.pitch=ie(e.pitch,_t.range)??1,this.volume=ie(e.volume,Bt.range)??1}}class Ue{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e={}){this.format=re(e.format,xr),this.inlineContextualization=Cr(e.inlineContextualization),this.verbosity=re(e.verbosity,vr),this.skip=at(e.skip),this.contextualize=at(e.contextualize),this.language=re(e.language,wr),this.pauseDuration=ie(e.pauseDuration,Lt.range),this.autoPause=re(e.autoPause,Er),this.rate=ie(e.rate,$t.range),this.pitch=ie(e.pitch,_t.range),this.volume=ie(e.volume,Bt.range)}merging(e){const n={...this};for(const r of Object.keys(e))e[r]!==void 0&&(n[r]=e[r]);return new Ue(n)}}class ht{_value;_effectiveValue;_isEffective;_onChange;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i}){this._value=e,this._effectiveValue=n,this._isEffective=r,this._onChange=i}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 tt extends ht{_supportedValues;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i,supportedValues:s}){super({initialValue:e,effectiveValue:n,isEffective:r,onChange:i}),this._supportedValues=s}set value(e){if(e!=null&&re(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 va extends ht{set value(e){if(e!=null&&Cr(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 Hn extends ht{set value(e){if(e!=null&&at(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 nt extends ht{_supportedRange;_step;_decimals;constructor({initialValue:e=null,effectiveValue:n,isEffective:r,onChange:i,supportedRange:s,step:o}){super({initialValue:e,effectiveValue:n,isEffective:r,onChange:i}),this._supportedRange=s,this._step=o,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e!=null&&ie(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 Wn{preferences;settings;constructor(e,n){this.preferences=new Ue({...e}),this.settings=n}clear(){this.preferences=new Ue({format:null,inlineContextualization:null,verbosity:null,skip:null,contextualize:null,language:null,pauseDuration:null,autoPause:null,rate:null,pitch:null,volume:null})}updatePreference(e,n){this.preferences[e]=n}get format(){return new tt({initialValue:this.preferences.format,effectiveValue:this.settings.format,isEffective:this.preferences.format!=null,onChange:e=>this.updatePreference("format",e??null),supportedValues:xr})}get inlineContextualization(){return new va({initialValue:this.preferences.inlineContextualization,effectiveValue:this.settings.inlineContextualization,isEffective:this.preferences.inlineContextualization!=null,onChange:e=>this.updatePreference("inlineContextualization",e??null)})}get verbosity(){return new tt({initialValue:this.preferences.verbosity,effectiveValue:this.settings.verbosity,isEffective:this.preferences.verbosity!=null,onChange:e=>this.updatePreference("verbosity",e??null),supportedValues:vr})}get skip(){return new Hn({initialValue:this.preferences.skip,effectiveValue:this.settings.skip,isEffective:this.preferences.skip!=null,onChange:e=>this.updatePreference("skip",e??null)})}get contextualize(){return new Hn({initialValue:this.preferences.contextualize,effectiveValue:this.settings.contextualize,isEffective:this.preferences.contextualize!=null,onChange:e=>this.updatePreference("contextualize",e??null)})}get language(){return new tt({initialValue:this.preferences.language,effectiveValue:this.settings.language,isEffective:this.preferences.language!=null,onChange:e=>this.updatePreference("language",e??null),supportedValues:wr})}get pauseDuration(){return new nt({initialValue:this.preferences.pauseDuration,effectiveValue:this.settings.pauseDuration,isEffective:this.preferences.pauseDuration!=null,onChange:e=>this.updatePreference("pauseDuration",e??null),supportedRange:Lt.range,step:Lt.step})}get autoPause(){return new tt({initialValue:this.preferences.autoPause,effectiveValue:this.settings.autoPause,isEffective:this.preferences.autoPause!=null,onChange:e=>this.updatePreference("autoPause",e??null),supportedValues:Er})}get rate(){return new nt({initialValue:this.preferences.rate,effectiveValue:this.settings.rate,isEffective:this.preferences.rate!=null,onChange:e=>this.updatePreference("rate",e??null),supportedRange:$t.range,step:$t.step})}get pitch(){return new nt({initialValue:this.preferences.pitch,effectiveValue:this.settings.pitch,isEffective:this.preferences.pitch!=null,onChange:e=>this.updatePreference("pitch",e??null),supportedRange:_t.range,step:_t.step})}get volume(){return new nt({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!=null,onChange:e=>this.updatePreference("volume",e??null),supportedRange:Bt.range,step:Bt.step})}}const wa=["audio","figure","image","math","table","video"],xa=[...wa,"blockquote","chapter","cover","details","notice","part","preformatted","qna","row","rowheader","subtitle","tip"],nd=[...xa,"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"],Ea={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"])},Ca={none:new Set,few:new Set(wa),some:new Set(xa),most:new Set(nd)},Gn={table:{few:"inline",some:"block",most:"block"}};function wt(t){const e={};for(const n of Object.keys(Gn))e[n]=Gn[n]?.[t]??"inline";return e}const ka={none:wt("none"),few:wt("few"),some:wt("some"),most:wt("most")},rd=Object.keys(Gn);function id(t,e){const n=t==="custom"?{}:ka[t];if(!e)return n;const r={...n};for(const i of Object.keys(e)){const s=e[i]?.[t];s&&(r[i]=s)}return r}class Kn{format;inlineContextualization;verbosity;skip;contextualize;language;pauseDuration;autoPause;rate;pitch;volume;constructor(e,n){this.format=e.format??n.format,this.inlineContextualization=e.inlineContextualization??n.inlineContextualization,this.verbosity=e.verbosity??n.verbosity,this.verbosity==="custom"?(this.skip=e.skip??n.skip,this.contextualize=e.contextualize??n.contextualize):(this.skip=[...Ea[this.verbosity]],this.contextualize=[...Ca[this.verbosity]]),this.language=e.language??n.language,this.pauseDuration=e.pauseDuration??n.pauseDuration,this.autoPause=e.autoPause??n.autoPause,this.rate=e.rate??n.rate,this.pitch=e.pitch??n.pitch,this.volume=e.volume??n.volume}}const O=t=>typeof t=="string",Xe=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},Ti=t=>t==null?"":String(t),sd=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},ad=/###/g,Ri=t=>t&&t.includes("###")?t.replace(ad,"."):t,Ni=t=>!t||O(t),rt=(t,e,n)=>{const r=O(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(Ni(t))return{};const s=Ri(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return Ni(t)?{}:{obj:t,k:Ri(r[i])}},Di=(t,e,n)=>{const{obj:r,k:i}=rt(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),a=rt(t,o,Object);for(;a.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),a=rt(t,o,Object),a?.obj&&typeof a.obj[`${a.k}.${s}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${s}`]=n},od=(t,e,n,r)=>{const{obj:i,k:s}=rt(t,e,Object);i[s]=i[s]||[],i[s].push(n)},qt=(t,e)=>{const{obj:n,k:r}=rt(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},ld=(t,e,n)=>{const r=qt(t,n);return r!==void 0?r:qt(e,n)},Oa=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(Object.prototype.hasOwnProperty.call(t,r)?O(t[r])||t[r]instanceof String||O(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):Oa(t[r],e[r],n):t[r]=e[r]);return t},ee=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),cd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},ud=t=>O(t)?t.replace(/[&<>"'\/]/g,e=>cd[e]):t;class hd{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const dd=[" ",",","?","!",";"],fd=new hd(20),gd=(t,e,n)=>{e=e||"",n=n||"";const r=dd.filter(o=>!e.includes(o)&&!n.includes(o));if(r.length===0)return!0;const i=fd.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!i.test(t);if(!s){const o=t.indexOf(n);o>0&&!i.test(t.substring(0,o))&&(s=!0)}return s},Jn=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let o,a="";for(let c=s;c<r.length;++c)if(c!==s&&(a+=n),a+=r[c],o=i[a],o!==void 0){if(["string","number","boolean"].includes(typeof o)&&c<r.length-1)continue;s+=c-s+1;break}i=o}return i},ot=t=>t?.replace(/_/g,"-"),pd={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ut{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||pd,this.options=n,this.debug=n.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,n,r,i){return i&&!this.debug?null:(e=e.map(s=>O(s)?s.replace(/[\r\n\x00-\x1F\x7F]/g," "):s),O(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ut(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ut(this.logger,e)}}var Q=new Ut;class en{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let o=0;o<s;o++)i(e,...n)})}}class Fi extends en{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,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 n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.includes(".")?a=e.split("."):(a=[e,n],r&&(Array.isArray(r)?a.push(...r):O(r)&&s?a.push(...r.split(s)):a.push(r)));const c=qt(this.data,a);return!c&&!n&&!r&&e.includes(".")&&(e=a[0],n=a[1],r=a.slice(2).join(".")),c||!o||!O(r)?c:Jn(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let a=[e,n];r&&(a=a.concat(o?r.split(o):r)),e.includes(".")&&(a=e.split("."),i=n,n=a[1]),this.addNamespaces(n),Di(this.data,a,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(O(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,o={silent:!1,skipCopy:!1}){let a=[e,n];e.includes(".")&&(a=e.split("."),i=r,r=n,n=a[1]),this.addNamespaces(n);let c=qt(this.data,a)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?Oa(c,r,s):c={...c,...r},Di(this.data,a,c),o.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var Aa={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const Ta=Symbol("i18next/PATH_KEY");function md(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===Ta?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Ie(t,e){const{[Ta]:n}=t(md()),r=e?.keySeparator??".",i=e?.nsSeparator??":",s=e?.enableSelector==="strict";if(n.length>1&&i){const o=e?.ns,a=s?Array.isArray(o)?o:o?[o]:null:Array.isArray(o)?o:null;if(a&&(s?a:a.length>1?a.slice(1):[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const wn=t=>!O(t)&&typeof t!="boolean"&&typeof t!="number";class Vt extends en{constructor(e,n={}){super(),sd(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Q.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=wn(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=r&&e.includes(r),a=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!gd(e,r,i);if(o&&!a){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:O(s)?[s]:s};const l=e.split(r);(r!==i||r===i&&this.options.ns.includes(l[0]))&&(s=l.shift()),e=l.join(i)}return{key:e,namespaces:O(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=Ie(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map(k=>typeof k=="function"?Ie(k,{...this.options,...i}):String(k));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:a,namespaces:c}=this.extractFromKey(e[e.length-1],i),l=c[c.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const h=i.lng||this.language,d=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return d?s?{res:`${l}${u}${a}`,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${a}`:s?{res:a,usedKey:a,exactUsedKey:a,usedLng:h,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:a;const g=this.resolve(e,i);let p=g?.res;const m=g?.usedKey||a,b=g?.exactUsedKey||a,x=["[object Number]","[object Function]","[object RegExp]"],A=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,w=i.count!==void 0&&!O(i.count),T=Vt.hasDefaultValue(i),F=w?this.pluralResolver.getSuffix(h,i.count,i):"",L=i.ordinal&&w?this.pluralResolver.getSuffix(h,i.count,{ordinal:!1}):"",X=w&&!i.ordinal&&i.count===0,M=X&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${F}`]||i[`defaultValue${L}`]||i.defaultValue;let y=p;S&&!p&&T&&(y=M);const gt=wn(y),ce=Object.prototype.toString.apply(y);if(S&&y&&gt&&!x.includes(ce)&&!(O(A)&&Array.isArray(y))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const k=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,y,{...i,ns:c}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(g.res=k,g.usedParams=this.getUsedParamsDetails(i),g):k}if(o){const k=Array.isArray(y),_=k?[]:{},G=k?b:m;for(const V in y)if(Object.prototype.hasOwnProperty.call(y,V)){const H=`${G}${o}${V}`;T&&!p?_[V]=this.translate(H,{...i,defaultValue:wn(M)?M[V]:void 0,joinArrays:!1,ns:c}):_[V]=this.translate(H,{...i,joinArrays:!1,ns:c}),_[V]===H&&(_[V]=y[V])}p=_}}else if(S&&O(A)&&Array.isArray(p))p=p.join(A),p&&(p=this.extendTranslation(p,e,i,r));else{let k=!1,_=!1;!this.isValidLookup(p)&&T&&(k=!0,p=M),this.isValidLookup(p)||(_=!0,p=a);const V=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&_?void 0:p,H=T&&M!==p&&this.options.updateMissing;if(_||k||H){if(this.logger.log(H?"updateKey":"missingKey",h,l,w&&!H?`${a}${this.pluralResolver.getSuffix(h,i.count,i)}`:a,H?M:p),o){const f=this.resolve(a,{...i,keySeparator:!1});f&&f.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 U=[];const ve=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ve&&ve[0])for(let f=0;f<ve.length;f++)U.push(ve[f]);else this.options.saveMissingTo==="all"?U=this.languageUtils.toResolveHierarchy(i.lng||this.language):U.push(i.lng||this.language);const K=(f,v,C)=>{const E=T&&C!==p?C:V;this.options.missingKeyHandler?this.options.missingKeyHandler(f,l,v,E,H,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(f,l,v,E,H,i),this.emit("missingKey",f,l,v,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?U.forEach(f=>{const v=this.pluralResolver.getSuffixes(f,i);X&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!v.includes(`${this.options.pluralSeparator}zero`)&&v.push(`${this.options.pluralSeparator}zero`),v.forEach(C=>{K([f],a+C,i[`defaultValue${C}`]||M)})}):K(U,a,M))}p=this.extendTranslation(p,e,i,g,r),_&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${l}${u}${a}`),(_||k)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${a}`:a,k?p:void 0,i))}return s?(g.res=p,g.usedParams=this.getUsedParamsDetails(i),g):p}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=O(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let l;if(c){const h=e.match(this.interpolator.nestingRegexp);l=h&&h.length}let u=r.replace&&!O(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),c){const h=e.match(this.interpolator.nestingRegexp),d=h&&h.length;l<d&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>s?.[0]===h[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${n[0]}`),null):this.translate(...h,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,a=O(o)?[o]:o;return e!=null&&a?.length&&r.applyPostProcessor!==!1&&(e=Aa.handle(a,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,o,a;return O(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(c=>typeof c=="function"?Ie(c,{...this.options,...n}):c)),e.forEach(c=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(c,n),u=l.key;i=u;let h=l.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const d=n.count!==void 0&&!O(n.count),g=d&&!n.ordinal&&n.count===0,p=n.context!==void 0&&(O(n.context)||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);h.forEach(b=>{this.isValidLookup(r)||(a=b,!this.checkedLoadedFor[`${m[0]}-${b}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(this.checkedLoadedFor[`${m[0]}-${b}`]=!0,this.logger.warn(`key "${i}" for languages "${m.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!!!")),m.forEach(x=>{if(this.isValidLookup(r))return;o=x;const A=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(A,u,x,b,n);else{let w;d&&(w=this.pluralResolver.getSuffix(x,n.count,n));const T=`${this.options.pluralSeparator}zero`,F=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(n.ordinal&&w.startsWith(F)&&A.push(u+w.replace(F,this.options.pluralSeparator)),A.push(u+w),g&&A.push(u+T)),p){const L=`${u}${this.options.contextSeparator||"_"}${n.context}`;A.push(L),d&&(n.ordinal&&w.startsWith(F)&&A.push(L+w.replace(F,this.options.pluralSeparator)),A.push(L+w),g&&A.push(L+T))}}let S;for(;S=A.pop();)this.isValidLookup(r)||(s=S,r=this.getResource(x,b,S,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!O(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i={...i,count:e.count}),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&r.startsWith(n)&&e[r]!==void 0)return!0;return!1}}class Ii{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=ot(e),!e||!e.includes("-"))return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=ot(e),!e||!e.includes("-"))return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(O(e)&&e.includes("-")){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(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 n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>o===s?!0:!o.includes("-")&&!s.includes("-")?!1:!!(o.includes("-")&&!s.includes("-")&&o.slice(0,o.indexOf("-"))===s||o.startsWith(s)&&s.length>1))}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),O(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.options.fallbackLng,i=Array.isArray(r)?r.join("|"):r;i!==this._cachedFallbackLng&&(this.resolveHierarchyCache={},this._cachedFallbackLng=i);const s=n===void 0||n===!1||O(n),o=n===void 0&&typeof this.options.fallbackLng=="function",a=O(e)&&s&&!o;let c=null;if(a){let d;n===void 0?d="undefined":n===!1?d="boolean:false":d=`string:${n}`,c=`${e.length}:${e}|${d}`}if(c!==null){const d=this.resolveHierarchyCache[c];if(d!==void 0)return d.slice()}const l=this.getFallbackCodes((n===!1?[]:n)||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 O(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))):O(e)&&h(this.formatLanguageCode(e)),l.forEach(d=>{u.includes(d)||h(this.formatLanguageCode(d))}),c!==null?(this.resolveHierarchyCache[c]=u,u.slice()):u}}const Pi={zero:0,one:1,two:2,few:3,many:4,other:5},Li={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class yd{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Q.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=ot(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Li;if(!e.match(/-|_/))return Li;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>Pi[i]-Pi[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const $i=(t,e,n,r=".",i=!0)=>{let s=ld(t,e,n);return!s&&i&&O(n)&&(s=Jn(t,n,r),s===void 0&&(s=Jn(e,n,r))),s},bd=t=>t.replace(/\$/g,"$$$$");class _i{constructor(e={}){this.logger=Q.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:o,suffix:a,suffixEscaped:c,formatSeparator:l,unescapeSuffix:u,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:g,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:b,maxReplaces:x,alwaysFormat:A}=e.interpolation;this.escape=n!==void 0?n:ud,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ee(s):o||"{{",this.suffix=a?ee(a):c||"}}",this.formatSeparator=l||",",this.unescapePrefix=u?"":h?ee(h):"-",this.unescapeSuffix=this.unescapePrefix?"":u?ee(u):"",this.nestingPrefix=d?ee(d):g||ee("$t("),this.nestingSuffix=p?ee(p):m||ee(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=x||1e3,this.alwaysFormat=A!==void 0?A:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"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,n,r,i){let s,o,a;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=g=>{if(!g.includes(this.formatSeparator)){const x=$i(n,c,g,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(x,void 0,r,{...i,...n,interpolationkey:g}):x}const p=g.split(this.formatSeparator),m=p.shift().trim(),b=p.join(this.formatSeparator).trim();return this.format($i(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...i,...n,interpolationkey:m})};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=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:g=>g},{regex:this.regexp,safeValue:g=>this.escapeValue?this.escape(g):g}].forEach(g=>{for(a=0;s=g.regex.exec(e);){const p=s[1].trim();if(o=l(p),o===void 0)if(typeof u=="function"){const b=u(e,s,i);o=O(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,p))o="";else if(h){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${p} for interpolating ${e}`),o="";else!O(o)&&!this.useRawValueToEscape&&(o=Ti(o));const m=g.safeValue(o);if(e=e.replace(s[0],bd(m)),h?(g.regex.lastIndex+=m.length,g.regex.lastIndex-=s[0].length):g.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,o;const a=(c,l)=>{const u=this.nestingOptionsSeparator;if(!c.includes(u))return c;const h=c.split(new RegExp(`${ee(u)}[ ]*{`));let d=`{${h[1]}`;c=h[0],d=this.interpolate(d,o);const g=d.match(/'/g),p=d.match(/"/g);((g?.length??0)%2===0&&!p||(p?.length??0)%2!==0)&&(d=d.replace(/'/g,'"'));try{o=JSON.parse(d),l&&(o={...l,...o})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${u}${d}`}return o.defaultValue&&o.defaultValue.includes(this.prefix)&&delete o.defaultValue,c};for(;i=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!O(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const l=/{.*}/s.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(l!==-1&&(c=i[1].slice(l).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,l)),s=n(a.call(this,i[1].trim(),o),o),s&&i[0]===e&&!O(s))return s;O(s)||(s=Ti(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((u,h)=>this.format(u,h,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Sd=t=>{let e=t.toLowerCase().trim();const n={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].slice(0,-1);e==="currency"&&!i.includes(":")?n.currency||(n.currency=i.trim()):e==="relativetime"&&!i.includes(":")?n.range||(n.range=i.trim()):i.split(";").forEach(o=>{if(o){const[a,...c]=o.split(":"),l=c.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();n[u]||(n[u]=l),l==="false"&&(n[u]=!1),l==="true"&&(n[u]=!0),isNaN(l)||(n[u]=parseInt(l,10))}})}return{formatName:e,formatOptions:n}},Bi=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const o=r+JSON.stringify(s);let a=e[o];return a||(a=t(ot(r),i),e[o]=a),a(n)}},vd=t=>(e,n,r)=>t(ot(n),r)(e);class wd{constructor(e={}){this.logger=Q.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?Bi:vd;this.formats={number:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s});return a=>o.format(a)}),currency:r((i,s)=>{const o=new Intl.NumberFormat(i,{...s,style:"currency"});return a=>o.format(a)}),datetime:r((i,s)=>{const o=new Intl.DateTimeFormat(i,{...s});return a=>o.format(a)}),relativetime:r((i,s)=>{const o=new Intl.RelativeTimeFormat(i,{...s});return a=>o.format(a,s.range||"day")}),list:r((i,s)=>{const o=new Intl.ListFormat(i,{...s});return a=>o.format(a)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=Bi(n)}format(e,n,r,i={}){if(!n||e==null)return e;const s=n.split(this.formatSeparator),o=[];for(let c=0;c<s.length;c++){let l=s[c];for(;l.indexOf("(")>-1&&!l.includes(")")&&c+1<s.length;)l=`${l}${this.formatSeparator}${s[++c]}`;o.push(l)}return o.reduce((c,l)=>{const{formatName:u,formatOptions:h}=Sd(l);if(this.formats[u]){let d=c;try{const g=i?.formatParams?.[i.interpolationkey]||{},p=g.locale||g.lng||i.locale||i.lng||r;d=this.formats[u](c,p,{...h,...i,...g})}catch(g){this.logger.warn(g)}return d}else this.logger.warn(`there was no format function for ${u}`);return c},e)}}const xd=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Ed extends en{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=Q.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(e,n,r,i){const s={},o={},a={},c={};return e.forEach(l=>{let u=!0;n.forEach(h=>{const d=`${l}|${h}`;!r.reload&&this.store.hasResourceBundle(l,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),s[d]===void 0&&(s[d]=!0),c[h]===void 0&&(c[h]=!0)))}),u||(a[l]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const i=e.split("|"),s=i[0],o=i[1];n&&this.emit("failedLoading",s,o,n),!n&&r&&this.store.addResourceBundle(s,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const a={};this.queue.forEach(c=>{od(c.loaded,[s],o),xd(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(l=>{a[l]||(a[l]={});const u=c.loaded[l];u.length&&u.forEach(h=>{a[l][h]===void 0&&(a[l][h]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(c=>!c.done)}read(e,n,r,i=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:o});return}this.readingCalls++;const a=(l,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(l&&u&&i<this.maxRetries){setTimeout(()=>{this.read(e,n,r,i+1,s*2,o)},s);return}o(l,u)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const l=c(e,n);l&&typeof l.then=="function"?l.then(u=>a(null,u)).catch(a):a(null,l)}catch(l){a(l)}return}return c(e,n,a)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();O(e)&&(e=this.languageUtils.toResolveHierarchy(e)),O(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,o),!o&&a&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,a),this.loaded(e,o,a)})}saveMissing(e,n,r,i,s,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" 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(!(r==null||r==="")){if(this.backend?.create){const c={...o,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let u;l.length===5?u=l(e,n,r,i,c):u=l(e,n,r,i),u&&typeof u.then=="function"?u.then(h=>a(null,h)).catch(a):a(null,u)}catch(u){a(u)}else l(e,n,r,i,a,c)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const xn=()=>({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:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),O(t[1])&&(e.defaultValue=t[1]),O(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),qi=t=>(O(t.ns)&&(t.ns=[t.ns]),O(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),O(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),xt=()=>{},Cd=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class it extends en{constructor(e={},n){if(super(),this.options=qi(e),this.services={},this.logger=Q,this.modules={external:[]},Cd(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(O(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=xn();this.options={...r,...this.options,...qi(e)},this.options.interpolation={...r.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=r.overloadTranslationOptionHandler);const i=l=>l?typeof l=="function"?new l:l:null;if(!this.options.isClone){this.modules.logger?Q.init(i(this.modules.logger),this.options):Q.init(null,this.options);let l;this.modules.formatter?l=this.modules.formatter:l=wd;const u=new Ii(this.options);this.store=new Fi(this.options.resources,this.options);const h=this.services;h.logger=Q,h.resourceStore=this.store,h.languageUtils=u,h.pluralResolver=new yd(u,{prepend:this.options.pluralSeparator}),l&&(h.formatter=i(l),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new _i(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new Ed(i(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.languageDetector&&(h.languageDetector=i(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=i(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new Vt(this.services,this.options),this.translator.on("*",(d,...g)=>{this.emit(d,...g)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,n||(n=xt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.length>0&&l[0]!=="dev"&&(this.options.lng=l[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(l=>{this[l]=(...u)=>this.store[l](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(l=>{this[l]=(...u)=>(this.store[l](...u),this)});const a=Xe(),c=()=>{const l=(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),n(u,h)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return l(null,this.t.bind(this));this.changeLanguage(this.options.lng,l)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),a}loadResources(e,n=xt){let r=n;const i=O(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(l=>{l!=="cimode"&&(s.includes(l)||s.push(l))})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(s,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(a)})}else r(null)}reloadResources(e,n,r){const i=Xe();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=xt),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}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"&&Aa.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 n=0;n<this.languages.length;n++){const r=this.languages[n];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Xe();this.emit("languageChanging",e);const i=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},s=(a,c)=>{c?this.isLanguageChangingTo===e&&(i(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...l)=>this.t(...l)),n&&n(a,(...l)=>this.t(...l))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const c=O(a)?a:a&&a[0],l=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(O(a)?[a]:a);l&&(this.language||i(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector?.cacheUserLanguage?.(l)),this.loadResources(l,u=>{s(u,l)})};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),r}getFixedT(e,n,r,i){const s=i?.scopeNs,o=(a,c,...l)=>{let u;typeof c!="object"?u=this.options.overloadTranslationOptionHandler([a,c].concat(l)):u={...c},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||r||o.keyPrefix);const d={...this.options,...u};Array.isArray(s)&&!h&&(d.ns=s),typeof u.keyPrefix=="function"&&(u.keyPrefix=Ie(u.keyPrefix,d));const g=this.options.keySeparator||".";let p;return u.keyPrefix&&Array.isArray(a)?p=a.map(m=>(typeof m=="function"&&(m=Ie(m,d)),`${u.keyPrefix}${g}${m}`)):(typeof a=="function"&&(a=Ie(a,d)),p=u.keyPrefix?`${u.keyPrefix}${g}${a}`:a),this.t(p,u)};return O(e)?o.lng=e:o.lngs=e,o.ns=n,o.keyPrefix=r,o}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){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 r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(a,c)=>{const l=this.services.backendConnector.state[`${a}|${c}`];return l===-1||l===0||l===2};if(n.precheck){const a=n.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!i||o(s,e)))}loadNamespaces(e,n){const r=Xe();return this.options.ns?(O(e)&&(e=[e]),e.forEach(i=>{this.options.ns.includes(i)||this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=Xe();O(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(o=>!i.includes(o)&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=i.concat(s),this.loadResources(o=>{r.resolve(),n&&n(o)}),r):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["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"],r=this.services?.languageUtils||new Ii(xn());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.includes(r.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new it(e,n);return r.createInstance=it.createInstance,r}cloneInstance(e={},n=xt){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new it(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(a=>{s[a]=this[a]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const a=Object.keys(this.store.data).reduce((c,l)=>(c[l]={...this.store.data[l]},c[l]=Object.keys(c[l]).reduce((u,h)=>(u[h]={...c[l][h]},u),c[l]),c),{});s.store=new Fi(a,i),s.services.resourceStore=s.store}if(e.interpolation){const c={...xn().interpolation,...this.options.interpolation,...e.interpolation},l={...i,interpolation:c};s.services.interpolator=new _i(l)}return s.translator=new Vt(s.services,i),s.translator.on("*",(a,...c)=>{s.emit(a,...c)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const z=it.createInstance();z.createInstance;z.dir;z.init;z.loadResources;z.reloadResources;z.use;z.changeLanguage;z.getFixedT;z.t;z.exists;z.setDefaultNamespace;z.hasLoadedNamespace;z.loadNamespaces;z.loadLanguages;function dt(t){return t.plain===""&&t.ssml===""&&t.language===""}function kd(t){if(!t||dt(t))return;if(t.ssml===""&&t.language==="")return t.plain;const e={language:t.language};return t.plain!==""&&(e.plain=t.plain),t.ssml!==""&&(e.ssml=t.ssml),e}function Od(t,e){if(t.lang!==e.lang||t.tag!==e.tag)return!1;const n=Object.entries(t.attrs??{}),r=Object.entries(e.attrs??{});return n.length!==r.length?!1:n.every(([i,s])=>e.attrs?.[i]===s)}const zt=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),En=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Ad=/[\u00A0\u2007\u202F]/;function Td(t){return Ad.test(t)}function Ve(t,e){let n="",r=!1,i=!1;for(const s of t)if(Td(s))n+=s,r=!1,i=!0;else if(/\s/.test(s)){if(e&&!i||r)continue;n+=" ",r=!0}else s!=="​"&&s!=="­"&&(n+=s,r=!1,i=!0);return n}const Xn="#css(",Yn=")";function Ra(t){return`${Xn}${encodeURIComponent(t)}${Yn}`}function Na(t){if(!(!t||!t.startsWith(Xn)||!t.endsWith(Yn)))return decodeURIComponent(t.slice(Xn.length,-Yn.length))}const Qn="#domrange(",Zn=")";function Da(t){return`${Qn}${encodeURIComponent(JSON.stringify(t))}${Zn}`}function Fa(t){if(!(!t||!t.startsWith(Qn)||!t.endsWith(Zn)))try{const e=JSON.parse(decodeURIComponent(t.slice(Qn.length,-Zn.length)));return!e?.start?.cssSelector||typeof e.start.textNodeIndex!="number"?void 0:e}catch{return}}const er=":~:text=";function Et(t){return encodeURIComponent(t).replace(/-/g,"%2D")}function Ia(t){let e="";return t.prefix&&(e+=`${Et(t.prefix)}-,`),e+=Et(t.textStart),t.textEnd&&(e+=`,${Et(t.textEnd)}`),t.suffix&&(e+=`,-${Et(t.suffix)}`),`${er}${e}`}function Rd(t){if(!t)return;const e=t.indexOf(er);if(e===-1)return;const n=t.slice(e+er.length).split("&")[0];if(n)try{let r=n.split(",");const i={textStart:""};return r[0].endsWith("-")&&(i.prefix=decodeURIComponent(r[0].slice(0,-1)),r=r.slice(1)),r.length>0&&r[r.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(r[r.length-1].slice(1)),r=r.slice(0,-1)),r.length===0||r[0]===""?void 0:(i.textStart=decodeURIComponent(r[0]),r.length>1&&(i.textEnd=decodeURIComponent(r[1])),i)}catch{return}}function tr(t){const e=t?.textref;if(!e)return;const n=e.indexOf(":~:"),r=n===-1?e:e.slice(0,n);let i,s;const o=Fa(r);if(o)s=o,i=o.start.cssSelector;else{const l=Na(r);l!==void 0?i=l:t?.id&&r===`#${CSS.escape(t.id)}`&&(i=r)}const a=Rd(e);if(i===void 0&&s===void 0&&a===void 0)return;const c={};return i!==void 0&&(c.cssSelector=i),s!==void 0&&(c.domRange=s),a?.textEnd!==void 0?c.fragment=Ia(a):a&&(c.text={highlight:a.textStart},a.prefix!==void 0&&(c.text.before=a.prefix),a.suffix!==void 0&&(c.text.after=a.suffix)),c}const Nd={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."}}}},Dd={speech:Nd},kr=Dd.speech.contextualizations,Ui={en:kr},Fd={};async function Id(t){const e=Ui[t];if(e)return e;const n=Fd[t];if(!n)return kr;const r=(await n()).speech.contextualizations;return Ui[t]=r,r}const Pd=/<lang xml:lang="[^"]*">([\s\S]*?)<\/lang>/g;function Pa(t){return t.replace(Pd,"$1")}const Ld=/\s*<readium:[a-zA-Z][\w-]*\s+id="[^"]*"\s*\/>\s*/g;function $d(t){return t.replace(Ld,(n,r,i)=>{const s=i.slice(r+n.length);return s.length===0||Qt(s)?"":" "}).replace(/ {2,}/g," ").trim()}function _d(t){return t.includes("<")}function Or(t){if(t===void 0)return;if(typeof t=="string")return{plain:t};const e={language:t.language};if(t.ssml){const n=$d(t.ssml);_d(n)&&(e.ssml=n)}return t.plain&&(e.plain=t.plain),e.plain||e.ssml?e:void 0}function tn(t){return t.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/ {2,}/g," ").trim()}const La=/<lang xml:lang="([^"]*)">([\s\S]*?)<\/lang>/g;function $a(t){return new RegExp(La).test(t)}function Vi(t){return t.replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/ {2,}/g," ")}const Bd=new RegExp(`\\s+|[${$n}]+|[${De}]+|[^\\s${$n}${De}]+`,"gu");function Cn(t){const e=[];for(const[n]of t.matchAll(Bd))/^\s/.test(n)?e.push({kind:"space"}):Tu(n)?e.push({kind:"open",text:n}):Qt(n)?e.push({kind:"close",text:n}):e.push({kind:"word",text:n});return e}function qd(t){let e="",n=!1;for(const r of t){if(r.kind==="space"){e&&(n=!0);continue}n&&(e+=" "),e+=r.text,n=!1}return e}function Ud(t){let e=t.length;for(;e>0&&(t[e-1].kind==="space"||t[e-1].kind==="open");)e--;return t.slice(e).some(n=>n.kind==="open")?t.splice(e):[]}function Vd(t){let e=0;for(;e<t.length&&(t[e].kind==="space"||t[e].kind==="close");)e++;return t.slice(0,e).some(n=>n.kind==="close")?t.splice(0,e):[]}function _a(t,e){const n=[];let r=0;for(const s of t.matchAll(La))n.push({tokens:Cn(Vi(t.slice(r,s.index))),language:e,tagged:!1}),n.push({tokens:Cn(tn(s[2])),language:s[1],tagged:!0}),r=s.index+s[0].length;n.push({tokens:Cn(Vi(t.slice(r))),language:e,tagged:!1});for(let s=0;s<n.length-1;s++)!n[s].tagged&&n[s+1].tagged?n[s+1].tokens.unshift(...Ud(n[s].tokens)):n[s].tagged&&!n[s+1].tagged&&n[s].tokens.push(...Vd(n[s+1].tokens));const i=[];for(const s of n){const o=qd(s.tokens);o&&i.push({plain:o,language:s.language})}return i}const Ba=/<readium:[a-zA-Z][\w-]*\s+id="([^"]*)"\s*\/>/g;function zd(t){return new RegExp(Ba).test(t)}function Md(t){const e=[];let n=0;for(const i of t.matchAll(Ba)){const s=t.slice(n,i.index).trim();s&&e.push({ssml:s}),e.push({placeholderId:i[1]}),n=i.index+i[0].length}const r=t.slice(n).trim();return r&&e.push({ssml:r}),e}const jd=["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"],qa=["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"],Hd={footnote:{drops:["aside"],unconditional:!0},cover:{drops:["image"]},pullquote:{drops:["blockquote","aside"]},epigraph:{drops:["blockquote"]}},Wd=["noteref","pagebreak"],Gd=["audio","video","image","figure","math","table","cover"],Kd=["cell","rowheader"],Jd=["separator"];function Ua(t){const e=Or(t.text);return e?e.plain??(e.ssml?tn(e.ssml):""):""}function Xd(t){const e=new Map,n=new Map;let r=0,i;return t.forEach((s,o)=>{e.set(s,o+1);const a=s.children??[];if(r=Math.max(r,a.length),a.some(c=>c.role?.includes("columnheader"))){i=a.map(Ua);return}i&&a.forEach((c,l)=>{const u=c.role??[];if(!u.includes("cell")&&!u.includes("rowheader"))return;const h=i[l];h&&n.set(c,h)})}),{lines:t.length,columns:r,rowNumbers:e,cellHeaders:n}}const Yd=new Set(qa),Qd=new Set(Wd),Zd=new Set(Gd),Ar=new Set(Kd),ef=new Set(Jd);function lt(t,e,n,r){const i=n?`${e}.${n}`:void 0;if(i&&t.i18n.exists(i))return t.i18n.t(i,r);if(t.i18n.exists(e))return t.i18n.t(e,r)}function fe(t,e){return e==="ssml"?{ssml:zt(t),synthetic:!0}:{plain:t,synthetic:!0}}function ge(t,e,n,r){t.push(...r);for(let i=0;i<r.length;i++)e.push(n)}function Va(t,e,n,r,i,s,o){o?(i.some(a=>n.blockStarts.has(a))&&n.blockStarts.add(o),ge(t,e,s[0]??r,[o])):(t.push(...i),e.push(...s))}function Tr(t,e){return Ar.has(t)?!0:e.contextualize.has(t)}function tf(t,e,n){return e.some(r=>{const i=Hd[r];return i?.drops.includes(t)?i.unconditional||Tr(r,n):!1})}function zi(t,e,n,r,i,s,o,a){if(!Tr(i,r))return;if((r.i18n.exists(`${i}.block.start`)||r.i18n.exists(`${i}.block.end`))&&r.contextualizationShapes[i]!=="inline"){const l=s==="before"?`${i}.block.start`:`${i}.block.end`,u=lt(r,l,o,a);u&&ge(t,e,n,[fe(u,r.format)]);return}if(s==="before"){const l=lt(r,`${i}.inline`,o,a);if(l){const u=fe(l,r.format);if(Ar.has(i)&&(delete u.synthetic,r.language!=="none")){const h=typeof n.text=="object"?n.text.language:void 0;h&&(u.language=h)}ge(t,e,n,[u])}}}function Mi(t,e){return e.size>0&&t.some(n=>e.has(n))}function Rr(t,e){let n,r=!1;const i=[];for(const a of t){const c=e==="ssml"?a.ssml:a.plain;if(c&&(i.push(c),a.language!==void 0)){if(r&&a.language!==n)return;n=a.language,r=!0}}if(i.length===0)return;let s="";for(const a of i)a.length===1&&s.endsWith(a)||(s&&!Qt(a)&&(s+=" "),s+=a);const o=e==="ssml"?{ssml:s}:{plain:s};return n&&(o.language=n),t.some(a=>a.synthetic)&&(o.synthetic=!0),o}function nf(t,e){const n=Or(t.text),r=n?za(n,e.format,e.language):[];if(!e.contextualize.has("pagebreak"))return r;const i=e.i18n.exists("pagebreak.block.start")?"pagebreak.block.start":"pagebreak.inline",s=lt(e,i);if(s===void 0)return r;const o=fe(s,e.format);if(r.length===0)return[o];const a=Rr([o,...r],e.format);return a?(a.plain!==void 0&&(a.plain+="."),a.ssml!==void 0&&(a.ssml+="."),[a]):[o,...r]}function za(t,e,n){if(e==="plain"&&n!=="block-level"&&n!=="none"&&t.ssml&&$a(t.ssml))return _a(t.ssml,t.language).map(i=>{const s={plain:i.plain};return i.language&&(s.language=i.language),s});const r={};return t.language&&(r.language=t.language),e==="ssml"?r.ssml=t.ssml??zt(t.plain??""):r.plain=t.plain??tn(t.ssml??""),(n==="block-level"||n==="none")&&(r.ssml&&(r.ssml=Pa(r.ssml)),n==="none"&&delete r.language),[r]}function rf(t){return(t.role??[]).some(e=>Qd.has(e))}function sf(t,e,n,r,i,s){const o=typeof t.text=="object"?t.text.language:void 0,a=new Map((t.children??[]).map(d=>[d.id,d])),c=[],l=[],u=[];for(const d of Md(e)){if(d.placeholderId!==void 0){const p=a.get(d.placeholderId);if(!p)continue;i.inlineContextualization||!rf(p)?Ma(p,c,l,i,s):u.push(p);continue}if(!d.ssml)continue;if(i.format==="plain"&&i.language!=="block-level"&&i.language!=="none"&&$a(d.ssml)){for(const p of _a(d.ssml,o)){const m={plain:p.plain};p.language&&(m.language=p.language),c.push(m),l.push(t)}continue}const g={};o&&(g.language=o),i.format==="ssml"?g.ssml=d.ssml:g.plain=tn(d.ssml),(i.language==="block-level"||i.language==="none")&&(g.ssml&&(g.ssml=Pa(g.ssml)),i.language==="none"&&delete g.language),c.push(g),l.push(t)}const h=c.length>1?Rr(c,i.format):void 0;return Va(n,r,i,t,c,l,h),u}function ji(t,e,n,r){const i=`${e}.parts.${n}`;return t.i18n.exists(i,{count:r})?t.i18n.t(i,{count:r}):String(r)}function af(t){return t.description===void 0?{variantKey:"unlabelled"}:{variantKey:"labelled",params:{description:t.description}}}function Hi(t,e){const n=e.tableCellHeaders.get(t);return{variantKey:n!==void 0?"withHeader":"withoutHeader",params:{header:n??"",value:Ua(t)}}}const of={table:(t,e)=>{const n=(t.children??[]).filter(i=>i.role?.includes("row")),r=Xd(n);for(const[i,s]of r.rowNumbers)e.tableRowNumbers.set(i,s);for(const[i,s]of r.cellHeaders)e.tableCellHeaders.set(i,s);return{params:{lines:ji(e,"table","lines",r.lines),columns:ji(e,"table","columns",r.columns)}}},row:(t,e)=>({params:{count:String(e.tableRowNumbers.get(t)??"")}}),cell:Hi,rowheader:Hi};function Wi(t,e,n){const r=af(e);let i=r.variantKey,s=r.params;const o=of[t]?.(e,n);o&&(o.variantKey&&(i=o.variantKey),s={...s,...o.params});const a=n.contextualizationParams?.(t,e);return a&&(s={...s,...a}),{variantKey:i,params:s}}function Ma(t,e,n,r,i){const s=t.role??[];if(Mi(s,r.skip))return;const o=s.some(d=>Yd.has(d)),a=o&&!i,c=e.length,l=s.filter(d=>d!=="footnote"&&d!=="pagebreak"&&!tf(d,s,r)),u=s.some(d=>Zd.has(d)&&r.contextualize.has(d)),h=s.includes("table")&&t.description!==void 0&&!u;h&&ge(e,n,t,[fe(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);zi(e,n,t,r,d,"before",g,p)}if(s.includes("noteref"))for(const d of t.children??[]){const g=d.role??[];if(!Mi(g,r.skip))if(g.includes("footnote")){const p=[],m=[];he([d],p,m,r,i);const b=r.contextualize.has("footnote"),x=r.i18n.exists("footnote.block.start")||r.i18n.exists("footnote.block.end"),A=b?lt(r,x?"footnote.block.start":"footnote.inline"):void 0,S=b&&(A!==void 0||x),w=[],T=[];if(A!==void 0&&(w.push(fe(A,r.format)),T.push(d)),w.push(...p),T.push(...m),S&&x){const L=lt(r,"footnote.block.end");L!==void 0&&(w.push(fe(L,r.format)),T.push(d))}const F=S&&w.length>1?Rr(w,r.format):void 0;Va(e,n,r,d,w,T,F)}else he([d],e,n,r,i)}else if(!s.some(d=>ef.has(d))){const d=typeof t.text=="object"?t.text.ssml:void 0;if(d&&zd(d)){const g=sf(t,d,e,n,r,i);if(g.length>0){const p=i||o&&e.length>c;he(g,e,n,r,p)}}else if(s.includes("pagebreak")){if(ge(e,n,t,nf(t,r)),t.children){const g=i||o&&e.length>c;he(t.children,e,n,r,g)}}else{const p=s.some(m=>Ar.has(m)&&Tr(m,r))?void 0:Or(t.text);if(p&&ge(e,n,t,za(p,r.format,r.language)),t.children){const m=i||o&&e.length>c;he(t.children,e,n,r,m)}}}a&&e.length>c&&r.blockStarts.add(e[c]),t.description!==void 0&&!u&&!h&&ge(e,n,t,[fe(t.description,r.format)]);for(const d of l){if(d==="figure"&&t.description===void 0)continue;const{variantKey:g,params:p}=Wi(d,t,r);zi(e,n,t,r,d,"after",g,p)}}function he(t,e,n,r,i){t.forEach((s,o)=>Ma(s,e,n,r,o===0?i:!1))}function lf(t,e){const n=z.createInstance();return n.init({lng:t,resources:{[t]:{translation:e}},interpolation:{escapeValue:!1}}),n}function ja(t,e){if(typeof e=="string"||typeof t!="object")return e;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}function cf(t,e){if(!e)return t;const n={...t};for(const r of Object.keys(e))n[r]=ja(t[r],e[r]);return n}async function Ha(t){const e=t.contextualizationLocale??"en",n=cf(await Id(e),t.contextualization?.contextualizations);return{contextualizations:n,i18n:lf(e,n),skip:new Set(t.skip??[]),contextualize:new Set(t.contextualize??[]),contextualizationShapes:t.contextualization?.shapes??{},contextualizationParams:t.contextualization?.params,format:t.format??"plain",inlineContextualization:t.inlineContextualization??!1,language:t.language??"block-level",blockStarts:new Set,tableRowNumbers:new Map,tableCellHeaders:new Map}}async function uf(t,e){const n=[],r=[];return he(t,n,r,await Ha(e),!1),Wa(n,r,Nr(t))}async function hf(t,e){const n=[],r=[],i=await Ha(e);he(t,n,r,i,!1);const s=n.map(o=>i.blockStarts.has(o));return{utterances:Wa(n,r,Nr(t)),sources:r,blockStarts:s}}function Nr(t,e=[],n=new Map){for(const r of t)n.set(r,e),r.children&&Nr(r.children,[r,...e],n);return n}function Wa(t,e,n){return t.map((r,i)=>{const s=e[i];let o=tr(s);if(!o&&s){for(const a of n.get(s)??[])if(o=tr(a),o)break}return o?{...r,locate:o}:r})}class df{engine;contentQueue=[];events=new Jt;navigatorState="idle";pendingAdvanceTimeout=null;_defaults;_preferences;_settings;_preferencesEditor=null;contextualizationOverrides;source;contentSources=[];contentBlockStarts=[];pendingResumeIndex=null;pendingResumeState=null;pendingAutoPauseIndex=null;constructor(e,n={}){this.engine=e,this._defaults=new Sa(n.defaults),this._preferences=new Ue(n.preferences),this._settings=new Kn(this._preferences,this._defaults),this.contextualizationOverrides=n.contextualizationOverrides,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"),this.emitEvent({type:"start"})}),this.engine.on("end",()=>{const e=this.engine.getCurrentUtteranceIndex(),n=this.engine.getUtteranceCount();if(e<n-1){const r=this._settings.autoPause==="utterance"||this.contentBlockStarts[e+1]===!0;this._settings.autoPause!=="none"&&r?(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,n=this.pendingResumeState;if(this.pendingResumeIndex=null,this.pendingResumeState=null,this.navigatorState==="loading"){if(n==="playing"){this.setNavigatorState("playing"),this.engine.speak(e??0);return}if(n==="paused"){const r=e??0;r>0?this.engine.setCurrentUtteranceIndex(r,()=>this.setNavigatorState("paused")):this.setNavigatorState("paused");return}this.setNavigatorState("ready"),this.emitEvent({type:"ready"})}}),this.engine.on("boundary",e=>{this.emitEvent(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,n=null,r=null){this.clearPendingAdvance(),this.pendingAutoPauseIndex=null,(this.navigatorState==="playing"||this.navigatorState==="paused")&&this.engine.stop();const i=Array.isArray(e)?e:[e];this.contentQueue=[...i],this.pendingResumeIndex=n,this.pendingResumeState=r,this.setNavigatorState("loading"),this.emitEvent({type:"loading"}),this.engine.loadUtterances(i,n??void 0),this.emitContentChangeEvent({content:i})}async reextract(){if(!this.source)return;const e=this.navigatorState==="playing"||this.navigatorState==="paused"?this.navigatorState:null,n=this.contentSources,r=this.getCurrentUtteranceIndex(),{utterances:i,sources:s,blockStarts:o}=await hf(this.source,{format:this._settings.format,inlineContextualization:this._settings.inlineContextualization,skip:this._settings.skip,contextualize:this._settings.contextualize,contextualization:{contextualizations:this.contextualizationOverrides?.contextualizations,shapes:id(this._settings.verbosity,this.contextualizationOverrides?.shapes),params:this.contextualizationOverrides?.params},language:this._settings.language});this.contentSources=s,this.contentBlockStarts=o;const a=e?this.resolveResumeIndex(n,r,s):null;this.setContentQueue(i,a,e)}resolveResumeIndex(e,n,r){for(let i=Math.min(n,e.length-1);i>=0;i--){const s=e[i];if(s===void 0)continue;const o=r.indexOf(s);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,n=!1){const r=this.getCurrentUtteranceIndex();return e<0||e>=this.contentQueue.length?!1:(e===r||(this.clearPendingAdvance(),this.navigatorState==="paused"&&!n?(this.pendingAutoPauseIndex!==null&&(this.pendingAutoPauseIndex=e),this.engine.setCurrentUtteranceIndex(e,i=>{i&&this.emitEvent({type:"skip",detail:{position:e}})})):(this.pendingAutoPauseIndex=null,this.setNavigatorState("playing"),this.engine.speak(e))),!0)}next(e=!1){const n=this.getCurrentUtteranceIndex();return this.skipToPosition(n+1,e)}previous(e=!1){const n=this.getCurrentUtteranceIndex();return this.skipToPosition(n-1,e)}jumpTo(e,n=!1){return this.skipToPosition(e,n)}getState(){return this.navigatorState}on(e,n){return this.events.on(e,n)}emitEvent(e){this.events.emit(e.type,e)}emitContentChangeEvent(e){this.events.emit("contentchange",{type:"contentchange",detail:e})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Wn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){!this.source&&Ai.some(n=>e[n]!==void 0)&&console.warn("submitPreferences(): extraction-affecting preferences (format, inlineContextualization, verbosity, skip, contextualize, language) 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 Kn(this._preferences,this._defaults),this.applyEngineParameters(),this._preferencesEditor!==null&&(this._preferencesEditor=new Wn(this._preferences,this._settings)),Ai.some(n=>!this.sameSettingValue(e[n],this._settings[n]))&&await this.reextract()}sameSettingValue(e,n){return Array.isArray(e)&&Array.isArray(n)?e.length===n.length&&e.every(r=>n.includes(r)):e===n}async destroy(){this.clearPendingAdvance(),this.events.clear(),await this.engine.destroy()}}const ff=["heading1","heading2","heading3","heading4","heading5","heading6"],Gi={"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"},gf={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"},pf={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"},mf=new Set(["table","tr","td","th"]),yf=new Set(["table","row","cell","columnheader","rowheader"]);function bf(t){const e=t.getAttribute("role");if(!e)return!1;const n=e.split(/\s+/).filter(Boolean);return n.includes("presentation")||n.includes("none")}function Sf(t){for(let e=t.parentElement;e;e=e.parentElement)if(bf(e))return!0;return!1}function vf(t,e,n){return mf.has(e)||n.some(r=>yf.has(r))}function Tt(t,e){const n=t.getAttribute("role");return n?n.split(/\s+/).filter(Boolean).includes(e):!1}function wf(t){return t.tagName.toLowerCase()==="table"||Tt(t,"table")||Tt(t,"grid")||Tt(t,"treegrid")}function xf(t){return t.tagName.toLowerCase()==="tr"||Tt(t,"row")}function Ef(t){let e=null;for(let r=t.parentElement;r;r=r.parentElement)if(wf(r)){e=r;break}return e?e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>xf(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===t:!1}function Ga(t){const e=[];let n=!1;const r=t.getAttribute("role");if(r)for(const s of r.split(/\s+/).filter(Boolean))if((s==="presentation"||s==="none")&&(n=!0),s==="heading"){let o=2;const a=parseInt(t.getAttribute("aria-level")??"",10);Number.isFinite(a)&&a>=1&&(o=Math.min(a,6)),e.push(ff[o-1])}else Gi[s]&&e.push(Gi[s]);const i=t.getAttribute("epub:type");if(i)for(const s of i.split(/\s+/).filter(Boolean)){const o=gf[s];o&&e.push(o)}return{attrRoles:e,presentational:n}}function Ka(t){const{attrRoles:e,presentational:n}=Ga(t);return e.length>0||n}function Rt(t){const e=[],n=o=>{e.includes(o)||e.push(o)},{attrRoles:r,presentational:i}=Ga(t),s=t.tagName.toLowerCase();if(i)return["presentation"];if(vf(t,s,r)&&Sf(t))return["presentation"];if(s==="body")n("body");else if(s==="th")switch(t.getAttribute("scope")){case"col":n("columnheader");break;case"row":n("rowheader");break;default:{const o=t.parentElement;o&&Ef(o)?n("columnheader"):t.previousElementSibling===null?n("rowheader"):n("cell")}}else{const o=pf[s];o&&n(o)}for(const o of r)n(o);return e}function Ki(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function Cf(t){let e="";const n=r=>{r.nodeType===3&&(e+=r.nodeValue??"");for(let i=r.firstChild;i;i=i.nextSibling)n(i)};return n(t),e}function nn(t){return Ve(Cf(t),!0).trim()}function nr(t){let e="";const n=(r,i)=>{if(r.nodeType===3){e+=r.nodeValue??"";return}if(!(r.nodeType===1&&!i&&Ka(r)))for(let s=r.firstChild;s;s=s.nextSibling)n(s,!1)};return n(t,!0),e}function Ji(t){return Ve(nr(t),!0).trim()}function kf(t){if(Ki(t))return[null,!1];const e=(t.getAttribute("aria-labelledby")??"").trim();if(e){const s=[...new Set(e.split(/\s+/).filter(Boolean))],o=t.ownerDocument,a=s.map(c=>o.getElementById(c)).filter(c=>c!==null);if(a.length>0){let c="";a.forEach((u,h)=>{if(Ki(u))return;const d=u.getAttribute("aria-label");c+=d||nr(u),h<a.length-1&&(c+=" ")});const l=Ve(c,!0).trim();if(l!=="")return[{language:"",plain:l},!0]}}const n=(t.getAttribute("aria-label")??"").trim();if(n)return[{language:"",plain:n},!0];const r=(t.getAttribute("aria-describedby")??"").trim();if(r){const o=[...new Set(r.split(/\s+/).filter(Boolean))].map(a=>t.ownerDocument.getElementById(a)).filter(a=>a!==null);if(o.length>0){const a=o.map(l=>nr(l)).join(" "),c=Ve(a,!0).trim();if(c!=="")return[{language:"",plain:c},!0]}}const i=t.tagName.toLowerCase();if(i==="img"){const s=(t.getAttribute("alt")??"").trim();if(s)return[{language:"",plain:s},!0];const o=(t.getAttribute("title")??"").trim();if(o)return[{language:"",plain:o},!0]}else if(i==="svg"){const s=t.querySelector(":scope > title");if(s){const o=nn(s);if(o)return[{language:"",plain:o},!0]}}else if(i==="math"){const s=(t.getAttribute("alttext")??"").trim();if(s)return[{language:"",plain:s},!0]}return[null,!0]}const Of={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function Af(t){return Of[t]??["",void 0]}const Tf=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]),Rf=["math","separator"];function rr(t){return t.role?.some(e=>Rf.includes(e))?!1:!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||dt(t.text))&&!(t.children&&t.children.length>0)&&!t.description}function Nf(t){return!t.audioref&&!t.imgref&&!t.textref&&!t.videoref&&(!t.text||dt(t.text))&&!!(t.children&&t.children.length>0)&&!(t.role&&t.role.length>0)&&!t.id}function Df(t){return!(t.role&&t.role.length>0)&&!t.id&&!t.textref&&!t.imgref&&!t.audioref&&!t.videoref}class Ct{el;object={};children=[];noText=!1;finalize(){const e=this.object,n=[];for(const r of this.children){const i=r.finalize();if(!rr(i)){if(Nf(i)){n.push(...i.children??[]);continue}n.push(i)}}if(n.length>0&&(e.children=n),e.role?.length&&e.children?.length===1&&!e.role.includes("presentation")){const r=e.children[0];r.role?.length&&e.role.every(i=>r.role.includes(i))&&delete e.role}if((!e.text||dt(e.text))&&e.children?.length===1){const r=e.children[0];Df(r)&&(r.text&&(e.text=r.text),e.children=r.children)}return e}}function ir(t){const e={};t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref);const n=kd(t.text);return n!==void 0&&(e.text=n),t.role&&t.role.length>0&&(e.role=t.role),t.children&&t.children.length>0&&(e.children=t.children.map(ir)),t.description&&(e.description=t.description),e}function Ja(t){const e={};return t.id&&(e.id=t.id),t.textref&&(e.textref=t.textref),t.imgref&&(e.imgref=t.imgref),t.audioref&&(e.audioref=t.audioref),t.videoref&&(e.videoref=t.videoref),t.role&&(e.role=t.role),t.description&&(e.description=t.description),typeof t.text=="string"?e.text={plain:t.text,ssml:"",language:""}:t.text&&(e.text={plain:t.text.plain??"",ssml:t.text.ssml??"",language:t.text.language}),t.children&&(e.children=t.children.map(Ja)),e}const Ff=1;function Xi(t){for(let e=t;e;e=e.parentElement){const n=e.getAttribute("xml:lang");if(n)return n;const r=e.getAttribute("lang");if(r)return r}return""}function If(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType===Ff)return!0;return!1}function Xa(t,e){for(let n=e;n;n=n.parentElement)if(n===t)return!0;return!1}const Pf=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 Lf(t){return Pf.has(t)}function $f(t){const e=t.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 Ya(t){return typeof t=="object"&&t!==null&&t.nodeType===Node.ELEMENT_NODE}const ct={NONE:"",DESCENDANT:" ",CHILD:" > "},$={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"};function _f(t,e){return Object.values(t).includes(e)}const Bf="CssSelectorGenerator";function Mt(t="unknown problem",...e){console.warn(`${Bf}: ${t}`,...e)}const qf={selectors:[$.id,$.class,$.tag,$.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1,ignoreGeneratedClassNames:!1};function Ye(t){return!!t}function Uf(t){return Array.isArray(t)?t.filter(e=>_f($,e)):[]}function Qa(t){return t instanceof RegExp}function Vf(t){return["string","function"].includes(typeof t)||Qa(t)}function Yi(t){return Array.isArray(t)?t.filter(Vf):[]}function zf(t){return t!=null&&typeof t=="object"&&"nodeType"in t&&typeof t.nodeType=="number"}function Qi(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return zf(t)&&e.includes(t.nodeType)}function Za(t,e){if(Qi(t))return t.contains(e)||Mt("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."),t;const n=e.getRootNode({composed:!1});return Qi(n)?(n.nodeType!==Node.DOCUMENT_NODE&&Mt("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."),n):Fr(e)}function kn(t){return typeof t=="number"?t:Number.POSITIVE_INFINITY}function Mf(t,e={}){const n=Object.assign(Object.assign({},qf),e);return{selectors:Uf(n.selectors),whitelist:Yi(n.whitelist),blacklist:Yi(n.blacklist),root:Za(n.root,t),combineWithinSelector:Ye(n.combineWithinSelector),combineBetweenSelectors:Ye(n.combineBetweenSelectors),includeTag:Ye(n.includeTag),maxCombinations:kn(n.maxCombinations),maxCandidates:kn(n.maxCandidates),useScope:Ye(n.useScope),maxResults:kn(n.maxResults),ignoreGeneratedClassNames:Ye(n.ignoreGeneratedClassNames)}}function ft(t=[]){const[e=[],...n]=t;return n.length===0?e:n.reduce((r,i)=>{const s=new Set(i);return r.filter(o=>s.has(o))},e)}function jf(t){return[].concat(...t)}function Hf(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function jt(t){const e=t.map(n=>{if(Qa(n))return r=>n.test(r);if(typeof n=="function")return r=>{const i=n(r);return typeof i!="boolean"?(Mt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",n),!1):i};if(typeof n=="string"){const r=new RegExp("^"+Hf(n)+"$");return i=>r.test(i)}return Mt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",n),()=>!1});return n=>e.some(r=>r(n))}function Dr(t,e,n){const r=Za(n,t[0]).querySelectorAll(e);if(r.length!==t.length)return!1;const i=new Set(r);return t.every(s=>i.has(s))}function eo(t,e){e=e??Fr(t);const n=[];let r=t;for(;r&&r!==e;)Ya(r)&&n.push(r),r=r.parentNode;return n}function Wf(t,e){return ft(t.map(n=>eo(n,e)))}function Gf(t){return typeof t=="object"&&t!==null&&"nodeType"in t&&t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function Fr(t){return t.ownerDocument.querySelector(":root")}const to=", ",Kf=new RegExp(["^$","\\s"].join("|")),Jf=new RegExp(["^$"].join("|")),no=[$.nthoftype,$.tag,$.id,$.class,$.attribute,$.nthchild],Xf=jt(["class","id","ng-*"]);function Yf({name:t}){return`[${t}]`}function Qf({name:t,value:e}){return`[${t}='${e}']`}function Zf({nodeName:t,nodeValue:e},n){const r=n.tagName.toLowerCase();return["input","option"].includes(r)&&t==="value"||t==="src"&&e?.startsWith("data:")?!1:!Xf(t)}function eg({nodeName:t,nodeValue:e}){return{name:ze(t),value:ze(e??void 0)}}function ro(t,e){const n=Array.from(t.attributes).filter(r=>Zf(r,t)).map(eg);return[...n.map(Yf),...n.map(Qf)]}function tg(t,e){const n=t.map(r=>ro(r));return ft(n)}const ng=/^[a-z_-]{3,}$/i,rg=/[bcdfghjklmnpqrstvwxyz]{4,}/i;function ig(t){if(!ng.test(t)||t.includes("_")&&!t.includes("__")||/^(css|sc|jsx|emotion|makeStyles|MuiButton|MuiBox)-/i.test(t))return!1;const e=t.split(new RegExp("--|__|[-]|(?<=[a-z])(?=[A-Z])")).filter(n=>n.length>0);if(e.length===0||e.length===1&&e[0].length<4)return!1;for(const n of e)if(n.length<=2||rg.test(n))return!1;return!0}function io(t,e){var n;const r=((n=t.getAttribute("class"))!==null&&n!==void 0?n:"").trim().split(/\s+/).filter(s=>!Jf.test(s));let i=r;if(e?.ignoreGeneratedClassNames){const s=jt(e.whitelist);i=r.filter(o=>{const a=`.${ze(o)}`;return s(a)?!0:ig(o)})}return i.map(s=>`.${ze(s)}`)}function sg(t,e){const n=t.map(r=>io(r,e));return ft(n)}function so(t,e){var n;const r=(n=t.getAttribute("id"))!==null&&n!==void 0?n:"",i=`#${ze(r)}`,s=t.getRootNode({composed:!1});return!Kf.test(r)&&Dr([t],i,s)?[i]:[]}function ag(t,e){return t.length===0||t.length>1?[]:so(t[0])}function ao(t,e){const n=t.parentNode,r=n&&"children"in n?n.children:null;if(r){for(let i=0;i<r.length;i++)if(r[i]===t)return[`:nth-child(${String(i+1)})`]}return[]}function og(t,e){return ft(t.map(n=>ao(n)))}function oo(t,e){return[ze(t.tagName.toLowerCase())]}function lo(t,e){const n=[...new Set(jf(t.map(r=>oo(r))))];return n.length===0||n.length>1?[]:[n[0]]}function co(t,e){const n=lo([t])[0],r=t.parentNode,i=r&&"children"in r?r:null;if(i){const o=Array.from(i.children).filter(a=>a.tagName.toLowerCase()===n).indexOf(t);if(o>-1)return[`${n}:nth-of-type(${String(o+1)})`]}return[]}function lg(t,e){return ft(t.map(n=>co(n)))}function*uo(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,r=ho(1);for(;r.length<=t.length&&n<e;){n+=1;const i=new Array(r.length);for(let s=0;s<r.length;s++)i[s]=t[r[s]];yield i,r=ug(r,t.length-1)}}function cg(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(uo(t,{maxResults:e}))}function ug(t=[],e=0){const n=t.length;if(n===0)return t;let r=n-1;for(;r>=0&&t[r]===e-(n-1-r);)r-=1;if(r<0)return ho(n+1);t[r]+=1;for(let i=r+1;i<n;i++)t[i]=t[i-1]+1;return t}function ho(t=1){const e=new Array(t);for(let n=0;n<t;n++)e[n]=n;return e}function*hg(t={}){const e=Object.entries(t);if(e.length===0)return;const n=[{index:e.length-1,partial:{}}];for(;n.length>0;){const r=n.pop();if(!r)break;const{index:i,partial:s}=r;if(i<0){yield s;continue}const[o,a]=e[i];for(let c=a.length-1;c>=0;c--)n.push({index:i-1,partial:Object.assign(Object.assign({},s),{[o]:a[c]})})}}const dg="3a".toUpperCase(),fg=/[ !"#$%&'()[\]{|}<>*+,./;=?@^`~\\]/;function ze(t=""){return CSS?CSS.escape(t):gg(t)}function gg(t=""){return t.split("").map(e=>e===":"?`\\${dg} `:fg.test(e)?`\\${e}`:escape(e).replace(/%/g,"\\")).join("")}const pg={tag:lo,id:ag,class:sg,attribute:tg,nthchild:og,nthoftype:lg},mg={tag:oo,id:so,class:io,attribute:ro,nthchild:ao,nthoftype:co};function yg(t,e,n){return mg[e](t,n)}function bg(t,e,n){const r=pg[e];return r(t,n)}function Sg(t=[],e,n){return t.filter(r=>n(r)||!e(r))}function vg(t=[],e){return t.sort((n,r)=>{const i=e(n),s=e(r);return i&&!s?-1:!i&&s?1:0})}function rn(){const t=new Map;let e;return(n,r)=>{if(n.length!==1)return e??(e=Zi(n,r));const[i]=n;let s=t.get(i);return s||(s=Zi(n,r),t.set(i,s)),s}}function*wg(t,e,n=rn()){const r=new Set,i=n(t,e);for(const s of kg(i,e))r.has(s)||(r.add(s),yield s)}function Zi(t,e){const{blacklist:n,whitelist:r,combineWithinSelector:i,maxCombinations:s}=e,o=jt(n),a=jt(r),c=(l,u)=>{const h=bg(t,u,e),d=Sg(h,o,a),g=vg(d,a);return l[u]=i?Array.from(uo(g,{maxResults:s})):g.map(p=>[p]),l};return xg(e).reduce(c,{})}function xg(t){const{selectors:e,includeTag:n}=t,r=[...e];return n&&!r.includes("tag")&&r.push("tag"),r}function Eg(t){return t.includes($.tag)||t.includes($.nthoftype)?[...t]:[...t,$.tag]}function Cg(t){const{selectors:e,combineBetweenSelectors:n,includeTag:r,maxCandidates:i}=t,s=n?cg(e,{maxResults:i}):e.map(o=>[o]);return r?s.map(Eg):s}function*kg(t,e){for(const n of Cg(e))yield*Og(n,t)}function*Og(t,e){const n={};for(const r of t){const i=e[r];i&&i.length>0&&(n[r]=i)}for(const r of hg(n))yield Tg(r)}function Ag(t,e){return e[t]?e[t].join(""):""}function Tg(t={}){const e=[...no];return t[$.tag]&&t[$.nthoftype]&&e.splice(e.indexOf($.tag),1),e.map(n=>Ag(n,t)).join("")}function Rg(t,e){return[...t.map(n=>e+ct.DESCENDANT+n),...t.map(n=>e+ct.CHILD+n)]}function*Ng(t,e){if(e==="")yield*t;else for(const n of t)yield*Rg([n],e)}function*Dg(t,e,n="",r,i=rn()){const s=wg(t,r,i);for(const o of Ng(s,n))Dr(t,o,e)&&(yield o)}function*Fg(t,e,n="",r,i=rn()){if(t.length===0)return null;const s=[t.length>1?t:[],...Wf(t,e).map(o=>[o])];for(const o of s)for(const a of Dg(o,e,n,r,i))yield{foundElements:o,selector:a}}function*Ig({elements:t,root:e,rootSelector:n="",options:r}){let i=e,s=n,o=!0;const a=rn();for(;o;){let c=!1;for(const l of Fg(t,i,s,r,a)){const{foundElements:u,selector:h}=l;if(c=!0,Dr(t,h,e))yield h;else{i=u[0],s=h;break}}c||(o=!1)}}function Pg(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(Ya);return[...new Set(e)]}function Lg(t){return{value:t,include:!1}}function $g(t,e,n=ct.NONE){const r={};return e.forEach(i=>{Reflect.set(r,i,yg(t,i).map(Lg))}),{element:t,operator:n,selectors:r}}function _g({selectors:t,operator:e}){let n=[...no];t[$.tag]&&t[$.nthoftype]&&(n=n.filter(i=>i!==$.tag));let r="";return n.forEach(i=>{var s;((s=t[i])!==null&&s!==void 0?s:[]).forEach(({value:a,include:c})=>{c&&(r+=a)})}),e+r}function Bg(t,e){const n=eo(t,e).reverse(),r=Gf(e),i=n.map((o,a)=>{var c;const l=$g(o,[$.nthchild],r&&a===0?ct.NONE:ct.CHILD);return((c=l.selectors.nthchild)!==null&&c!==void 0?c:[]).forEach(u=>{u.include=!0}),l});return[r?"":e?":scope":":root",...i.map(_g)].join("")}function qg(t,e){return t.map(n=>Bg(n,e)).join(to)}var Ug=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n};function fo(t,e={}){const n=Object.assign(Object.assign({},e),{maxResults:1});return Vg(t,n).next().value}function*Vg(t,e={}){var n;const r=Pg(t),i=Mf(r[0],e),s=(n=i.root)!==null&&n!==void 0?n:Fr(r[0]);let o=0;for(const c of Ig({elements:r,options:i,root:s,rootSelector:""}))if(yield c,o++,o>=i.maxResults)return;if(r.length>1){const{maxResults:c}=e,l=Ug(e,["maxResults"]);if(yield r.map(u=>fo(u,l)).join(to),o++,o>=i.maxResults)return}const a=e.root!==void 0;yield qg(r,i.useScope||a?s:void 0)}function Ir(t,e){const n=t.getAttribute("id");return n?`#${CSS.escape(n)}`:fo(t,{root:e?.documentElement??void 0})??void 0}function go(t){if(t)return t.startsWith("#")?t:Ra(t)}const zg=3;function Mg(t,e){let n=0;for(const r of Array.from(t.childNodes)){if(r===e)return n;r.nodeType===zg&&n++}return n}function es(t,e,n,r){const i=t.parentElement;if(!i)return;const s=r&&i===r.el?r.selector:Ir(i,n);if(s)return{cssSelector:s,textNodeIndex:Mg(i,t),charOffset:e}}function jg(t,e,n){const r=es(...t.first,e,n);if(!r)return;const i=es(...t.last,e,n);return i?{start:r,end:i}:{start:r}}function Hg(t){const e=mh(t);return e.status===de.SUCCESS?e.fragment:void 0}function ts(t){if(t===!0)return e=>e.length>0;if(Array.isArray(t)&&t.length>0){const e=new Set(t);return n=>n.some(r=>e.has(r))}return null}function Wg(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Gg(t){return Wg(t)?{predicate:ts(t.roles),domRange:!!t.domRange,textFragment:!!t.textFragment}:{predicate:ts(t),domRange:!1,textFragment:!1}}class Kg{claimed=new Set;counters=new Map;allocate(e,n){for(;;){const r=(this.counters.get(e)??0)+1;this.counters.set(e,r);const i=`${e}${r}`;if(!(n(i)||this.claimed.has(i)))return this.claimed.add(i),i}}claim(e){return this.claimed.has(e)?!1:(this.claimed.add(e),!0)}}function Jg(t,e,n){const r=[],i=(s,o)=>{const a=s.getAttribute("id");if(a&&!e.has(a)&&e.set(a,s),o=o||s.getAttribute("aria-hidden")==="true"||s.hasAttribute("hidden"),!o&&s.tagName.toLowerCase()==="a"&&Rt(s).includes("noteref")){const l=s.getAttribute("href")??"";l.startsWith("#")&&r.push({id:l.slice(1),ref:s})}for(let c=s.firstElementChild;c;c=c.nextElementSibling)i(c,o)};i(t,!1);for(const s of r){const o=e.get(s.id);o&&(Xa(o,s.ref)||n.add(o))}}function Xg(t,e,n,r){const i={role:r},s=(e.getAttribute("title")??"").trim();s?i.text={plain:s,ssml:"",language:""}:n&&(i.text={plain:n.plain??"",ssml:n.ssml??"",language:n.language});const o=!!(i.text&&!dt(i.text)),a=!t.xmlParsed&&(If(e)||o&&e.firstChild!==null);if(!o&&!a){const u=nn(e);u&&(i.text={plain:u,ssml:"",language:""})}const c=Ir(e,t.docRoot),l=go(c);return l&&(i.textref=l),t.placeholder(e,"pagebreak",i),a}function Yg(t,e,n){const r={role:n},i=nn(e);i&&(r.text={plain:i,ssml:"",language:""});const s=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&s.startsWith("#")&&(o=s.slice(1)),s.startsWith("#")){const a=s.slice(1),c=t.ids.get(a);if(c&&!Xa(c,e)&&t.noterefDepth<3){const l=t.spawnChild(c);l.convert(c);const u=l.result();u.length>0&&(r.children=u.map(h=>{const d=Ja(h);return delete d.id,d}))}}!r.children&&s&&(r.children=[{textref:s}]),t.placeholder(e,"noteref",r,o||void 0)}function Qg(t,e,n,r){const i={};if(n.length>0&&(i.role=n),r)i.text={plain:r.plain??"",ssml:r.ssml??"",language:r.language};else{const o=nn(e);o&&(i.text={plain:o,ssml:"",language:""})}const s=e.getAttribute("href");s&&(i.textref=s),t.placeholder(e,n[0]??"link",i)}const Zg=3,ep=1,tp=new Set(["summary","dfn","span"]);function ns(t,e){return tp.has(t)&&e.length>0?!0:!Lf(t)}class Ht{xmlParsed;ids=new Map;suppressed=new Set;idAlloc=new Kg;noterefDepth=0;allowNode=null;selectorPredicate=null;domRangeEnabled=!1;textFragmentEnabled=!1;docRoot=null;root=new Ct;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,n=1){const r=new Ht(this.xmlParsed);return r.ids=this.ids,r.suppressed=this.suppressed,r.idAlloc=this.idAlloc,r.noterefDepth=this.noterefDepth+n,r.allowNode=e,r.docRoot=this.docRoot,r.selectorPredicate=this.selectorPredicate,r.domRangeEnabled=this.domRangeEnabled,r.textFragmentEnabled=this.textFragmentEnabled,r}prescan(e){Jg(e,this.ids,this.suppressed)}convert(e){this.prescan(e),this.walk(e)}convertChildren(e){this.prescan(e);for(let n=e.firstChild;n;n=n.nextSibling)this.walk(n);this.flushText()}result(){const e=this.root.finalize();return!e.children||e.children.length===0?rr(e)?[]:[ir(e)]:e.children.map(ir)}descend(e,n){const r=new Ct;r.el=e,r.noText=this.foldedCaptions.has(e)||(!Ka(e)||n.includes("caption"))&&this.current.noText,this.current.children.push(r),this.current=r}appendChild(e){e.noText=this.current.noText,this.current.children.push(e)}walk(e){if(e.nodeType===Zg){this.text(e);return}if(e.nodeType!==ep)return;const n=e,r=this.current,i=this.head(n);if(!i)for(let s=n.firstChild;s;s=s.nextSibling)this.walk(s);this.tail(n,i,r)}head(e){const n=e.tagName.toLowerCase();if(Tf.has(n)||this.suppressed.has(e)&&e!==this.allowNode)return!0;const[r,i]=kf(e);if(!i&&e!==this.allowNode)return!0;const s=Rt(e);if((n==="img"||n==="svg")&&(s.includes("presentation")||r===null&&e.hasAttribute("alt")&&e.getAttribute("alt").trim()===""))return!0;if(n==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(s.includes("pagebreak"))return!Xg(this,e,r,s);if(n==="a"&&s.includes("noteref")&&e.getAttribute("href"))return Yg(this,e,s),!0;if(n==="a"&&e.getAttribute("href"))return Qg(this,e,s,r),!0;if(n==="img"){const c={role:s},l=e.getAttribute("src");return l&&(c.imgref=l),r&&(c.description=r.plain),this.placeholder(e,"image",c),!0}if(n==="audio"||n==="video"){const c={role:s};let l=e.getAttribute("src");if(!l){const u=e.querySelector(":scope > source[src]");u&&(l=u.getAttribute("src"))}return n==="audio"?l&&(c.audioref=l):l&&(c.videoref=l),r&&(c.description=r.plain),this.placeholder(e,n,c),!0}if(s.includes("image")||s.includes("math")){const c={role:s};return r&&(c.description=r.plain),this.placeholder(e,s.includes("math")?"math":"image",c),!0}if(!ns(n,s))return!1;this.flushText(),this.descend(e,s);const o=this.current.object;if(s.length>0&&(o.role=s),r)o.description=r.plain,s.includes("figure")&&(this.current.noText=!0);else if(s.includes("figure")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.current.noText=!0)}}else if(s.includes("table")){const c=this.implicitCaptionOf(e);if(c){const l=Ji(c);l&&(o.description=l,this.foldedCaptions.add(c))}}const a=e.getAttribute("id");return a&&(o.id=a),!1}implicitCaptionOf(e){for(let n=e.firstElementChild;n;n=n.nextElementSibling)if(Rt(n).includes("caption")&&!n.getAttribute("aria-labelledby"))return n;return null}tail(e,n,r){if(n)return;const i=e.tagName.toLowerCase(),s=Rt(e);ns(i,s)&&(this.flushText(),this.selectorPredicate?.(s)&&this.applyTextref(e),this.current=r)}applyTextref(e){const n=this.current.object,r=Ir(e,this.docRoot);if(n.textref=go(r),this.domRangeEnabled&&this.lastFlowRange){const i=r?{el:e,selector:r}:void 0,s=jg(this.lastFlowRange,this.docRoot,i);s&&(n.textref=Da(s))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const i=this.docRoot.createRange();i.setStart(...this.lastFlowRange.first),i.setEnd(...this.lastFlowRange.last);const s=Hg(i);s&&(n.textref=`${n.textref??"#"}${Ia(s)}`)}}text(e){if(this.current.noText)return;const n=e.nodeValue??"";if(/^\s*$/.test(n)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=Ve(n,this.flowEndsWithSpace),this.updateFlowSpace());return}const r=this.textContext(e);if(Od(r,this.currentCtx)||(this.closeSegment(),this.currentCtx=r),this.textAcc+=Ve(n,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const i=e;this.flowFirstNode===null&&(this.flowFirstNode=i,this.flowFirstOffset=n.search(/\S/)),this.flowLastNode=i,this.flowLastOffset=n.length-(n.match(/\s+$/)?.[0].length??0)}}textContext(e){const n={lang:Xi(e.parentElement),tag:""};for(let r=e.parentElement;r&&r!==this.current.el;r=r.parentElement){const[i,s]=Af(r.tagName.toLowerCase());if(i&&i!=="break"){n.tag=i,n.attrs=s;break}}return n}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,n,r,i){if(rr(r))return;const s=new Ct;if(s.el=e,s.object=r,this.current.noText){this.appendChild(s);return}this.closeSegment(),this.pendingChildren.push(s),this.segments.push({kind:"placeholder",tag:n,child:s,candidateID:i??e.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let e=this.segments;const n=this.pendingChildren,r=this.flowFirstNode,i=this.flowFirstOffset,s=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 w=S.text.replace(/^\s+/,"");if(w===""){e=e.slice(1);continue}e=[{...S,text:w},...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 w=S.text.replace(/\s+$/,"");if(w===""){e=e.slice(0,-1);continue}e=[...e.slice(0,-1),{...S,text:w}]}break}if(!e.some(S=>S.kind==="text"&&S.text.trim()!=="")){for(const S of n)this.appendChild(S);return}const c=[];for(const S of e)if(S.kind==="text"&&S.text.trim()!==""){const w=S.ctx.lang;c.includes(w)||c.push(w)}let l=Xi(this.current.el??null);c.length===1&&c[0]!==""&&(l=c[0]);let u=!1;for(const S of e)if(S.kind!=="text"||S.ctx.tag!==""||S.ctx.lang!==l){u=!0;break}if(u&&l===""&&(l="en"),u)for(const S of e){if(S.kind!=="placeholder")continue;let w=S.candidateID;(!w||!this.idAlloc.claim(w))&&(w=this.idAlloc.allocate(S.tag,T=>this.ids.has(T))),S.child.object.id=w}let h="",d=!1,g=!1,p=!1,m=!1;for(const S of e)if(S.kind==="text"){const w=S.text.startsWith(" "),T=S.text.replace(/^ +| +$/g,"");if(T===""){m=!0;continue}let F=!1;if(h.length>0){const L=d||m||w;g?F=!0:p?F=L&&!Qt(T):F=L}F&&(h+=" "),h+=T,d=S.text.endsWith(" "),g=!1,p=!1,m=!1}else S.kind==="break"?g=!0:S.kind==="placeholder"&&(p=!0);const b=e.some(S=>S.kind==="placeholder");this.lastFlowText=h.trim();const x={plain:u&&!b?"":h.trim(),ssml:"",language:l};if(u){let S="";for(const w of e)if(w.kind==="text"){let T=w.ctx.tag,F=w.ctx.attrs;if(w.ctx.lang!==l&&w.ctx.lang!==""&&(T="lang",F=void 0),T){S+=`<${T}`;for(const[L,X]of Object.entries(F??{}))S+=` ${L}="${En(X)}"`;w.ctx.lang!==l&&w.ctx.lang!==""&&(S+=` xml:lang="${En(w.ctx.lang)}"`),S+=`>${zt(w.text)}</${T}>`}else S+=zt(w.text)}else w.kind==="break"?S+="<break/>":w.kind==="placeholder"&&(S+=`<readium:${w.tag} id="${En(w.child.object.id)}" />`);x.ssml=S}const A=new Ct;A.object={text:x};for(const S of n)A.children.push(S);this.appendChild(A),r&&s&&(this.lastFlowRange={first:[r,i],last:[s,o]})}}const np=/<body[\s>]/i;function po(t,e,n){const{predicate:r,domRange:i,textFragment:s}=Gg(n?.textrefs);if(typeof t!="string"){const u=e??(t.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),h=new Ht(u==="application/xhtml+xml");return h.selectorPredicate=r,h.domRangeEnabled=i,h.textFragmentEnabled=s,h.docRoot=t.ownerDocument,h.convert(t),h.result()}const o=e??$f(t),a=new DOMParser().parseFromString(t,o),c=new Ht(o==="application/xhtml+xml");c.selectorPredicate=r,c.textFragmentEnabled=s,c.docRoot=a;const l=a.querySelector("body");return l&&!np.test(t)?c.convertChildren(l):c.convert(l??a.documentElement),c.result()}function rp(t,e,n){return{guided:po(t,e,n)}}exports.BUILTIN_DECORATION_TYPES=ca;exports.BooleanPreference=va;exports.DecorationController=ma;exports.DecorationLayout=aa;exports.DecorationStyleType=R;exports.DecorationWidth=sa;exports.Decorator=la;exports.DirectCommsChannel=fa;exports.DirectCommsFrame=ga;exports.DirectCommsHost=pa;exports.EnumPreference=tt;exports.FallbackEngineProvider=ju;exports.FallbackSpeechEngine=Rs;exports.Locator=Sr;exports.LocatorLocations=ue;exports.LocatorText=br;exports.Preference=ht;exports.RangePreference=nt;exports.ReadiumSpeechDecorationController=ba;exports.ReadiumSpeechNavigator=df;exports.ReadiumSpeechProviderRegistry=td;exports.SpeechDefaults=Sa;exports.SpeechPreferences=Ue;exports.SpeechPreferencesEditor=Wn;exports.SpeechServerAudioDecodeError=gr;exports.SpeechServerEngine=As;exports.SpeechServerEngineProvider=Vu;exports.SpeechServerError=qe;exports.SpeechServerNetworkError=pr;exports.SpeechServerStallError=fr;exports.SpeechSettings=Kn;exports.StringArrayPreference=Hn;exports.WebSpeechEngine=Ln;exports.WebSpeechEngineProvider=ku;exports.WebSpeechVoiceManager=P;exports.blockLevelRoles=qa;exports.chineseVariantMap=Pe;exports.chunkPlainText=xs;exports.chunkSsmlText=Es;exports.contextualizationShapesAtVerbosity=ka;exports.contextualizedAtVerbosity=Ca;exports.createLocator=ya;exports.decodeCssSelectorFragment=Na;exports.decodeDomRangeFragment=Fa;exports.decodeTextref=tr;exports.decorationsEqual=ha;exports.defaultContextualizations=kr;exports.encodeCssSelectorFragment=Ra;exports.encodeDomRangeFragment=Da;exports.extractUtterances=uf;exports.isRecoverableFailure=Ts;exports.makeGnd=rp;exports.mapServerVoice=dr;exports.mimeTypeForFormat=Cs;exports.parseMarkup=po;exports.resolveDecorationForWire=jn;exports.selectBitrate=Os;exports.selectFormat=ks;exports.setupDecorations=ed;exports.shapeableRoles=rd;exports.skippableRoles=jd;exports.skippedAtVerbosity=Ea;exports.supportsDecorationStyle=ua;exports.toSpeechServerError=Fe;
20
+ }`;break}case E.Highlight:default:g=`::highlight(${c}) {
21
+ color: ${yi(f,d)};
22
+ background-color: ${f};
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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},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(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/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;