@readium/navigator 2.5.2-beta.5 → 2.5.3

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 (31) hide show
  1. package/dist/{ReadiumCSS-after-DBPN8It0.js → ReadiumCSS-after-BYNAMW5u.js} +4 -4
  2. package/dist/{ReadiumCSS-after-CVNJvQab.js → ReadiumCSS-after-C8SjJ_Rf.js} +4 -4
  3. package/dist/{ReadiumCSS-after-CPAYSG9F.js → ReadiumCSS-after-Dzd22Ssm.js} +6 -7
  4. package/dist/{ReadiumCSS-after-Cpw6SSeZ.js → ReadiumCSS-after-b-ykC0_O.js} +11 -12
  5. package/dist/ReadiumCSS-before-6kD9Qj82.js +529 -0
  6. package/dist/ReadiumCSS-before-CvMFpmud.js +529 -0
  7. package/dist/ReadiumCSS-before-crwPhKrV.js +529 -0
  8. package/dist/ReadiumCSS-before-usMdEglk.js +530 -0
  9. package/dist/{ReadiumCSS-default-BMLfH2r9.js → ReadiumCSS-default-BVp3Ygi2.js} +1 -1
  10. package/dist/{ReadiumCSS-default-C_BHdXWz.js → ReadiumCSS-default-CL_hP__L.js} +1 -1
  11. package/dist/{ReadiumCSS-default-BTgk8NbH.js → ReadiumCSS-default-nJgSC4Z_.js} +1 -1
  12. package/dist/{ReadiumCSS-default-C7kHIm6s.js → ReadiumCSS-default-vv7hNCaM.js} +1 -1
  13. package/dist/index.js +483 -448
  14. package/dist/index.umd.cjs +702 -289
  15. package/package.json +2 -2
  16. package/src/Navigator.ts +5 -0
  17. package/src/audio/AudioNavigator.ts +3 -3
  18. package/src/epub/EpubNavigator.ts +1 -5
  19. package/src/epub/preferences/EpubPreferencesEditor.ts +6 -6
  20. package/src/helpers/lineLength.ts +1 -1
  21. package/src/preferences/Types.ts +21 -1
  22. package/src/webpub/WebPubNavigator.ts +2 -3
  23. package/types/src/Navigator.d.ts +4 -1
  24. package/types/src/audio/AudioNavigator.d.ts +3 -3
  25. package/types/src/epub/EpubNavigator.d.ts +2 -5
  26. package/types/src/preferences/Types.d.ts +15 -0
  27. package/types/src/webpub/WebPubNavigator.d.ts +2 -2
  28. package/dist/ReadiumCSS-before-CA1r4W7i.js +0 -425
  29. package/dist/ReadiumCSS-before-D5x0zuZP.js +0 -425
  30. package/dist/ReadiumCSS-before-DXNoxSjL.js +0 -426
  31. package/dist/ReadiumCSS-before-DtkzLMzT.js +0 -425
@@ -1,19 +1,19 @@
1
- (function(S,me){typeof exports=="object"&&typeof module<"u"?me(exports):typeof define=="function"&&define.amd?define(["exports"],me):(S=typeof globalThis<"u"?globalThis:S||self,me(S.navigator={}))})(this,(function(S){"use strict";var ae;const w=class w{constructor(e){this.uri=e}static deserialize(e){if(!(!e||typeof e!="string"))return new w(e)}serialize(){return this.uri}get isWCAGLevelA(){return this===w.EPUB_A11Y_10_WCAG_20_A||this===w.EPUB_A11Y_11_WCAG_20_A||this===w.EPUB_A11Y_11_WCAG_21_A||this===w.EPUB_A11Y_11_WCAG_22_A}get isWCAGLevelAA(){return this===w.EPUB_A11Y_10_WCAG_20_AA||this===w.EPUB_A11Y_11_WCAG_20_AA||this===w.EPUB_A11Y_11_WCAG_21_AA||this===w.EPUB_A11Y_11_WCAG_22_AA}get isWCAGLevelAAA(){return this===w.EPUB_A11Y_10_WCAG_20_AAA||this===w.EPUB_A11Y_11_WCAG_20_AAA||this===w.EPUB_A11Y_11_WCAG_21_AAA||this===w.EPUB_A11Y_11_WCAG_22_AAA}};w.EPUB_A11Y_10_WCAG_20_A=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"),w.EPUB_A11Y_10_WCAG_20_AA=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"),w.EPUB_A11Y_10_WCAG_20_AAA=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"),w.EPUB_A11Y_11_WCAG_20_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"),w.EPUB_A11Y_11_WCAG_20_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"),w.EPUB_A11Y_11_WCAG_20_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"),w.EPUB_A11Y_11_WCAG_21_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"),w.EPUB_A11Y_11_WCAG_21_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"),w.EPUB_A11Y_11_WCAG_21_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"),w.EPUB_A11Y_11_WCAG_22_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"),w.EPUB_A11Y_11_WCAG_22_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"),w.EPUB_A11Y_11_WCAG_22_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");let me=w;const C=class C{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new C(e)}serialize(){return this.value}};C.AUDITORY=new C("auditory"),C.CHART_ON_VISUAL=new C("chartOnVisual"),C.CHEM_ON_VISUAL=new C("chemOnVisual"),C.COLOR_DEPENDENT=new C("colorDependent"),C.DIAGRAM_ON_VISUAL=new C("diagramOnVisual"),C.MATH_ON_VISUAL=new C("mathOnVisual"),C.MUSIC_ON_VISUAL=new C("musicOnVisual"),C.TACTILE=new C("tactile"),C.TEXT_ON_VISUAL=new C("textOnVisual"),C.TEXTUAL=new C("textual"),C.VISUAL=new C("visual");let fn=C;const D=class D{constructor(e){if(typeof e=="string"){if(!D.VALID_MODES.has(e.toLowerCase()))return;this.value=e.toLowerCase()}else{const t=e.filter(n=>D.VALID_MODES.has(n.toLowerCase()));if(t.length===0)return;this.value=Array.from(new Set(t))}}static deserialize(e){if(!e)return;if(typeof e=="string")return new D(e);if(!Array.isArray(e))return;const t=e.filter(n=>n?D.VALID_MODES.has(n.toLowerCase()):!1);if(t.length!==0)return new D(t)}serialize(){return this.value}};D.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),D.AUDITORY=new D("auditory"),D.TACTILE=new D("tactile"),D.TEXTUAL=new D("textual"),D.VISUAL=new D("visual");let yn=D;const y=class y{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new y(e)}serialize(){return this.value}};y.NONE=new y("none"),y.ANNOTATIONS=new y("annotations"),y.ARIA=new y("ARIA"),y.INDEX=new y("index"),y.PAGE_BREAK_MARKERS=new y("pageBreakMarkers"),y.PAGE_NAVIGATION=new y("pageNavigation"),y.PRINT_PAGE_NUMBERS=new y("printPageNumbers"),y.READING_ORDER=new y("readingOrder"),y.STRUCTURAL_NAVIGATION=new y("structuralNavigation"),y.TABLE_OF_CONTENTS=new y("tableOfContents"),y.TAGGED_PDF=new y("taggedPDF"),y.ALTERNATIVE_TEXT=new y("alternativeText"),y.AUDIO_DESCRIPTION=new y("audioDescription"),y.CAPTIONS=new y("captions"),y.CLOSED_CAPTIONS=new y("closedCaptions"),y.DESCRIBED_MATH=new y("describedMath"),y.LONG_DESCRIPTION=new y("longDescription"),y.OPEN_CAPTIONS=new y("openCaptions"),y.SIGN_LANGUAGE=new y("signLanguage"),y.TRANSCRIPT=new y("transcript"),y.DISPLAY_TRANSFORMABILITY=new y("displayTransformability"),y.SYNCHRONIZED_AUDIO_TEXT=new y("synchronizedAudioText"),y.TIMING_CONTROL=new y("timingControl"),y.UNLOCKED=new y("unlocked"),y.CHEM_ML=new y("ChemML"),y.LATEX=new y("latex"),y.LATEX_CHEMISTRY=new y("latex-chemistry"),y.MATH_ML=new y("MathML"),y.MATH_ML_CHEMISTRY=new y("MathML-chemistry"),y.TTS_MARKUP=new y("ttsMarkup"),y.HIGH_CONTRAST_AUDIO=new y("highContrastAudio"),y.HIGH_CONTRAST_DISPLAY=new y("highContrastDisplay"),y.LARGE_PRINT=new y("largePrint"),y.BRAILLE=new y("braille"),y.TACTILE_GRAPHIC=new y("tactileGraphic"),y.TACTILE_OBJECT=new y("tactileObject"),y.FULL_RUBY_ANNOTATIONS=new y("fullRubyAnnotations"),y.HORIZONTAL_WRITING=new y("horizontalWriting"),y.RUBY_ANNOTATIONS=new y("rubyAnnotations"),y.VERTICAL_WRITING=new y("verticalWriting"),y.WITH_ADDITIONAL_WORD_SEGMENTATION=new y("withAdditionalWordSegmentation"),y.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new y("withoutAdditionalWordSegmentation");let Je=y;const x=class x{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new x(e)}serialize(){return this.value}};x.FLASHING=new x("flashing"),x.NO_FLASHING_HAZARD=new x("noFlashingHazard"),x.UNKNOWN_FLASHING_HAZARD=new x("unknownFlashingHazard"),x.MOTION_SIMULATION=new x("motionSimulation"),x.NO_MOTION_SIMULATION_HAZARD=new x("noMotionSimulationHazard"),x.UNKNOWN_MOTION_SIMULATION_HAZARD=new x("unknownMotionSimulationHazard"),x.SOUND=new x("sound"),x.NO_SOUND_HAZARD=new x("noSoundHazard"),x.UNKNOWN_SOUND_HAZARD=new x("unknownSoundHazard"),x.UNKNOWN=new x("unknown"),x.NONE=new x("none");let Sn=x;const L=class L{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new L(e)}serialize(){return this.value}};L.NONE=new L("none"),L.DOCUMENTED=new L("documented"),L.LEGAL=new L("legal"),L.TEMPORARY=new L("temporary"),L.TECHNICAL=new L("technical"),L.EAA_DISPROPORTIONATE_BURDEN=new L("eaa-disproportionate-burden"),L.EAA_FUNDAMENTAL_ALTERATION=new L("eaa-fundamental-alteration"),L.EAA_MICROENTERPRISE=new L("eaa-microenterprise"),L.EAA_TECHNICAL_IMPOSSIBILITY=new L("eaa-technical-impossibility"),L.EAA_TEMPORARY=new L("eaa-temporary");let bn=L;const _n=["en","ar","da","fr","it","pt_PT","sv"],io={publication:JSON.parse(`{"format":{"audiobook":"Audiobook","audiobookJSON":"Audiobook Manifest","cbz":"Comic Book Archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"LCP Protected Audiobook","lcpdf":"LCP Protected PDF","lcpl":"LCP License Document","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_one":"audiobook","audiobook_other":"audiobooks","book_one":"book","book_other":"books","comic_one":"comic","comic_other":"comics","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"No information is available","publisher-contact":"For more information about the accessibility of this product, please contact the publisher: ","title":"Accessibility summary"},"additional-accessibility-information":{"aria":{"compact":"ARIA roles included","descriptive":"Content is enhanced with ARIA roles to optimize organization and facilitate navigation"},"audio-descriptions":"Audio descriptions","braille":"Braille","color-not-sole-means-of-conveying-information":"Color is not the sole means of conveying information","dyslexia-readability":"Dyslexia readability","full-ruby-annotations":"Full ruby annotations","high-contrast-between-foreground-and-background-audio":"High contrast between foreground and background audio","high-contrast-between-text-and-background":"High contrast between foreground text and background","large-print":"Large print","page-breaks":{"compact":"Page breaks included","descriptive":"Page breaks included from the original print source"},"ruby-annotations":"Some Ruby annotations","sign-language":"Sign language","tactile-graphics":{"compact":"Tactile graphics included","descriptive":"Tactile graphics have been integrated to facilitate access to visual elements for blind people"},"tactile-objects":"Tactile 3D objects","text-to-speech-hinting":"Text-to-speech hinting provided","title":"Additional accessibility information","ultra-high-contrast-between-text-and-background":"Ultra high contrast between text and background","visible-page-numbering":"Visible page numbering","without-background-sounds":"Without background sounds"},"conformance":{"a":{"compact":"This publication meets minimum accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level A standard"},"aa":{"compact":"This publication meets accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AA standard"},"aaa":{"compact":"This publication exceeds accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AAA standard"},"certifier":"The publication was certified by ","certifier-credentials":"The certifier's credential is ","details":{"certification-info":"The publication was certified on ","certifier-report":"For more information refer to the certifier's report","claim":"This publication claims to meet","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Level A","level-aa":"Level AA","level-aaa":"Level AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detailed conformance information","no":"No information is available","title":"Conformance","unknown-standard":"Conformance to accepted standards for accessibility of this publication cannot be determined"},"hazards":{"flashing":{"compact":"Flashing content","descriptive":"The publication contains flashing content that can cause photosensitive seizures"},"flashing-none":{"compact":"No flashing hazards","descriptive":"The publication does not contain flashing content that can cause photosensitive seizures"},"flashing-unknown":{"compact":"Flashing hazards not known","descriptive":"The presence of flashing content that can cause photosensitive seizures could not be determined"},"motion":{"compact":"Motion simulation","descriptive":"The publication contains motion simulations that can cause motion sickness"},"motion-none":{"compact":"No motion simulation hazards","descriptive":"The publication does not contain motion simulations that can cause motion sickness"},"motion-unknown":{"compact":"Motion simulation hazards not known","descriptive":"The presence of motion simulations that can cause motion sickness could not be determined"},"no-metadata":"No information is available","none":{"compact":"No hazards","descriptive":"The publication contains no hazards"},"sound":{"compact":"Sounds","descriptive":"The publication contains sounds that can cause sensitivity issues"},"sound-none":{"compact":"No sound hazards","descriptive":"The publication does not contain sounds that can cause sensitivity issues"},"sound-unknown":{"compact":"Sound hazards not known","descriptive":"The presence of sounds that can cause sensitivity issues could not be determined"},"title":"Hazards","unknown":"The presence of hazards is unknown"},"legal-considerations":{"exempt":{"compact":"Claims an accessibility exemption in some jurisdictions","descriptive":"This publication claims an accessibility exemption in some jurisdictions"},"no-metadata":"No information is available","title":"Legal considerations"},"navigation":{"index":{"compact":"Index","descriptive":"Index with links to referenced entries"},"no-metadata":"No information is available","page-navigation":{"compact":"Go to page","descriptive":"Page list to go to pages from the print source version"},"structural":{"compact":"Headings","descriptive":"Elements such as headings, tables, etc for structured navigation"},"title":"Navigation","toc":{"compact":"Table of contents","descriptive":"Table of contents to all chapters of the text via links"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Chemical formulas in LaTeX","descriptive":"Chemical formulas in accessible format (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Chemical formulas in MathML","descriptive":"Chemical formulas in accessible format (MathML)"},"accessible-math-as-latex":{"compact":"Math as LaTeX","descriptive":"Math formulas in accessible format (LaTeX)"},"accessible-math-described":"Text descriptions of math are provided","closed-captions":{"compact":"Videos have closed captions","descriptive":"Videos included in publications have closed captions"},"extended-descriptions":"Information-rich images are described by extended descriptions","math-as-mathml":{"compact":"Math as MathML","descriptive":"Math formulas in accessible format (MathML)"},"open-captions":{"compact":"Videos have open captions","descriptive":"Videos included in publications have open captions"},"title":"Rich content","transcript":"Transcript(s) provided","unknown":"No information is available"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Has alternative text","descriptive":"Has alternative text descriptions for images"},"no-metadata":"No information about nonvisual reading is available","none":{"compact":"Not readable in read aloud or dynamic braille","descriptive":"The content is not readable as read aloud speech or dynamic braille"},"not-fully":{"compact":"Not fully readable in read aloud or dynamic braille","descriptive":"Not all of the content will be readable as read aloud speech or dynamic braille"},"readable":{"compact":"Readable in read aloud or dynamic braille","descriptive":"All content can be read as read aloud speech or dynamic braille"}},"prerecorded-audio":{"complementary":{"compact":"Prerecorded audio clips","descriptive":"Prerecorded audio clips are embedded in the content"},"no-metadata":"No information about prerecorded audio is available","only":{"compact":"Prerecorded audio only","descriptive":"Audiobook with no text alternative"},"synchronized":{"compact":"Prerecorded audio synchronized with text","descriptive":"All the content is available as prerecorded audio synchronized with text"}},"title":"Ways of reading","visual-adjustments":{"modifiable":{"compact":"Appearance can be modified","descriptive":"Appearance of the text and page layout can be modified according to the capabilities of the reading system (font family and font size, spaces between paragraphs, sentences, words, and letters, as well as color of background and text)"},"unknown":"No information about appearance modifiability is available","unmodifiable":{"compact":"Appearance cannot be modified","descriptive":"Text and page layout cannot be modified as the reading experience is close to a print version, but reading systems can still provide zooming options"}}}}},"altIdentifier_one":"alternate identifier","altIdentifier_other":"alternate identifiers","artist_one":"artist","artist_other":"artists","author_one":"author","author_other":"authors","collection_one":"editorial collection","collection_other":"editorial collections","colorist_one":"colorist","colorist_other":"colorists","contributor_one":"contributor","contributor_other":"contributors","description":"description","duration":"duration","editor_one":"editor","editor_other":"editors","identifier_one":"identifier","identifier_other":"identifiers","illustrator_one":"illustrator","illustrator_other":"illustrators","imprint_one":"imprint","imprint_other":"imprints","inker_one":"inker","inker_other":"inkers","language_one":"language","language_other":"languages","letterer_one":"letterer","letterer_other":"letterers","modified":"modification date","narrator_one":"narrator","narrator_other":"narrators","numberOfPages":"print length","penciler_one":"penciler","penciler_other":"pencilers","published":"publication date","publisher_one":"publisher","publisher_other":"publishers","series_one":"series","series_other":"series","subject_one":"subject","subject_other":"subjects","subtitle":"subtitle","title":"title","translator_one":"translator","translator_other":"translators"}}`)},vn={fr:()=>Promise.resolve().then(()=>Fr),ar:()=>Promise.resolve().then(()=>Nr),da:()=>Promise.resolve().then(()=>Ir),it:()=>Promise.resolve().then(()=>Dr),pt_PT:()=>Promise.resolve().then(()=>Hr),sv:()=>Promise.resolve().then(()=>Wr)},wn=io?.publication?.metadata?.accessibility?.["display-guide"]||{};class pe{constructor(){this.currentLocaleCode="en",this.locale=wn,this.loadedLocales={},this.loadedLocales.en=wn}static getInstance(){return pe.instance||(pe.instance=new pe),pe.instance}async loadLocale(e){if(!_n.includes(e))return console.warn(`Locale '${e}' is not enabled`),!1;if(e in this.loadedLocales)return!0;try{if(!(e in vn))return console.warn(`Locale file not found for: ${e}`),!1;const i=(await vn[e]()).default?.publication?.metadata?.accessibility?.["display-guide"];return i?(this.loadedLocales[e]=i,!0):(console.warn(`No accessibility strings found in locale ${e}`),!1)}catch(t){return console.warn(`Failed to load locale ${e}:`,t),!1}}registerLocale(e,t){if(!e||typeof e!="string")throw new Error("Locale code must be a non-empty string");this.loadedLocales[e]=t}async setLocale(e){return e in this.loadedLocales||await this.loadLocale(e),e in this.loadedLocales?(this.locale=this.loadedLocales[e],this.currentLocaleCode=e,!0):(console.warn(`Locale '${e}' is not available`),!1)}getCurrentLocale(){return this.currentLocaleCode}getAvailableLocales(){return _n}getNestedValue(e,t){const n=t.split(".");let i=e;for(const o of n){if(i==null)return;i=i[o]}return i}getString(e){let t=this.getNestedValue(this.locale,e);return t===void 0&&this.currentLocaleCode!=="en"&&(t=this.getNestedValue(this.loadedLocales.en,e)),t!==void 0?typeof t=="string"?{compact:t,descriptive:t}:t:(console.warn(`Missing localization for key: ${e}`),{compact:"",descriptive:""})}}pe.getInstance();var b=(r=>(r.reflowable="reflowable",r.fixed="fixed",r.scrolled="scrolled",r))(b||{});class yt{constructor(e){this.algorithm=e.algorithm,this.compression=e.compression,this.originalLength=e.originalLength,this.profile=e.profile,this.scheme=e.scheme}static deserialize(e){if(e&&e.algorithm)return new yt({algorithm:e.algorithm,compression:e.compression,originalLength:e.originalLength,profile:e.profile,scheme:e.scheme})}serialize(){const e={algorithm:this.algorithm};return this.compression!==void 0&&(e.compression=this.compression),this.originalLength!==void 0&&(e.originalLength=this.originalLength),this.profile!==void 0&&(e.profile=this.profile),this.scheme!==void 0&&(e.scheme=this.scheme),e}}var X=(r=>(r.left="left",r.right="right",r.center="center",r))(X||{});let Y=class gn{constructor(e){this.otherProperties=e}get page(){return this.otherProperties.page}static deserialize(e){if(e)return new gn(e)}serialize(){return this.otherProperties}add(e){const t=Object.assign({},this.otherProperties);for(const n in e)t[n]=e[n];return new gn(t)}};Object.defineProperty(Y.prototype,"encryption",{get:function(){return yt.deserialize(this.otherProperties.encrypted)}});function oo(r){return r&&Array.isArray(r)?r:void 0}function Pn(r){return r&&typeof r=="string"?[r]:oo(r)}function Rn(r){return typeof r=="string"?new Date(r):void 0}function Qe(r){return isNaN(r)?void 0:r}function G(r){return Qe(r)!==void 0&&Math.sign(r)>=0?r:void 0}function ro(r){const e=new Array;return r.forEach(t=>e.push(t)),e}class g{constructor(e){let t,n,i=e.mediaType.replace(/\s/g,"").split(";");const o=i[0].split("/");if(o.length===2){if(t=o[0].toLowerCase().trim(),n=o[1].toLowerCase().trim(),t.length===0||n.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const a={};for(let m=1;m<i.length;m++){const f=i[m].split("=");if(f.length===2){const d=f[0].toLocaleLowerCase(),p=d==="charset"?f[1].toUpperCase():f[1];a[d]=p}}const s={},l=Object.keys(a);l.sort((m,f)=>m.localeCompare(f)),l.forEach(m=>s[m]=a[m]);let c="";for(const m in s){const f=s[m];c+=`;${m}=${f}`}const h=`${t}/${n}${c}`,u=s.encoding;this.string=h,this.type=t,this.subtype=n,this.parameters=s,this.encoding=u,this.name=e.name,this.fileExtension=e.fileExtension}static parse(e){return new g(e)}get structuredSyntaxSuffix(){const e=this.subtype.split("+");return e.length>1?`+${e[e.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(e){const t=typeof e=="string"?g.parse({mediaType:e}):e;if(!((this.type==="*"||this.type===t.type)&&(this.subtype==="*"||this.subtype===t.subtype)))return!1;const n=new Set(Object.entries(this.parameters).map(([o,a])=>`${o}=${a}`)),i=new Set(Object.entries(t.parameters).map(([o,a])=>`${o}=${a}`));for(const o of Array.from(n.values()))if(!i.has(o))return!1;return!0}matches(e){const t=typeof e=="string"?g.parse({mediaType:e}):e;return this.contains(t)||t.contains(this)}matchesAny(...e){for(const t of e)if(this.matches(t))return!0;return!1}equals(e){return this.string===e.string}get isZIP(){return this.matchesAny(g.ZIP,g.LCP_PROTECTED_AUDIOBOOK,g.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(g.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(g.OPDS1,g.OPDS1_ENTRY,g.OPDS2,g.OPDS2_PUBLICATION,g.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(g.HTML,g.XHTML)}get isBitmap(){return this.matchesAny(g.AVIF,g.BMP,g.GIF,g.JPEG,g.PNG,g.TIFF,g.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(g.READIUM_AUDIOBOOK_MANIFEST,g.DIVINA_MANIFEST,g.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(g.READIUM_AUDIOBOOK,g.READIUM_AUDIOBOOK_MANIFEST,g.CBZ,g.DIVINA,g.DIVINA_MANIFEST,g.EPUB,g.LCP_PROTECTED_AUDIOBOOK,g.LCP_PROTECTED_PDF,g.LPF,g.PDF,g.W3C_WPUB_MANIFEST,g.READIUM_WEBPUB,g.READIUM_WEBPUB_MANIFEST,g.ZAB)}static get AAC(){return g.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return g.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return g.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return g.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get AVIF(){return g.parse({mediaType:"image/avif",fileExtension:"avif"})}static get BINARY(){return g.parse({mediaType:"application/octet-stream"})}static get BMP(){return g.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return g.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return g.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return g.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return g.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return g.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return g.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return g.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return g.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return g.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return g.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return g.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return g.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return g.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return g.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return g.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return g.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return g.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return g.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return g.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return g.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return g.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return g.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return g.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return g.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return g.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return g.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return g.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return g.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return g.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return g.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return g.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return g.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return g.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return g.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return g.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return g.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return g.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return g.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return g.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return g.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return g.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return g.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return g.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return g.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return g.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return g.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return g.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return g.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return g.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return g.parse({mediaType:"application/zip",fileExtension:"zip"})}}class kn{constructor(e){this.uri=e,this.parameters=this.getParameters(e)}getParameters(e){const t=/\{\??([^}]+)\}/g,n=e.match(t);return n?new Set(n.join(",").replace(t,"$1").split(",").map(i=>i.trim())):new Set}expand(e){const t=i=>i.split(",").map(o=>{const a=e[o];return a?encodeURIComponent(a):""}).join(","),n=i=>"?"+i.split(",").map(o=>{const a=o.split("=")[0],s=e[a];return s?`${a}=${encodeURIComponent(s)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...i)=>i[1]?n(i[2]):t(i[2]))}}class k{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=Qe(e.progression),n=Qe(e.totalProgression),i=Qe(e.position),o=new Map,a=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(e).forEach(([s,l])=>{a.has(s)||o.set(s,l)}),new k({fragments:Pn(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:n!==void 0&&n>=0&&n<=1?n:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:o.size===0?void 0:o})}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,n)=>e[n]=t),e}}class oe{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new oe({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}}class F{constructor(e){this.href=e.href,this.type=e.type,this.title=e.title,this.locations=e.locations?e.locations:new k({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new F({href:e.href,type:e.type,title:e.title,locations:k.deserialize(e.locations),text:oe.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 F({href:this.href,type:this.type,title:this.title,text:this.text,locations:new k({...this.locations,...e})})}}class V{constructor(e){this.href=e.href,this.templated=e.templated,this.type=e.type,this.title=e.title,this.rels=e.rels,this.properties=e.properties,this.height=e.height,this.width=e.width,this.size=e.size,this.duration=e.duration,this.bitrate=e.bitrate,this.languages=e.languages,this.alternates=e.alternates,this.children=e.children}static deserialize(e){if(!(!e||typeof e.href!="string"))return new V({href:e.href,templated:e.templated,type:e.type,title:e.title,rels:e.rel?Array.isArray(e.rel)?new Set(e.rel):new Set([e.rel]):void 0,properties:Y.deserialize(e.properties),height:G(e.height),width:G(e.width),size:G(e.size),duration:G(e.duration),bitrate:G(e.bitrate),languages:Pn(e.language),alternates:et.deserialize(e.alternate),children:et.deserialize(e.children)})}serialize(){const e={href:this.href};return this.templated!==void 0&&(e.templated=this.templated),this.type!==void 0&&(e.type=this.type),this.title!==void 0&&(e.title=this.title),this.rels&&(e.rel=ro(this.rels)),this.properties&&(e.properties=this.properties.serialize()),this.height!==void 0&&(e.height=this.height),this.width!==void 0&&(e.width=this.width),this.size!==void 0&&(e.size=this.size),this.duration!==void 0&&(e.duration=this.duration),this.bitrate!==void 0&&(e.bitrate=this.bitrate),this.languages&&(e.language=this.languages),this.alternates&&(e.alternate=this.alternates.serialize()),this.children&&(e.children=this.children.serialize()),e}get mediaType(){return this.type!==void 0?g.parse({mediaType:this.type}):g.BINARY}toURL(e){const t=this.href.replace(/^(\/)/,"");if(t.length===0)return;let n=e||"/";return n.startsWith("/")&&(n="file://"+n),new URL(t,n).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new kn(this.href).parameters:new Set}expandTemplate(e){return new V({href:new kn(this.href).expand(e),templated:!1})}addProperties(e){const t=V.deserialize(this.serialize());return t.properties=t.properties?t.properties?.add(e):new Y(e),t}get locator(){let e=this.href.split("#");return new F({href:e.length>0&&e[0]!==void 0?e[0]:this.href,type:this.type??"",title:this.title,locations:new k({fragments:e.length>1&&e[1]!==void 0?[e[1]]:[]})})}}class et{constructor(e){this.items=e}static deserialize(e){if(e&&Array.isArray(e))return new et(e.map(t=>V.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(e=>e.serialize())}findWithRel(e){const t=n=>n.rels&&n.rels.has(e);return this.items.find(t)}filterByRel(e){const t=n=>n.rels&&n.rels.has(e);return this.items.filter(t)}findWithHref(e){const t=n=>n.href===e;return this.items.find(t)}findIndexWithHref(e){const t=n=>n.href===e;return this.items.findIndex(t)}findWithMediaType(e){const t=n=>n.mediaType.matches(e);return this.items.find(t)}filterByMediaType(e){const t=n=>n.mediaType.matches(e);return this.items.filter(t)}filterByMediaTypes(e){const t=n=>{for(const i of e)if(n.mediaType.matches(i))return!0;return!1};return this.items.filter(t)}everyIsAudio(){const e=t=>t.mediaType.isAudio;return this.items.length>0&&this.items.every(e)}everyIsBitmap(){const e=t=>t.mediaType.isBitmap;return this.items.length>0&&this.items.every(e)}everyIsHTML(){const e=t=>t.mediaType.isHTML;return this.items.length>0&&this.items.every(e)}everyIsVideo(){const e=t=>t.mediaType.isVideo;return this.items.length>0&&this.items.every(e)}everyMatchesMediaType(e){return Array.isArray(e)?this.items.length>0&&this.items.every(t=>{for(const n of e)return t.mediaType.matches(n);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(e))}filterLinksHasType(){return this.items.filter(e=>e.type)}}var En=(r=>(r.EPUB="https://readium.org/webpub-manifest/profiles/epub",r.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",r.DIVINA="https://readium.org/webpub-manifest/profiles/divina",r.PDF="https://readium.org/webpub-manifest/profiles/pdf",r))(En||{}),N=(r=>(r.ltr="ltr",r.rtl="rtl",r))(N||{});Y.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class tt{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=G(e.textNodeIndex);if(t===void 0)return;let n=G(e.charOffset);return n===void 0&&(n=G(e.offset)),new tt({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:n})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}}class St{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=tt.deserialize(e.start);if(t)return new St({start:t,end:tt.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}}k.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},k.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},k.prototype.getDomRange=function(){return St.deserialize(this.otherLocations?.get("domRange"))},k.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},k.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(e=>e.length&&!e.includes("="));if(!r){const e=this.fragmentParameters();e.has("id")?r=e.get("id"):e.has("name")&&(r=e.get("name"))}return r?.startsWith("#")?r.slice(1):r},k.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},k.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},k.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const e=r.get("xywh").split(",").map(t=>parseInt(t));if(e.length===4&&!e.some(isNaN))return e};class bt{constructor(e){this.currency=e.currency,this.value=e.value}static deserialize(e){if(!e)return;let t=e.currency;if(!(t&&typeof t=="string"&&t.length>0))return;let n=G(e.value);if(n!==void 0)return new bt({currency:t,value:n})}serialize(){return{currency:this.currency,value:this.value}}}class ze{constructor(e){this.type=e.type,this.children=e.children}static deserialize(e){if(e&&e.type)return new ze({type:e.type,children:ze.deserializeArray(e.children)})}static deserializeArray(e){if(Array.isArray(e))return e.map(t=>ze.deserialize(t)).filter(t=>t!==void 0)}serialize(){const e={type:this.type};return this.children&&(e.children=this.children.map(t=>t.serialize())),e}}class _t{constructor(e){this.total=e.total,this.position=e.position}static deserialize(e){if(e)return new _t({total:G(e.total),position:G(e.position)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.position!==void 0&&(e.position=this.position),e}}class vt{constructor(e){this.total=e.total,this.available=e.available}static deserialize(e){if(e)return new vt({total:G(e.total),available:G(e.available)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.available!==void 0&&(e.available=this.available),e}}class wt{constructor(e){this.state=e.state,this.since=e.since,this.until=e.until}static deserialize(e){if(e&&e.state)return new wt({state:e.state,since:Rn(e.since),until:Rn(e.until)})}serialize(){const e={state:this.state};return this.since!==void 0&&(e.since=this.since.toISOString()),this.until!==void 0&&(e.until=this.until.toISOString()),e}}Y.prototype.getNumberOfItems=function(){return G(this.otherProperties.numberOfItems)},Y.prototype.getPrice=function(){return bt.deserialize(this.otherProperties.price)},Y.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(e=>ze.deserialize(e)).filter(e=>e!==void 0)},Y.prototype.getHolds=function(){return _t.deserialize(this.otherProperties.holds)},Y.prototype.getCopies=function(){return vt.deserialize(this.otherProperties.copies)},Y.prototype.getAvailability=function(){return wt.deserialize(this.otherProperties.availability)},Y.prototype.getAuthenticate=function(){return V.deserialize(this.otherProperties.authenticate)};const ao="CssSelectorGenerator";function Cn(r="unknown problem",...e){console.warn(`${ao}: ${r}`,...e)}function so(r){return r instanceof RegExp}function lo(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function co(r){const e=r.map(t=>{if(so(t))return n=>t.test(n);if(typeof t=="function")return n=>{const i=t(n);return typeof i!="boolean"?(Cn("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):i};if(typeof t=="string"){const n=new RegExp("^"+lo(t)+"$");return i=>n.test(i)}return Cn("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(n=>n(t))}co(["class","id","ng-*"]);const ho=Math.pow(2,32),xn=()=>Math.round(Math.random()*ho).toString(36),Pt=()=>`${Math.round(performance.now())}-${xn()}-${xn()}`,ge=1;class uo{constructor(e){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=e,e.addEventListener("message",this.receiver)}receive(e){if(e.source===null)throw Error("Event source is null");if(typeof e.data!="object")return;const t=e.data;if(!(!("_readium"in t)||!t._readium||t._readium<=0)){if(t.key==="_ping"){if(!this.destination){if(this.destination=e.source,this.origin=e.origin,this.channelId=t._channel,t._readium!==ge){t._readium>ge?this.send("error",`received comms version ${t._readium} higher than ${ge}`):this.send("error",`received comms version ${t._readium} lower than ${ge}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(n=>this.send("log",n)),this.preLog=[]}return}else if(this.channelId){if(t._channel!==this.channelId||e.origin!==this.origin)return}else return;this.handle(t)}}handle(e){const t=this.registrar.get(e.key);if(!t||t.length===0){e.strict&&this.send("_unhandled",e);return}t.forEach(n=>n.cb(e.data,i=>{this.send("_ack",i,e.id)}))}register(e,t,n){Array.isArray(e)||(e=[e]),e.forEach(i=>{const o=this.registrar.get(i);if(o&&o.length>=0){if(o.find(s=>s.module===t))throw new Error(`Trying to register another callback for combination of event ${i} and module ${t}`);o.push({cb:n,module:t}),this.registrar.set(i,o)}else this.registrar.set(i,[{cb:n,module:t}])})}unregister(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{const i=this.registrar.get(n);!i||i.length===0||i.splice(i.findIndex(o=>o.module===t),1)})}unregisterAll(e){this.registrar.forEach((t,n)=>this.registrar.set(n,t.filter(i=>i.module!==e)))}log(...e){this.destination?this.send("log",e):this.preLog.push(e)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(e,t,n=void 0,i=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const o={_readium:ge,_channel:this.channelId,id:n??Pt(),key:e,data:t};try{this.destination.postMessage(o,{targetOrigin:this.origin,transfer:i})}catch(a){if(i.length>0)throw a;this.destination.postMessage(o,this.origin,i)}}}class fe{}function Ln(r){return r.split("").reverse().join("")}function mo(r,e,t){const n=Ln(e);return t.map(i=>{const o=Math.max(0,i.end-e.length-i.errors),a=Ln(r.slice(o,i.end));return{start:On(a,n,i.errors).reduce((l,c)=>i.end-c.end<l?i.end-c.end:l,i.end),end:i.end,errors:i.errors}})}function Rt(r){return(r|-r)>>31&1}function zn(r,e,t,n){let i=r.P[t],o=r.M[t];const a=n>>>31,s=e[t]|a,l=s|o,c=(s&i)+i^i|s;let h=o|~(c|i),u=i&c;const m=Rt(h&r.lastRowMask[t])-Rt(u&r.lastRowMask[t]);return h<<=1,u<<=1,u|=a,h|=Rt(n)-a,i=u|~(l|h),o=h&l,r.P[t]=i,r.M[t]=o,m}function On(r,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const n=[],i=32,o=Math.ceil(e.length/i)-1,a={P:new Uint32Array(o+1),M:new Uint32Array(o+1),lastRowMask:new Uint32Array(o+1)};a.lastRowMask.fill(1<<31),a.lastRowMask[o]=1<<(e.length-1)%i;const s=new Uint32Array(o+1),l=new Map,c=[];for(let m=0;m<256;m++)c.push(s);for(let m=0;m<e.length;m+=1){const f=e.charCodeAt(m);if(l.has(f))continue;const d=new Uint32Array(o+1);l.set(f,d),f<c.length&&(c[f]=d);for(let p=0;p<=o;p+=1){d[p]=0;for(let _=0;_<i;_+=1){const R=p*i+_;if(R>=e.length)continue;e.charCodeAt(R)===f&&(d[p]|=1<<_)}}}let h=Math.max(0,Math.ceil(t/i)-1);const u=new Uint32Array(o+1);for(let m=0;m<=h;m+=1)u[m]=(m+1)*i;u[o]=e.length;for(let m=0;m<=h;m+=1)a.P[m]=-1,a.M[m]=0;for(let m=0;m<r.length;m+=1){const f=r.charCodeAt(m);let d;f<c.length?d=c[f]:(d=l.get(f),typeof d>"u"&&(d=s));let p=0;for(let _=0;_<=h;_+=1)p=zn(a,d,_,p),u[_]+=p;if(u[h]-p<=t&&h<o&&(d[h+1]&1||p<0)){h+=1,a.P[h]=-1,a.M[h]=0;let _;if(h===o){const R=e.length%i;_=R===0?i:R}else _=i;u[h]=u[h-1]+_-p+zn(a,d,h,p)}else for(;h>0&&u[h]>=t+i;)h-=1;h===o&&u[h]<=t&&(u[h]<t&&n.splice(0,n.length),n.push({start:-1,end:m+1,errors:u[h]}),t=u[h])}return n}function po(r,e,t){const n=On(r,e,t);return mo(r,e,n)}function An(r,e,t){let n=0;const i=[];for(;n!==-1;)n=r.indexOf(e,n),n!==-1&&(i.push({start:n,end:n+e.length,errors:0}),n+=1);return i.length>0?i:po(r,e,t)}function Un(r,e){return e.length===0||r.length===0?0:1-An(r,e,e.length)[0].errors/e.length}function go(r,e,t={}){if(e.length===0)return null;const n=Math.min(256,e.length/2),i=An(r,e,n);if(i.length===0)return null;const o=s=>{const m=1-s.errors/e.length,f=t.prefix?Un(r.slice(Math.max(0,s.start-t.prefix.length),s.start),t.prefix):1,d=t.suffix?Un(r.slice(s.end,s.end+t.suffix.length),t.suffix):1;let p=1;return typeof t.hint=="number"&&(p=1-Math.abs(s.start-t.hint)/r.length),(50*m+20*f+20*d+2*p)/92},a=i.map(s=>({start:s.start,end:s.end,score:o(s)}));return a.sort((s,l)=>l.score-s.score),a[0]}function kt(r,e,t){const n=t===1?e:e-1;if(r.charAt(n).trim()!=="")return e;let i,o;if(t===2?(i=r.substring(0,e),o=i.trimEnd()):(i=r.substring(e),o=i.trimStart()),!o.length)return-1;const a=i.length-o.length;return t===2?e-a:e+a}function Tn(r,e){const t=r.commonAncestorContainer.ownerDocument.createNodeIterator(r.commonAncestorContainer,NodeFilter.SHOW_TEXT),n=e===1?r.startContainer:r.endContainer,i=e===1?r.endContainer:r.startContainer;let o=t.nextNode();for(;o&&o!==n;)o=t.nextNode();e===2&&(o=t.previousNode());let a=-1;const s=()=>{if(o=e===1?t.nextNode():t.previousNode(),o){const l=o.textContent,c=e===1?0:l.length;a=kt(l,c,e)}};for(;o&&a===-1&&o!==i;)s();if(o&&a>=0)return{node:o,offset:a};throw new RangeError("No text nodes with non-whitespace text found in range")}function fo(r){if(!r.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(r.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(r.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=r.cloneRange();let t=!1,n=!1;const i={start:kt(r.startContainer.textContent,r.startOffset,1),end:kt(r.endContainer.textContent,r.endOffset,2)};if(i.start>=0&&(e.setStart(r.startContainer,i.start),t=!0),i.end>0&&(e.setEnd(r.endContainer,i.end),n=!0),t&&n)return e;if(!t){const{node:o,offset:a}=Tn(e,1);o&&a>=0&&e.setStart(o,a)}if(!n){const{node:o,offset:a}=Tn(e,2);o&&a>0&&e.setEnd(o,a)}return e}function Mn(r){switch(r.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return r.textContent?.length??0;default:return 0}}function Fn(r){let e=r.previousSibling,t=0;for(;e;)t+=Mn(e),e=e.previousSibling;return t}function Nn(r,...e){let t=e.shift();const n=r.ownerDocument.createNodeIterator(r,NodeFilter.SHOW_TEXT),i=[];let o=n.nextNode(),a,s=0;for(;t!==void 0&&o;)a=o,s+a.data.length>t?(i.push({node:a,offset:t-s}),t=e.shift()):(o=n.nextNode(),s+=a.data.length);for(;t!==void 0&&a&&s===t;)i.push({node:a,offset:a.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return i}class K{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,n=this.offset;for(;t!==e;)n+=Fn(t),t=t.parentElement;return new K(t,n)}resolve(e={}){try{return Nn(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const i=e.direction===1,o=i?n.nextNode():n.previousNode();if(!o)throw t;return{node:o,offset:i?0:o.data.length}}else throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return K.fromPoint(e,t);case Node.ELEMENT_NODE:return new K(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 n=Fn(e)+t;return new K(e.parentElement,n)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let n=0;for(let i=0;i<t;i++)n+=Mn(e.childNodes[i]);return new K(e,n)}default:throw new Error("Point is not in an element or text node")}}}class re{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new re(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]=Nn(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const n=new Range;return n.setStart(e.node,e.offset),n.setEnd(t.node,t.offset),n}static fromRange(e){const t=K.fromPoint(e.startContainer,e.startOffset),n=K.fromPoint(e.endContainer,e.endOffset);return new re(t,n)}static fromOffsets(e,t,n){return new re(new K(e,t),new K(e,n))}static trimmedRange(e){return fo(re.fromRange(e).toRange())}}class nt{constructor(e,t,n){this.root=e,this.start=t,this.end=n}static fromRange(e,t){const n=re.fromRange(t).relativeTo(e);return new nt(e,n.start.offset,n.end.offset)}static fromSelector(e,t){return new nt(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return re.fromOffsets(this.root,this.start,this.end).toRange()}}class it{constructor(e,t,n={}){this.root=e,this.exact=t,this.context=n}static fromRange(e,t){const n=e.textContent,i=re.fromRange(t).relativeTo(e),o=i.start.offset,a=i.end.offset,s=32;return new it(e,n.slice(o,a),{prefix:n.slice(Math.max(0,o-s),o),suffix:n.slice(a,Math.min(n.length,a+s))})}static fromSelector(e,t){const{prefix:n,suffix:i}=t;return new it(e,t.exact,{prefix:n,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 t=this.root.textContent,n=go(t,this.exact,{...this.context,hint:e.hint});if(!n)throw new Error("Quote not found");return new nt(this.root,n.start,n.end)}}function yo(r){const e=r.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Oe(r,e){try{const t=e.locations,n=e.text;if(n&&n.highlight){let i;t&&t.getCssSelector()&&(i=r.querySelector(t.getCssSelector())),i||(i=r.body);const o=new it(i,n.highlight,{prefix:n.before,suffix:n.after});try{return o.toRange()}catch{return console.warn("Quote not found:",o),null}}if(t){let i=null;if(!i&&t.getCssSelector()&&(i=r.querySelector(t.getCssSelector())),!i&&t.fragments){for(const o of t.fragments)if(i=r.getElementById(o),i)break}if(i){const o=r.createRange();return i.childNodes.length===0||yo(i)?(o.selectNode(i),o):(o.setStartBefore(i),o.setEndAfter(i),o)}}}catch(t){console.error(t)}return null}function So(r,e){let t=r.getClientRects();t.length||r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(t=r.commonAncestorContainer.getClientRects());const n=1,i=[];for(const c of t)i.push({bottom:c.bottom,height:c.height,left:c.left,right:c.right,top:c.top,width:c.width});const o=In(i,n),a=_o(o,n),s=Dn(a),l=4;for(let c=s.length-1;c>=0;c--){const h=s[c];if(!(h.width*h.height>l))if(s.length>1)s.splice(c,1);else break}return s}function In(r,e,t){for(let n=0;n<r.length;n++)for(let i=n+1;i<r.length;i++){const o=r[n],a=r[i];if(o===a)continue;const s=$(o.top,a.top,e)&&$(o.bottom,a.bottom,e),l=$(o.left,a.left,e)&&$(o.right,a.right,e);if(s&&!l&&Wn(o,a,e)){const u=r.filter(f=>f!==o&&f!==a),m=bo(o,a);return u.push(m),In(u,e)}}return r}function bo(r,e){const t=Math.min(r.left,e.left),n=Math.max(r.right,e.right),i=Math.min(r.top,e.top),o=Math.max(r.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:n,top:i,width:n-t}}function _o(r,e){const t=new Set(r);for(const n of r){if(!(n.width>1&&n.height>1)){t.delete(n);continue}for(const o of r)if(n!==o&&t.has(o)&&vo(o,n,e)){t.delete(n);break}}return Array.from(t)}function vo(r,e,t){return ot(r,e.left,e.top,t)&&ot(r,e.right,e.top,t)&&ot(r,e.left,e.bottom,t)&&ot(r,e.right,e.bottom,t)}function ot(r,e,t,n){return(r.left<e||$(r.left,e,n))&&(r.right>e||$(r.right,e,n))&&(r.top<t||$(r.top,t,n))&&(r.bottom>t||$(r.bottom,t,n))}function Dn(r){for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){const n=r[e],i=r[t];if(n!==i&&Wn(n,i,-1)){let o=[],a;const s=Hn(n,i);if(s.length===1)o=s,a=n;else{const c=Hn(i,n);s.length<c.length?(o=s,a=n):(o=c,a=i)}const l=r.filter(c=>c!==a);return Array.prototype.push.apply(l,o),Dn(l)}}return r}function Hn(r,e){const t=wo(e,r);if(t.height===0||t.width===0)return[r];const n=[];{const i={bottom:r.bottom,height:0,left:r.left,right:t.left,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:t.top,height:0,left:t.left,right:t.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:r.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:r.bottom,height:0,left:t.right,right:r.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}return n}function wo(r,e){const t=Math.max(r.left,e.left),n=Math.min(r.right,e.right),i=Math.max(r.top,e.top),o=Math.min(r.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:n,top:i,width:Math.max(0,n-t)}}function Wn(r,e,t){return(r.left<e.right||t>=0&&$(r.left,e.right,t))&&(e.left<r.right||t>=0&&$(e.left,r.right,t))&&(r.top<e.bottom||t>=0&&$(r.top,e.bottom,t))&&(e.top<r.bottom||t>=0&&$(e.top,r.bottom,t))}function $(r,e,t){return Math.abs(r-e)<=t}function Et(r){const e={},t=r.document.documentElement.style;for(const n in r.document.documentElement.style)Object.hasOwn(t,n)&&!Number.isNaN(Number.parseInt(n))&&(e[t[n]]=t.getPropertyValue(t[n]));return e}function Bn(r,e){const t=Et(r);Object.keys(t).forEach(n=>{e.hasOwnProperty(n)||rt(r,n)}),Object.entries(e).forEach(([n,i])=>{t[n]!==i&&Ae(r,n,i)})}function Ct(r,e){return r.document.documentElement.style.getPropertyValue(e)}function Ae(r,e,t){r.document.documentElement.style.setProperty(e,t)}function rt(r,e){r.document.documentElement.style.removeProperty(e)}let at=null,xt=null,Ue=0;const ye={r:255,g:255,b:255,a:1},Se=new Map,Po=()=>{if(!at)if(typeof OffscreenCanvas<"u")at=new OffscreenCanvas(5,5),xt=at.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const r=document.createElement("canvas");r.width=5,r.height=5,at=r,xt=r.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return xt},Ro=r=>{if(!r)return!0;const e=r.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(i=>e.includes(i))},st=(r,e)=>{console.warn(`[Decorator] Could not parse color: "${r}". ${e} Falling back to ${JSON.stringify(ye)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},Lt=(r,e=null)=>{const t=e?`${r}|${e}`:r,n=Se.get(t);if(n!==void 0)return n??ye;if(Ro(r))return st(r,"Unsupported color format or special value."),Se.set(t,null),ye;const i=Po();if(!i)return st(r,"Could not get canvas context."),Se.set(t,null),ye;try{Ue===0&&i.clearRect(0,0,5,5);const o=Ue%5,a=Math.floor(Ue/5);i.clearRect(o,a,1,1),e&&(i.fillStyle=e,i.fillRect(o,a,1,1)),i.fillStyle=r,i.fillRect(o,a,1,1);const s=i.getImageData(o,a,1,1);Ue=(Ue+1)%25;const[l,c,h,u]=s.data;if(u===0)return st(r,"Fully transparent color."),Se.set(t,null),ye;const m={r:l,g:c,b:h,a:u/255};return Se.set(t,m),m}catch(o){return st(r,`Error: ${o instanceof Error?o.message:String(o)}`),Se.set(t,null),ye}},zt=r=>{const e=r/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},jn=r=>{const e=zt(r.r),t=zt(r.g),n=zt(r.b);return .2126*e+.7152*t+.0722*n},Gn=(r,e)=>{const t=typeof r=="string"?Lt(r):r,n=typeof e=="string"?Lt(e):e,i=jn(t),o=jn(n),a=Math.max(i,o),s=Math.min(i,o);return(a+.05)/(s+.05)},Ot=(r,e=null)=>{const t=Lt(r,e),n=Gn(t,{r:255,g:255,b:255,a:1}),i=Gn(t,{r:0,g:0,b:0,a:1});return n>i},ko=(r,e=null)=>Ot(r,e)?"white":"black",Vn="#FFFF00",Eo=()=>"Highlight"in window,$n=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Co{constructor(e,t,n,i){this.wnd=e,this.comms=t,this.id=n,this.name=i,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,Eo()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(e){this.activateable=e}add(e){const t=`${this.id}-${this.lastItemId++}`,n=Oe(this.wnd.document,e.locator);if(!n){this.comms.log("Can't locate DOM range for decoration",e);return}const i=n.commonAncestorContainer;i.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&($n.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),n.cloneContents().querySelector($n.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(i.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0));const o={decoration:e,id:t,range:n};this.items.push(o),this.layout(o),this.renderLayout([o])}remove(e){const t=this.items.findIndex(i=>i.decoration.id===e);if(t<0)return;const n=this.items[t];this.items.splice(t,1),n.clickableElements=void 0,n.container&&(n.container.remove(),n.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(n.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(n.range),this.notTextFlag?.delete(n.id)}update(e){this.remove(e.id),this.add(e)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(e=>this.layout(e)),this.renderLayout(this.items)}experimentalLayout(e){const[t,n]=this.requireContainer(!0);n.add(e.range);const i=Ct(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"),o=e.decoration?.style?.tint??Vn;t.innerHTML=`
1
+ (function(_,me){typeof exports=="object"&&typeof module<"u"?me(exports):typeof define=="function"&&define.amd?define(["exports"],me):(_=typeof globalThis<"u"?globalThis:_||self,me(_.navigator={}))})(this,(function(_){"use strict";var ae;const w=class w{constructor(e){this.uri=e}static deserialize(e){if(!(!e||typeof e!="string"))return new w(e)}serialize(){return this.uri}get isWCAGLevelA(){return this===w.EPUB_A11Y_10_WCAG_20_A||this===w.EPUB_A11Y_11_WCAG_20_A||this===w.EPUB_A11Y_11_WCAG_21_A||this===w.EPUB_A11Y_11_WCAG_22_A}get isWCAGLevelAA(){return this===w.EPUB_A11Y_10_WCAG_20_AA||this===w.EPUB_A11Y_11_WCAG_20_AA||this===w.EPUB_A11Y_11_WCAG_21_AA||this===w.EPUB_A11Y_11_WCAG_22_AA}get isWCAGLevelAAA(){return this===w.EPUB_A11Y_10_WCAG_20_AAA||this===w.EPUB_A11Y_11_WCAG_20_AAA||this===w.EPUB_A11Y_11_WCAG_21_AAA||this===w.EPUB_A11Y_11_WCAG_22_AAA}};w.EPUB_A11Y_10_WCAG_20_A=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"),w.EPUB_A11Y_10_WCAG_20_AA=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"),w.EPUB_A11Y_10_WCAG_20_AAA=new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"),w.EPUB_A11Y_11_WCAG_20_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"),w.EPUB_A11Y_11_WCAG_20_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"),w.EPUB_A11Y_11_WCAG_20_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"),w.EPUB_A11Y_11_WCAG_21_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"),w.EPUB_A11Y_11_WCAG_21_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"),w.EPUB_A11Y_11_WCAG_21_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"),w.EPUB_A11Y_11_WCAG_22_A=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"),w.EPUB_A11Y_11_WCAG_22_AA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"),w.EPUB_A11Y_11_WCAG_22_AAA=new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");let me=w;const E=class E{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new E(e)}serialize(){return this.value}};E.AUDITORY=new E("auditory"),E.CHART_ON_VISUAL=new E("chartOnVisual"),E.CHEM_ON_VISUAL=new E("chemOnVisual"),E.COLOR_DEPENDENT=new E("colorDependent"),E.DIAGRAM_ON_VISUAL=new E("diagramOnVisual"),E.MATH_ON_VISUAL=new E("mathOnVisual"),E.MUSIC_ON_VISUAL=new E("musicOnVisual"),E.TACTILE=new E("tactile"),E.TEXT_ON_VISUAL=new E("textOnVisual"),E.TEXTUAL=new E("textual"),E.VISUAL=new E("visual");let fn=E;const H=class H{constructor(e){if(typeof e=="string"){if(!H.VALID_MODES.has(e.toLowerCase()))return;this.value=e.toLowerCase()}else{const t=e.filter(n=>H.VALID_MODES.has(n.toLowerCase()));if(t.length===0)return;this.value=Array.from(new Set(t))}}static deserialize(e){if(!e)return;if(typeof e=="string")return new H(e);if(!Array.isArray(e))return;const t=e.filter(n=>n?H.VALID_MODES.has(n.toLowerCase()):!1);if(t.length!==0)return new H(t)}serialize(){return this.value}};H.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),H.AUDITORY=new H("auditory"),H.TACTILE=new H("tactile"),H.TEXTUAL=new H("textual"),H.VISUAL=new H("visual");let yn=H;const y=class y{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new y(e)}serialize(){return this.value}};y.NONE=new y("none"),y.ANNOTATIONS=new y("annotations"),y.ARIA=new y("ARIA"),y.INDEX=new y("index"),y.PAGE_BREAK_MARKERS=new y("pageBreakMarkers"),y.PAGE_NAVIGATION=new y("pageNavigation"),y.PRINT_PAGE_NUMBERS=new y("printPageNumbers"),y.READING_ORDER=new y("readingOrder"),y.STRUCTURAL_NAVIGATION=new y("structuralNavigation"),y.TABLE_OF_CONTENTS=new y("tableOfContents"),y.TAGGED_PDF=new y("taggedPDF"),y.ALTERNATIVE_TEXT=new y("alternativeText"),y.AUDIO_DESCRIPTION=new y("audioDescription"),y.CAPTIONS=new y("captions"),y.CLOSED_CAPTIONS=new y("closedCaptions"),y.DESCRIBED_MATH=new y("describedMath"),y.LONG_DESCRIPTION=new y("longDescription"),y.OPEN_CAPTIONS=new y("openCaptions"),y.SIGN_LANGUAGE=new y("signLanguage"),y.TRANSCRIPT=new y("transcript"),y.DISPLAY_TRANSFORMABILITY=new y("displayTransformability"),y.SYNCHRONIZED_AUDIO_TEXT=new y("synchronizedAudioText"),y.TIMING_CONTROL=new y("timingControl"),y.UNLOCKED=new y("unlocked"),y.CHEM_ML=new y("ChemML"),y.LATEX=new y("latex"),y.LATEX_CHEMISTRY=new y("latex-chemistry"),y.MATH_ML=new y("MathML"),y.MATH_ML_CHEMISTRY=new y("MathML-chemistry"),y.TTS_MARKUP=new y("ttsMarkup"),y.HIGH_CONTRAST_AUDIO=new y("highContrastAudio"),y.HIGH_CONTRAST_DISPLAY=new y("highContrastDisplay"),y.LARGE_PRINT=new y("largePrint"),y.BRAILLE=new y("braille"),y.TACTILE_GRAPHIC=new y("tactileGraphic"),y.TACTILE_OBJECT=new y("tactileObject"),y.FULL_RUBY_ANNOTATIONS=new y("fullRubyAnnotations"),y.HORIZONTAL_WRITING=new y("horizontalWriting"),y.RUBY_ANNOTATIONS=new y("rubyAnnotations"),y.VERTICAL_WRITING=new y("verticalWriting"),y.WITH_ADDITIONAL_WORD_SEGMENTATION=new y("withAdditionalWordSegmentation"),y.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new y("withoutAdditionalWordSegmentation");let Ze=y;const x=class x{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new x(e)}serialize(){return this.value}};x.FLASHING=new x("flashing"),x.NO_FLASHING_HAZARD=new x("noFlashingHazard"),x.UNKNOWN_FLASHING_HAZARD=new x("unknownFlashingHazard"),x.MOTION_SIMULATION=new x("motionSimulation"),x.NO_MOTION_SIMULATION_HAZARD=new x("noMotionSimulationHazard"),x.UNKNOWN_MOTION_SIMULATION_HAZARD=new x("unknownMotionSimulationHazard"),x.SOUND=new x("sound"),x.NO_SOUND_HAZARD=new x("noSoundHazard"),x.UNKNOWN_SOUND_HAZARD=new x("unknownSoundHazard"),x.UNKNOWN=new x("unknown"),x.NONE=new x("none");let _n=x;const F=class F{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new F(e)}serialize(){return this.value}};F.NONE=new F("none"),F.DOCUMENTED=new F("documented"),F.LEGAL=new F("legal"),F.TEMPORARY=new F("temporary"),F.TECHNICAL=new F("technical"),F.EAA_DISPROPORTIONATE_BURDEN=new F("eaa-disproportionate-burden"),F.EAA_FUNDAMENTAL_ALTERATION=new F("eaa-fundamental-alteration"),F.EAA_MICROENTERPRISE=new F("eaa-microenterprise"),F.EAA_TECHNICAL_IMPOSSIBILITY=new F("eaa-technical-impossibility"),F.EAA_TEMPORARY=new F("eaa-temporary");let Sn=F;const bn=["en","ar","da","fr","it","pt_PT","sv"],io={publication:JSON.parse(`{"format":{"audiobook":"Audiobook","audiobookJSON":"Audiobook Manifest","cbz":"Comic Book Archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"LCP Protected Audiobook","lcpdf":"LCP Protected PDF","lcpl":"LCP License Document","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_one":"audiobook","audiobook_other":"audiobooks","book_one":"book","book_other":"books","comic_one":"comic","comic_other":"comics","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"No information is available","publisher-contact":"For more information about the accessibility of this product, please contact the publisher: ","title":"Accessibility summary"},"additional-accessibility-information":{"aria":{"compact":"ARIA roles included","descriptive":"Content is enhanced with ARIA roles to optimize organization and facilitate navigation"},"audio-descriptions":"Audio descriptions","braille":"Braille","color-not-sole-means-of-conveying-information":"Color is not the sole means of conveying information","dyslexia-readability":"Dyslexia readability","full-ruby-annotations":"Full ruby annotations","high-contrast-between-foreground-and-background-audio":"High contrast between foreground and background audio","high-contrast-between-text-and-background":"High contrast between foreground text and background","large-print":"Large print","page-breaks":{"compact":"Page breaks included","descriptive":"Page breaks included from the original print source"},"ruby-annotations":"Some Ruby annotations","sign-language":"Sign language","tactile-graphics":{"compact":"Tactile graphics included","descriptive":"Tactile graphics have been integrated to facilitate access to visual elements for blind people"},"tactile-objects":"Tactile 3D objects","text-to-speech-hinting":"Text-to-speech hinting provided","title":"Additional accessibility information","ultra-high-contrast-between-text-and-background":"Ultra high contrast between text and background","visible-page-numbering":"Visible page numbering","without-background-sounds":"Without background sounds"},"conformance":{"a":{"compact":"This publication meets minimum accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level A standard"},"aa":{"compact":"This publication meets accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AA standard"},"aaa":{"compact":"This publication exceeds accepted accessibility standards","descriptive":"The publication contains a conformance statement that it meets the EPUB Accessibility and WCAG 2 Level AAA standard"},"certifier":"The publication was certified by ","certifier-credentials":"The certifier's credential is ","details":{"certification-info":"The publication was certified on ","certifier-report":"For more information refer to the certifier's report","claim":"This publication claims to meet","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Level A","level-aa":"Level AA","level-aaa":"Level AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detailed conformance information","no":"No information is available","title":"Conformance","unknown-standard":"Conformance to accepted standards for accessibility of this publication cannot be determined"},"hazards":{"flashing":{"compact":"Flashing content","descriptive":"The publication contains flashing content that can cause photosensitive seizures"},"flashing-none":{"compact":"No flashing hazards","descriptive":"The publication does not contain flashing content that can cause photosensitive seizures"},"flashing-unknown":{"compact":"Flashing hazards not known","descriptive":"The presence of flashing content that can cause photosensitive seizures could not be determined"},"motion":{"compact":"Motion simulation","descriptive":"The publication contains motion simulations that can cause motion sickness"},"motion-none":{"compact":"No motion simulation hazards","descriptive":"The publication does not contain motion simulations that can cause motion sickness"},"motion-unknown":{"compact":"Motion simulation hazards not known","descriptive":"The presence of motion simulations that can cause motion sickness could not be determined"},"no-metadata":"No information is available","none":{"compact":"No hazards","descriptive":"The publication contains no hazards"},"sound":{"compact":"Sounds","descriptive":"The publication contains sounds that can cause sensitivity issues"},"sound-none":{"compact":"No sound hazards","descriptive":"The publication does not contain sounds that can cause sensitivity issues"},"sound-unknown":{"compact":"Sound hazards not known","descriptive":"The presence of sounds that can cause sensitivity issues could not be determined"},"title":"Hazards","unknown":"The presence of hazards is unknown"},"legal-considerations":{"exempt":{"compact":"Claims an accessibility exemption in some jurisdictions","descriptive":"This publication claims an accessibility exemption in some jurisdictions"},"no-metadata":"No information is available","title":"Legal considerations"},"navigation":{"index":{"compact":"Index","descriptive":"Index with links to referenced entries"},"no-metadata":"No information is available","page-navigation":{"compact":"Go to page","descriptive":"Page list to go to pages from the print source version"},"structural":{"compact":"Headings","descriptive":"Elements such as headings, tables, etc for structured navigation"},"title":"Navigation","toc":{"compact":"Table of contents","descriptive":"Table of contents to all chapters of the text via links"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Chemical formulas in LaTeX","descriptive":"Chemical formulas in accessible format (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Chemical formulas in MathML","descriptive":"Chemical formulas in accessible format (MathML)"},"accessible-math-as-latex":{"compact":"Math as LaTeX","descriptive":"Math formulas in accessible format (LaTeX)"},"accessible-math-described":"Text descriptions of math are provided","closed-captions":{"compact":"Videos have closed captions","descriptive":"Videos included in publications have closed captions"},"extended-descriptions":"Information-rich images are described by extended descriptions","math-as-mathml":{"compact":"Math as MathML","descriptive":"Math formulas in accessible format (MathML)"},"open-captions":{"compact":"Videos have open captions","descriptive":"Videos included in publications have open captions"},"title":"Rich content","transcript":"Transcript(s) provided","unknown":"No information is available"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Has alternative text","descriptive":"Has alternative text descriptions for images"},"no-metadata":"No information about nonvisual reading is available","none":{"compact":"Not readable in read aloud or dynamic braille","descriptive":"The content is not readable as read aloud speech or dynamic braille"},"not-fully":{"compact":"Not fully readable in read aloud or dynamic braille","descriptive":"Not all of the content will be readable as read aloud speech or dynamic braille"},"readable":{"compact":"Readable in read aloud or dynamic braille","descriptive":"All content can be read as read aloud speech or dynamic braille"}},"prerecorded-audio":{"complementary":{"compact":"Prerecorded audio clips","descriptive":"Prerecorded audio clips are embedded in the content"},"no-metadata":"No information about prerecorded audio is available","only":{"compact":"Prerecorded audio only","descriptive":"Audiobook with no text alternative"},"synchronized":{"compact":"Prerecorded audio synchronized with text","descriptive":"All the content is available as prerecorded audio synchronized with text"}},"title":"Ways of reading","visual-adjustments":{"modifiable":{"compact":"Appearance can be modified","descriptive":"Appearance of the text and page layout can be modified according to the capabilities of the reading system (font family and font size, spaces between paragraphs, sentences, words, and letters, as well as color of background and text)"},"unknown":"No information about appearance modifiability is available","unmodifiable":{"compact":"Appearance cannot be modified","descriptive":"Text and page layout cannot be modified as the reading experience is close to a print version, but reading systems can still provide zooming options"}}}}},"altIdentifier_one":"alternate identifier","altIdentifier_other":"alternate identifiers","artist_one":"artist","artist_other":"artists","author_one":"author","author_other":"authors","collection_one":"editorial collection","collection_other":"editorial collections","colorist_one":"colorist","colorist_other":"colorists","contributor_one":"contributor","contributor_other":"contributors","description":"description","duration":"duration","editor_one":"editor","editor_other":"editors","identifier_one":"identifier","identifier_other":"identifiers","illustrator_one":"illustrator","illustrator_other":"illustrators","imprint_one":"imprint","imprint_other":"imprints","inker_one":"inker","inker_other":"inkers","language_one":"language","language_other":"languages","letterer_one":"letterer","letterer_other":"letterers","modified":"modification date","narrator_one":"narrator","narrator_other":"narrators","numberOfPages":"print length","penciler_one":"penciler","penciler_other":"pencilers","published":"publication date","publisher_one":"publisher","publisher_other":"publishers","series_one":"series","series_other":"series","subject_one":"subject","subject_other":"subjects","subtitle":"subtitle","title":"title","translator_one":"translator","translator_other":"translators"}}`)},vn={fr:()=>Promise.resolve().then(()=>Wr),ar:()=>Promise.resolve().then(()=>Br),da:()=>Promise.resolve().then(()=>jr),it:()=>Promise.resolve().then(()=>Gr),pt_PT:()=>Promise.resolve().then(()=>Vr),sv:()=>Promise.resolve().then(()=>$r)},wn=io?.publication?.metadata?.accessibility?.["display-guide"]||{};class pe{constructor(){this.currentLocaleCode="en",this.locale=wn,this.loadedLocales={},this.loadedLocales.en=wn}static getInstance(){return pe.instance||(pe.instance=new pe),pe.instance}async loadLocale(e){if(!bn.includes(e))return console.warn(`Locale '${e}' is not enabled`),!1;if(e in this.loadedLocales)return!0;try{if(!(e in vn))return console.warn(`Locale file not found for: ${e}`),!1;const i=(await vn[e]()).default?.publication?.metadata?.accessibility?.["display-guide"];return i?(this.loadedLocales[e]=i,!0):(console.warn(`No accessibility strings found in locale ${e}`),!1)}catch(t){return console.warn(`Failed to load locale ${e}:`,t),!1}}registerLocale(e,t){if(!e||typeof e!="string")throw new Error("Locale code must be a non-empty string");this.loadedLocales[e]=t}async setLocale(e){return e in this.loadedLocales||await this.loadLocale(e),e in this.loadedLocales?(this.locale=this.loadedLocales[e],this.currentLocaleCode=e,!0):(console.warn(`Locale '${e}' is not available`),!1)}getCurrentLocale(){return this.currentLocaleCode}getAvailableLocales(){return bn}getNestedValue(e,t){const n=t.split(".");let i=e;for(const o of n){if(i==null)return;i=i[o]}return i}getString(e){let t=this.getNestedValue(this.locale,e);return t===void 0&&this.currentLocaleCode!=="en"&&(t=this.getNestedValue(this.loadedLocales.en,e)),t!==void 0?typeof t=="string"?{compact:t,descriptive:t}:t:(console.warn(`Missing localization for key: ${e}`),{compact:"",descriptive:""})}}pe.getInstance();var S=(r=>(r.reflowable="reflowable",r.fixed="fixed",r.scrolled="scrolled",r))(S||{});class yt{constructor(e){this.algorithm=e.algorithm,this.compression=e.compression,this.originalLength=e.originalLength,this.profile=e.profile,this.scheme=e.scheme}static deserialize(e){if(e&&e.algorithm)return new yt({algorithm:e.algorithm,compression:e.compression,originalLength:e.originalLength,profile:e.profile,scheme:e.scheme})}serialize(){const e={algorithm:this.algorithm};return this.compression!==void 0&&(e.compression=this.compression),this.originalLength!==void 0&&(e.originalLength=this.originalLength),this.profile!==void 0&&(e.profile=this.profile),this.scheme!==void 0&&(e.scheme=this.scheme),e}}var K=(r=>(r.left="left",r.right="right",r.center="center",r))(K||{});let X=class gn{constructor(e){this.otherProperties=e}get page(){return this.otherProperties.page}static deserialize(e){if(e)return new gn(e)}serialize(){return this.otherProperties}add(e){const t=Object.assign({},this.otherProperties);for(const n in e)t[n]=e[n];return new gn(t)}};Object.defineProperty(X.prototype,"encryption",{get:function(){return yt.deserialize(this.otherProperties.encrypted)}});function oo(r){return r&&Array.isArray(r)?r:void 0}function Rn(r){return r&&typeof r=="string"?[r]:oo(r)}function Pn(r){return typeof r=="string"?new Date(r):void 0}function Qe(r){return isNaN(r)?void 0:r}function G(r){return Qe(r)!==void 0&&Math.sign(r)>=0?r:void 0}function ro(r){const e=new Array;return r.forEach(t=>e.push(t)),e}class g{constructor(e){let t,n,i=e.mediaType.replace(/\s/g,"").split(";");const o=i[0].split("/");if(o.length===2){if(t=o[0].toLowerCase().trim(),n=o[1].toLowerCase().trim(),t.length===0||n.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const a={};for(let m=1;m<i.length;m++){const f=i[m].split("=");if(f.length===2){const d=f[0].toLocaleLowerCase(),p=d==="charset"?f[1].toUpperCase():f[1];a[d]=p}}const s={},l=Object.keys(a);l.sort((m,f)=>m.localeCompare(f)),l.forEach(m=>s[m]=a[m]);let c="";for(const m in s){const f=s[m];c+=`;${m}=${f}`}const h=`${t}/${n}${c}`,u=s.encoding;this.string=h,this.type=t,this.subtype=n,this.parameters=s,this.encoding=u,this.name=e.name,this.fileExtension=e.fileExtension}static parse(e){return new g(e)}get structuredSyntaxSuffix(){const e=this.subtype.split("+");return e.length>1?`+${e[e.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(e){const t=typeof e=="string"?g.parse({mediaType:e}):e;if(!((this.type==="*"||this.type===t.type)&&(this.subtype==="*"||this.subtype===t.subtype)))return!1;const n=new Set(Object.entries(this.parameters).map(([o,a])=>`${o}=${a}`)),i=new Set(Object.entries(t.parameters).map(([o,a])=>`${o}=${a}`));for(const o of Array.from(n.values()))if(!i.has(o))return!1;return!0}matches(e){const t=typeof e=="string"?g.parse({mediaType:e}):e;return this.contains(t)||t.contains(this)}matchesAny(...e){for(const t of e)if(this.matches(t))return!0;return!1}equals(e){return this.string===e.string}get isZIP(){return this.matchesAny(g.ZIP,g.LCP_PROTECTED_AUDIOBOOK,g.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(g.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(g.OPDS1,g.OPDS1_ENTRY,g.OPDS2,g.OPDS2_PUBLICATION,g.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(g.HTML,g.XHTML)}get isBitmap(){return this.matchesAny(g.AVIF,g.BMP,g.GIF,g.JPEG,g.PNG,g.TIFF,g.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(g.READIUM_AUDIOBOOK_MANIFEST,g.DIVINA_MANIFEST,g.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(g.READIUM_AUDIOBOOK,g.READIUM_AUDIOBOOK_MANIFEST,g.CBZ,g.DIVINA,g.DIVINA_MANIFEST,g.EPUB,g.LCP_PROTECTED_AUDIOBOOK,g.LCP_PROTECTED_PDF,g.LPF,g.PDF,g.W3C_WPUB_MANIFEST,g.READIUM_WEBPUB,g.READIUM_WEBPUB_MANIFEST,g.ZAB)}static get AAC(){return g.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return g.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return g.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return g.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get AVIF(){return g.parse({mediaType:"image/avif",fileExtension:"avif"})}static get BINARY(){return g.parse({mediaType:"application/octet-stream"})}static get BMP(){return g.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return g.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return g.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return g.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return g.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return g.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return g.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return g.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return g.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return g.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return g.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return g.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return g.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return g.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return g.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return g.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return g.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return g.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return g.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return g.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return g.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return g.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return g.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return g.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return g.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return g.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return g.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return g.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return g.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return g.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return g.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return g.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return g.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return g.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return g.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return g.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return g.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return g.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return g.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return g.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return g.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return g.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return g.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return g.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return g.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return g.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return g.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return g.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return g.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return g.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return g.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return g.parse({mediaType:"application/zip",fileExtension:"zip"})}}class Cn{constructor(e){this.uri=e,this.parameters=this.getParameters(e)}getParameters(e){const t=/\{\??([^}]+)\}/g,n=e.match(t);return n?new Set(n.join(",").replace(t,"$1").split(",").map(i=>i.trim())):new Set}expand(e){const t=i=>i.split(",").map(o=>{const a=e[o];return a?encodeURIComponent(a):""}).join(","),n=i=>"?"+i.split(",").map(o=>{const a=o.split("=")[0],s=e[a];return s?`${a}=${encodeURIComponent(s)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...i)=>i[1]?n(i[2]):t(i[2]))}}class C{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=Qe(e.progression),n=Qe(e.totalProgression),i=Qe(e.position),o=new Map,a=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(e).forEach(([s,l])=>{a.has(s)||o.set(s,l)}),new C({fragments:Rn(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:n!==void 0&&n>=0&&n<=1?n:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:o.size===0?void 0:o})}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,n)=>e[n]=t),e}}class oe{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new oe({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}}class N{constructor(e){this.href=e.href,this.type=e.type,this.title=e.title,this.locations=e.locations?e.locations:new C({}),this.text=e.text}static deserialize(e){if(e&&e.href&&e.type)return new N({href:e.href,type:e.type,title:e.title,locations:C.deserialize(e.locations),text:oe.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 N({href:this.href,type:this.type,title:this.title,text:this.text,locations:new C({...this.locations,...e})})}}class V{constructor(e){this.href=e.href,this.templated=e.templated,this.type=e.type,this.title=e.title,this.rels=e.rels,this.properties=e.properties,this.height=e.height,this.width=e.width,this.size=e.size,this.duration=e.duration,this.bitrate=e.bitrate,this.languages=e.languages,this.alternates=e.alternates,this.children=e.children}static deserialize(e){if(!(!e||typeof e.href!="string"))return new V({href:e.href,templated:e.templated,type:e.type,title:e.title,rels:e.rel?Array.isArray(e.rel)?new Set(e.rel):new Set([e.rel]):void 0,properties:X.deserialize(e.properties),height:G(e.height),width:G(e.width),size:G(e.size),duration:G(e.duration),bitrate:G(e.bitrate),languages:Rn(e.language),alternates:et.deserialize(e.alternate),children:et.deserialize(e.children)})}serialize(){const e={href:this.href};return this.templated!==void 0&&(e.templated=this.templated),this.type!==void 0&&(e.type=this.type),this.title!==void 0&&(e.title=this.title),this.rels&&(e.rel=ro(this.rels)),this.properties&&(e.properties=this.properties.serialize()),this.height!==void 0&&(e.height=this.height),this.width!==void 0&&(e.width=this.width),this.size!==void 0&&(e.size=this.size),this.duration!==void 0&&(e.duration=this.duration),this.bitrate!==void 0&&(e.bitrate=this.bitrate),this.languages&&(e.language=this.languages),this.alternates&&(e.alternate=this.alternates.serialize()),this.children&&(e.children=this.children.serialize()),e}get mediaType(){return this.type!==void 0?g.parse({mediaType:this.type}):g.BINARY}toURL(e){const t=this.href.replace(/^(\/)/,"");if(t.length===0)return;let n=e||"/";return n.startsWith("/")&&(n="file://"+n),new URL(t,n).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new Cn(this.href).parameters:new Set}expandTemplate(e){return new V({href:new Cn(this.href).expand(e),templated:!1})}addProperties(e){const t=V.deserialize(this.serialize());return t.properties=t.properties?t.properties?.add(e):new X(e),t}get locator(){let e=this.href.split("#");return new N({href:e.length>0&&e[0]!==void 0?e[0]:this.href,type:this.type??"",title:this.title,locations:new C({fragments:e.length>1&&e[1]!==void 0?[e[1]]:[]})})}}class et{constructor(e){this.items=e}static deserialize(e){if(e&&Array.isArray(e))return new et(e.map(t=>V.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(e=>e.serialize())}findWithRel(e){const t=n=>n.rels&&n.rels.has(e);return this.items.find(t)}filterByRel(e){const t=n=>n.rels&&n.rels.has(e);return this.items.filter(t)}findWithHref(e){const t=n=>n.href===e;return this.items.find(t)}findIndexWithHref(e){const t=n=>n.href===e;return this.items.findIndex(t)}findWithMediaType(e){const t=n=>n.mediaType.matches(e);return this.items.find(t)}filterByMediaType(e){const t=n=>n.mediaType.matches(e);return this.items.filter(t)}filterByMediaTypes(e){const t=n=>{for(const i of e)if(n.mediaType.matches(i))return!0;return!1};return this.items.filter(t)}everyIsAudio(){const e=t=>t.mediaType.isAudio;return this.items.length>0&&this.items.every(e)}everyIsBitmap(){const e=t=>t.mediaType.isBitmap;return this.items.length>0&&this.items.every(e)}everyIsHTML(){const e=t=>t.mediaType.isHTML;return this.items.length>0&&this.items.every(e)}everyIsVideo(){const e=t=>t.mediaType.isVideo;return this.items.length>0&&this.items.every(e)}everyMatchesMediaType(e){return Array.isArray(e)?this.items.length>0&&this.items.every(t=>{for(const n of e)return t.mediaType.matches(n);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(e))}filterLinksHasType(){return this.items.filter(e=>e.type)}}var kn=(r=>(r.EPUB="https://readium.org/webpub-manifest/profiles/epub",r.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",r.DIVINA="https://readium.org/webpub-manifest/profiles/divina",r.PDF="https://readium.org/webpub-manifest/profiles/pdf",r))(kn||{}),M=(r=>(r.ltr="ltr",r.rtl="rtl",r))(M||{});X.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class tt{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=G(e.textNodeIndex);if(t===void 0)return;let n=G(e.charOffset);return n===void 0&&(n=G(e.offset)),new tt({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:n})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}}class _t{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=tt.deserialize(e.start);if(t)return new _t({start:t,end:tt.deserialize(e.end)})}serialize(){const e={start:this.start.serialize()};return this.end&&(e.end=this.end.serialize()),e}}C.prototype.getCssSelector=function(){return this.otherLocations?.get("cssSelector")},C.prototype.getPartialCfi=function(){return this.otherLocations?.get("partialCfi")},C.prototype.getDomRange=function(){return _t.deserialize(this.otherLocations?.get("domRange"))},C.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},C.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(e=>e.length&&!e.includes("="));if(!r){const e=this.fragmentParameters();e.has("id")?r=e.get("id"):e.has("name")&&(r=e.get("name"))}return r?.startsWith("#")?r.slice(1):r},C.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},C.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},C.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const e=r.get("xywh").split(",").map(t=>parseInt(t));if(e.length===4&&!e.some(isNaN))return e};class St{constructor(e){this.currency=e.currency,this.value=e.value}static deserialize(e){if(!e)return;let t=e.currency;if(!(t&&typeof t=="string"&&t.length>0))return;let n=G(e.value);if(n!==void 0)return new St({currency:t,value:n})}serialize(){return{currency:this.currency,value:this.value}}}class ze{constructor(e){this.type=e.type,this.children=e.children}static deserialize(e){if(e&&e.type)return new ze({type:e.type,children:ze.deserializeArray(e.children)})}static deserializeArray(e){if(Array.isArray(e))return e.map(t=>ze.deserialize(t)).filter(t=>t!==void 0)}serialize(){const e={type:this.type};return this.children&&(e.children=this.children.map(t=>t.serialize())),e}}class bt{constructor(e){this.total=e.total,this.position=e.position}static deserialize(e){if(e)return new bt({total:G(e.total),position:G(e.position)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.position!==void 0&&(e.position=this.position),e}}class vt{constructor(e){this.total=e.total,this.available=e.available}static deserialize(e){if(e)return new vt({total:G(e.total),available:G(e.available)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.available!==void 0&&(e.available=this.available),e}}class wt{constructor(e){this.state=e.state,this.since=e.since,this.until=e.until}static deserialize(e){if(e&&e.state)return new wt({state:e.state,since:Pn(e.since),until:Pn(e.until)})}serialize(){const e={state:this.state};return this.since!==void 0&&(e.since=this.since.toISOString()),this.until!==void 0&&(e.until=this.until.toISOString()),e}}X.prototype.getNumberOfItems=function(){return G(this.otherProperties.numberOfItems)},X.prototype.getPrice=function(){return St.deserialize(this.otherProperties.price)},X.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&Array.isArray(r))return r.map(e=>ze.deserialize(e)).filter(e=>e!==void 0)},X.prototype.getHolds=function(){return bt.deserialize(this.otherProperties.holds)},X.prototype.getCopies=function(){return vt.deserialize(this.otherProperties.copies)},X.prototype.getAvailability=function(){return wt.deserialize(this.otherProperties.availability)},X.prototype.getAuthenticate=function(){return V.deserialize(this.otherProperties.authenticate)};const ao="CssSelectorGenerator";function En(r="unknown problem",...e){console.warn(`${ao}: ${r}`,...e)}function so(r){return r instanceof RegExp}function lo(r){return r.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function co(r){const e=r.map(t=>{if(so(t))return n=>t.test(n);if(typeof t=="function")return n=>{const i=t(n);return typeof i!="boolean"?(En("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):i};if(typeof t=="string"){const n=new RegExp("^"+lo(t)+"$");return i=>n.test(i)}return En("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(n=>n(t))}co(["class","id","ng-*"]);const ho=Math.pow(2,32),xn=()=>Math.round(Math.random()*ho).toString(36),Rt=()=>`${Math.round(performance.now())}-${xn()}-${xn()}`,ge=1;class uo{constructor(e){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=e,e.addEventListener("message",this.receiver)}receive(e){if(e.source===null)throw Error("Event source is null");if(typeof e.data!="object")return;const t=e.data;if(!(!("_readium"in t)||!t._readium||t._readium<=0)){if(t.key==="_ping"){if(!this.destination){if(this.destination=e.source,this.origin=e.origin,this.channelId=t._channel,t._readium!==ge){t._readium>ge?this.send("error",`received comms version ${t._readium} higher than ${ge}`):this.send("error",`received comms version ${t._readium} lower than ${ge}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(n=>this.send("log",n)),this.preLog=[]}return}else if(this.channelId){if(t._channel!==this.channelId||e.origin!==this.origin)return}else return;this.handle(t)}}handle(e){const t=this.registrar.get(e.key);if(!t||t.length===0){e.strict&&this.send("_unhandled",e);return}t.forEach(n=>n.cb(e.data,i=>{this.send("_ack",i,e.id)}))}register(e,t,n){Array.isArray(e)||(e=[e]),e.forEach(i=>{const o=this.registrar.get(i);if(o&&o.length>=0){if(o.find(s=>s.module===t))throw new Error(`Trying to register another callback for combination of event ${i} and module ${t}`);o.push({cb:n,module:t}),this.registrar.set(i,o)}else this.registrar.set(i,[{cb:n,module:t}])})}unregister(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{const i=this.registrar.get(n);!i||i.length===0||i.splice(i.findIndex(o=>o.module===t),1)})}unregisterAll(e){this.registrar.forEach((t,n)=>this.registrar.set(n,t.filter(i=>i.module!==e)))}log(...e){this.destination?this.send("log",e):this.preLog.push(e)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(e,t,n=void 0,i=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const o={_readium:ge,_channel:this.channelId,id:n??Rt(),key:e,data:t};try{this.destination.postMessage(o,{targetOrigin:this.origin,transfer:i})}catch(a){if(i.length>0)throw a;this.destination.postMessage(o,this.origin,i)}}}class fe{}function Fn(r){return r.split("").reverse().join("")}function mo(r,e,t){const n=Fn(e);return t.map(i=>{const o=Math.max(0,i.end-e.length-i.errors),a=Fn(r.slice(o,i.end));return{start:Ln(a,n,i.errors).reduce((l,c)=>i.end-c.end<l?i.end-c.end:l,i.end),end:i.end,errors:i.errors}})}function Pt(r){return(r|-r)>>31&1}function zn(r,e,t,n){let i=r.P[t],o=r.M[t];const a=n>>>31,s=e[t]|a,l=s|o,c=(s&i)+i^i|s;let h=o|~(c|i),u=i&c;const m=Pt(h&r.lastRowMask[t])-Pt(u&r.lastRowMask[t]);return h<<=1,u<<=1,u|=a,h|=Pt(n)-a,i=u|~(l|h),o=h&l,r.P[t]=i,r.M[t]=o,m}function Ln(r,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const n=[],i=32,o=Math.ceil(e.length/i)-1,a={P:new Uint32Array(o+1),M:new Uint32Array(o+1),lastRowMask:new Uint32Array(o+1)};a.lastRowMask.fill(1<<31),a.lastRowMask[o]=1<<(e.length-1)%i;const s=new Uint32Array(o+1),l=new Map,c=[];for(let m=0;m<256;m++)c.push(s);for(let m=0;m<e.length;m+=1){const f=e.charCodeAt(m);if(l.has(f))continue;const d=new Uint32Array(o+1);l.set(f,d),f<c.length&&(c[f]=d);for(let p=0;p<=o;p+=1){d[p]=0;for(let b=0;b<i;b+=1){const P=p*i+b;if(P>=e.length)continue;e.charCodeAt(P)===f&&(d[p]|=1<<b)}}}let h=Math.max(0,Math.ceil(t/i)-1);const u=new Uint32Array(o+1);for(let m=0;m<=h;m+=1)u[m]=(m+1)*i;u[o]=e.length;for(let m=0;m<=h;m+=1)a.P[m]=-1,a.M[m]=0;for(let m=0;m<r.length;m+=1){const f=r.charCodeAt(m);let d;f<c.length?d=c[f]:(d=l.get(f),typeof d>"u"&&(d=s));let p=0;for(let b=0;b<=h;b+=1)p=zn(a,d,b,p),u[b]+=p;if(u[h]-p<=t&&h<o&&(d[h+1]&1||p<0)){h+=1,a.P[h]=-1,a.M[h]=0;let b;if(h===o){const P=e.length%i;b=P===0?i:P}else b=i;u[h]=u[h-1]+b-p+zn(a,d,h,p)}else for(;h>0&&u[h]>=t+i;)h-=1;h===o&&u[h]<=t&&(u[h]<t&&n.splice(0,n.length),n.push({start:-1,end:m+1,errors:u[h]}),t=u[h])}return n}function po(r,e,t){const n=Ln(r,e,t);return mo(r,e,n)}function On(r,e,t){let n=0;const i=[];for(;n!==-1;)n=r.indexOf(e,n),n!==-1&&(i.push({start:n,end:n+e.length,errors:0}),n+=1);return i.length>0?i:po(r,e,t)}function An(r,e){return e.length===0||r.length===0?0:1-On(r,e,e.length)[0].errors/e.length}function go(r,e,t={}){if(e.length===0)return null;const n=Math.min(256,e.length/2),i=On(r,e,n);if(i.length===0)return null;const o=s=>{const m=1-s.errors/e.length,f=t.prefix?An(r.slice(Math.max(0,s.start-t.prefix.length),s.start),t.prefix):1,d=t.suffix?An(r.slice(s.end,s.end+t.suffix.length),t.suffix):1;let p=1;return typeof t.hint=="number"&&(p=1-Math.abs(s.start-t.hint)/r.length),(50*m+20*f+20*d+2*p)/92},a=i.map(s=>({start:s.start,end:s.end,score:o(s)}));return a.sort((s,l)=>l.score-s.score),a[0]}function Ct(r,e,t){const n=t===1?e:e-1;if(r.charAt(n).trim()!=="")return e;let i,o;if(t===2?(i=r.substring(0,e),o=i.trimEnd()):(i=r.substring(e),o=i.trimStart()),!o.length)return-1;const a=i.length-o.length;return t===2?e-a:e+a}function Un(r,e){const t=r.commonAncestorContainer.ownerDocument.createNodeIterator(r.commonAncestorContainer,NodeFilter.SHOW_TEXT),n=e===1?r.startContainer:r.endContainer,i=e===1?r.endContainer:r.startContainer;let o=t.nextNode();for(;o&&o!==n;)o=t.nextNode();e===2&&(o=t.previousNode());let a=-1;const s=()=>{if(o=e===1?t.nextNode():t.previousNode(),o){const l=o.textContent,c=e===1?0:l.length;a=Ct(l,c,e)}};for(;o&&a===-1&&o!==i;)s();if(o&&a>=0)return{node:o,offset:a};throw new RangeError("No text nodes with non-whitespace text found in range")}function fo(r){if(!r.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(r.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(r.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=r.cloneRange();let t=!1,n=!1;const i={start:Ct(r.startContainer.textContent,r.startOffset,1),end:Ct(r.endContainer.textContent,r.endOffset,2)};if(i.start>=0&&(e.setStart(r.startContainer,i.start),t=!0),i.end>0&&(e.setEnd(r.endContainer,i.end),n=!0),t&&n)return e;if(!t){const{node:o,offset:a}=Un(e,1);o&&a>=0&&e.setStart(o,a)}if(!n){const{node:o,offset:a}=Un(e,2);o&&a>0&&e.setEnd(o,a)}return e}function Tn(r){switch(r.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return r.textContent?.length??0;default:return 0}}function Nn(r){let e=r.previousSibling,t=0;for(;e;)t+=Tn(e),e=e.previousSibling;return t}function Mn(r,...e){let t=e.shift();const n=r.ownerDocument.createNodeIterator(r,NodeFilter.SHOW_TEXT),i=[];let o=n.nextNode(),a,s=0;for(;t!==void 0&&o;)a=o,s+a.data.length>t?(i.push({node:a,offset:t-s}),t=e.shift()):(o=n.nextNode(),s+=a.data.length);for(;t!==void 0&&a&&s===t;)i.push({node:a,offset:a.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return i}class q{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,n=this.offset;for(;t!==e;)n+=Nn(t),t=t.parentElement;return new q(t,n)}resolve(e={}){try{return Mn(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const n=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);n.currentNode=this.element;const i=e.direction===1,o=i?n.nextNode():n.previousNode();if(!o)throw t;return{node:o,offset:i?0:o.data.length}}else throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return q.fromPoint(e,t);case Node.ELEMENT_NODE:return new q(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 n=Nn(e)+t;return new q(e.parentElement,n)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let n=0;for(let i=0;i<t;i++)n+=Tn(e.childNodes[i]);return new q(e,n)}default:throw new Error("Point is not in an element or text node")}}}class re{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new re(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]=Mn(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const n=new Range;return n.setStart(e.node,e.offset),n.setEnd(t.node,t.offset),n}static fromRange(e){const t=q.fromPoint(e.startContainer,e.startOffset),n=q.fromPoint(e.endContainer,e.endOffset);return new re(t,n)}static fromOffsets(e,t,n){return new re(new q(e,t),new q(e,n))}static trimmedRange(e){return fo(re.fromRange(e).toRange())}}class nt{constructor(e,t,n){this.root=e,this.start=t,this.end=n}static fromRange(e,t){const n=re.fromRange(t).relativeTo(e);return new nt(e,n.start.offset,n.end.offset)}static fromSelector(e,t){return new nt(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return re.fromOffsets(this.root,this.start,this.end).toRange()}}class it{constructor(e,t,n={}){this.root=e,this.exact=t,this.context=n}static fromRange(e,t){const n=e.textContent,i=re.fromRange(t).relativeTo(e),o=i.start.offset,a=i.end.offset,s=32;return new it(e,n.slice(o,a),{prefix:n.slice(Math.max(0,o-s),o),suffix:n.slice(a,Math.min(n.length,a+s))})}static fromSelector(e,t){const{prefix:n,suffix:i}=t;return new it(e,t.exact,{prefix:n,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 t=this.root.textContent,n=go(t,this.exact,{...this.context,hint:e.hint});if(!n)throw new Error("Quote not found");return new nt(this.root,n.start,n.end)}}function yo(r){const e=r.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Le(r,e){try{const t=e.locations,n=e.text;if(n&&n.highlight){let i;t&&t.getCssSelector()&&(i=r.querySelector(t.getCssSelector())),i||(i=r.body);const o=new it(i,n.highlight,{prefix:n.before,suffix:n.after});try{return o.toRange()}catch{return console.warn("Quote not found:",o),null}}if(t){let i=null;if(!i&&t.getCssSelector()&&(i=r.querySelector(t.getCssSelector())),!i&&t.fragments){for(const o of t.fragments)if(i=r.getElementById(o),i)break}if(i){const o=r.createRange();return i.childNodes.length===0||yo(i)?(o.selectNode(i),o):(o.setStartBefore(i),o.setEndAfter(i),o)}}}catch(t){console.error(t)}return null}function _o(r,e){let t=r.getClientRects();t.length||r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(t=r.commonAncestorContainer.getClientRects());const n=1,i=[];for(const c of t)i.push({bottom:c.bottom,height:c.height,left:c.left,right:c.right,top:c.top,width:c.width});const o=In(i,n),a=bo(o,n),s=Hn(a),l=4;for(let c=s.length-1;c>=0;c--){const h=s[c];if(!(h.width*h.height>l))if(s.length>1)s.splice(c,1);else break}return s}function In(r,e,t){for(let n=0;n<r.length;n++)for(let i=n+1;i<r.length;i++){const o=r[n],a=r[i];if(o===a)continue;const s=$(o.top,a.top,e)&&$(o.bottom,a.bottom,e),l=$(o.left,a.left,e)&&$(o.right,a.right,e);if(s&&!l&&Wn(o,a,e)){const u=r.filter(f=>f!==o&&f!==a),m=So(o,a);return u.push(m),In(u,e)}}return r}function So(r,e){const t=Math.min(r.left,e.left),n=Math.max(r.right,e.right),i=Math.min(r.top,e.top),o=Math.max(r.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:n,top:i,width:n-t}}function bo(r,e){const t=new Set(r);for(const n of r){if(!(n.width>1&&n.height>1)){t.delete(n);continue}for(const o of r)if(n!==o&&t.has(o)&&vo(o,n,e)){t.delete(n);break}}return Array.from(t)}function vo(r,e,t){return ot(r,e.left,e.top,t)&&ot(r,e.right,e.top,t)&&ot(r,e.left,e.bottom,t)&&ot(r,e.right,e.bottom,t)}function ot(r,e,t,n){return(r.left<e||$(r.left,e,n))&&(r.right>e||$(r.right,e,n))&&(r.top<t||$(r.top,t,n))&&(r.bottom>t||$(r.bottom,t,n))}function Hn(r){for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){const n=r[e],i=r[t];if(n!==i&&Wn(n,i,-1)){let o=[],a;const s=Dn(n,i);if(s.length===1)o=s,a=n;else{const c=Dn(i,n);s.length<c.length?(o=s,a=n):(o=c,a=i)}const l=r.filter(c=>c!==a);return Array.prototype.push.apply(l,o),Hn(l)}}return r}function Dn(r,e){const t=wo(e,r);if(t.height===0||t.width===0)return[r];const n=[];{const i={bottom:r.bottom,height:0,left:r.left,right:t.left,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:t.top,height:0,left:t.left,right:t.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:r.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{const i={bottom:r.bottom,height:0,left:t.right,right:r.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}return n}function wo(r,e){const t=Math.max(r.left,e.left),n=Math.min(r.right,e.right),i=Math.max(r.top,e.top),o=Math.min(r.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:n,top:i,width:Math.max(0,n-t)}}function Wn(r,e,t){return(r.left<e.right||t>=0&&$(r.left,e.right,t))&&(e.left<r.right||t>=0&&$(e.left,r.right,t))&&(r.top<e.bottom||t>=0&&$(r.top,e.bottom,t))&&(e.top<r.bottom||t>=0&&$(e.top,r.bottom,t))}function $(r,e,t){return Math.abs(r-e)<=t}function kt(r){const e={},t=r.document.documentElement.style;for(const n in r.document.documentElement.style)Object.hasOwn(t,n)&&!Number.isNaN(Number.parseInt(n))&&(e[t[n]]=t.getPropertyValue(t[n]));return e}function Bn(r,e){const t=kt(r);Object.keys(t).forEach(n=>{e.hasOwnProperty(n)||rt(r,n)}),Object.entries(e).forEach(([n,i])=>{t[n]!==i&&Oe(r,n,i)})}function Et(r,e){return r.document.documentElement.style.getPropertyValue(e)}function Oe(r,e,t){r.document.documentElement.style.setProperty(e,t)}function rt(r,e){r.document.documentElement.style.removeProperty(e)}let at=null,xt=null,Ae=0;const ye={r:255,g:255,b:255,a:1},_e=new Map,Ro=()=>{if(!at)if(typeof OffscreenCanvas<"u")at=new OffscreenCanvas(5,5),xt=at.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const r=document.createElement("canvas");r.width=5,r.height=5,at=r,xt=r.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return xt},Po=r=>{if(!r)return!0;const e=r.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(i=>e.includes(i))},st=(r,e)=>{console.warn(`[Decorator] Could not parse color: "${r}". ${e} Falling back to ${JSON.stringify(ye)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},Ft=(r,e=null)=>{const t=e?`${r}|${e}`:r,n=_e.get(t);if(n!==void 0)return n??ye;if(Po(r))return st(r,"Unsupported color format or special value."),_e.set(t,null),ye;const i=Ro();if(!i)return st(r,"Could not get canvas context."),_e.set(t,null),ye;try{Ae===0&&i.clearRect(0,0,5,5);const o=Ae%5,a=Math.floor(Ae/5);i.clearRect(o,a,1,1),e&&(i.fillStyle=e,i.fillRect(o,a,1,1)),i.fillStyle=r,i.fillRect(o,a,1,1);const s=i.getImageData(o,a,1,1);Ae=(Ae+1)%25;const[l,c,h,u]=s.data;if(u===0)return st(r,"Fully transparent color."),_e.set(t,null),ye;const m={r:l,g:c,b:h,a:u/255};return _e.set(t,m),m}catch(o){return st(r,`Error: ${o instanceof Error?o.message:String(o)}`),_e.set(t,null),ye}},zt=r=>{const e=r/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},jn=r=>{const e=zt(r.r),t=zt(r.g),n=zt(r.b);return .2126*e+.7152*t+.0722*n},Gn=(r,e)=>{const t=typeof r=="string"?Ft(r):r,n=typeof e=="string"?Ft(e):e,i=jn(t),o=jn(n),a=Math.max(i,o),s=Math.min(i,o);return(a+.05)/(s+.05)},Lt=(r,e=null)=>{const t=Ft(r,e),n=Gn(t,{r:255,g:255,b:255,a:1}),i=Gn(t,{r:0,g:0,b:0,a:1});return n>i},Co=(r,e=null)=>Lt(r,e)?"white":"black",Vn="#FFFF00",ko=()=>"Highlight"in window,$n=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Eo{constructor(e,t,n,i){this.wnd=e,this.comms=t,this.id=n,this.name=i,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,ko()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(e){this.activateable=e}add(e){const t=`${this.id}-${this.lastItemId++}`,n=Le(this.wnd.document,e.locator);if(!n){this.comms.log("Can't locate DOM range for decoration",e);return}const i=n.commonAncestorContainer;i.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&($n.includes(i.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),n.cloneContents().querySelector($n.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(i.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0));const o={decoration:e,id:t,range:n};this.items.push(o),this.layout(o),this.renderLayout([o])}remove(e){const t=this.items.findIndex(i=>i.decoration.id===e);if(t<0)return;const n=this.items[t];this.items.splice(t,1),n.clickableElements=void 0,n.container&&(n.container.remove(),n.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(n.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(n.range),this.notTextFlag?.delete(n.id)}update(e){this.remove(e.id),this.add(e)}clear(){this.clearContainer(),this.items.length=0,this.notTextFlag?.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(e=>this.layout(e)),this.renderLayout(this.items)}experimentalLayout(e){const[t,n]=this.requireContainer(!0);n.add(e.range);const i=Et(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"),o=e.decoration?.style?.tint??Vn;t.innerHTML=`
2
2
  ::highlight(${this.id}) {
3
- color: ${ko(o,i)};
3
+ color: ${Co(o,i)};
4
4
  background-color: ${o};
5
- }`}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 n=this.wnd.innerWidth,i=parseInt(getComputedStyle(this.wnd.document.documentElement).getPropertyValue("column-count")),o=n/(i||1),a=this.wnd.document.scrollingElement,s=a.scrollLeft,l=a.scrollTop,c=(d,p,_)=>{if(d.style.position="absolute",e.decoration?.style?.width==="viewport"){d.style.width=`${n}px`,d.style.height=`${p.height}px`;let R=Math.floor(p.left/n)*n;d.style.left=`${R+s}px`,d.style.top=`${p.top+l}px`}else if(e.decoration?.style?.width==="bounds")d.style.width=`${_.width}px`,d.style.height=`${p.height}px`,d.style.left=`${_.left+s}px`,d.style.top=`${p.top+l}px`;else if(e.decoration?.style?.width==="page"){d.style.width=`${o}px`,d.style.height=`${p.height}px`;let R=Math.floor(p.left/o)*o;d.style.left=`${R+s}px`,d.style.top=`${p.top+l}px`}else d.style.width=`${p.width}px`,d.style.height=`${p.height}px`,d.style.left=`${p.left+s}px`,d.style.top=`${p.top+l}px`},h=e.range.getBoundingClientRect();let u=this.wnd.document.createElement("template");const m=this.getCurrentDarkMode();u.innerHTML=`
5
+ }`}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 n=this.wnd.innerWidth,i=parseInt(getComputedStyle(this.wnd.document.documentElement).getPropertyValue("column-count")),o=n/(i||1),a=this.wnd.document.scrollingElement,s=a.scrollLeft,l=a.scrollTop,c=(d,p,b)=>{if(d.style.position="absolute",e.decoration?.style?.width==="viewport"){d.style.width=`${n}px`,d.style.height=`${p.height}px`;let P=Math.floor(p.left/n)*n;d.style.left=`${P+s}px`,d.style.top=`${p.top+l}px`}else if(e.decoration?.style?.width==="bounds")d.style.width=`${b.width}px`,d.style.height=`${p.height}px`,d.style.left=`${b.left+s}px`,d.style.top=`${p.top+l}px`;else if(e.decoration?.style?.width==="page"){d.style.width=`${o}px`,d.style.height=`${p.height}px`;let P=Math.floor(p.left/o)*o;d.style.left=`${P+s}px`,d.style.top=`${p.top+l}px`}else d.style.width=`${p.width}px`,d.style.height=`${p.height}px`,d.style.left=`${p.left+s}px`,d.style.top=`${p.top+l}px`},h=e.range.getBoundingClientRect();let u=this.wnd.document.createElement("template");const m=this.getCurrentDarkMode();u.innerHTML=`
6
6
  <div
7
7
  data-readium="true"
8
8
  class="readium-highlight"
9
9
  style="${[`background-color: ${e.decoration?.style?.tint??Vn} !important`,`mix-blend-mode: ${m?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}"
10
10
  >
11
11
  </div>
12
- `.trim();const f=u.content.firstElementChild;if(e.decoration?.style?.layout==="bounds"){const d=f.cloneNode(!0);d.style.setProperty("pointer-events","none"),c(d,h,h),t.append(d)}else{let d=So(e.range);d=d.sort((p,_)=>p.top<_.top?-1:p.top>_.top?1:0);for(let p of d){const _=f.cloneNode(!0);_.style.setProperty("pointer-events","none"),c(_,p,h),t.append(_)}}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(()=>{if(e=e.filter(n=>!this.experimentalHighlights||!!this.notTextFlag?.has(n.id)),!e||e.length===0)return;this.requireContainer().append(...e.map(n=>n.container).filter(n=>!!n))})}requireContainer(e=!1){if(e){let t;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));let n;return this.wnd.CSS.highlights.has(this.id)?n=this.wnd.CSS.highlights.get(this.id):(n=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,n)),[t,n]}return this.container||(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.wnd.document.body.append(this.container)),this.container}getCurrentDarkMode(){return Ct(this.wnd,"--USER__appearance")==="readium-night-on"||Ot(Ct(this.wnd,"--USER__backgroundColor"))||Ot(this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"))}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const qe=class qe extends fe{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(e=>e.clear()),this.groups.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}extractCustomProperty(e,t){if(!e)return null;const n=e.match(new RegExp(`${t}:\\s*([^;]+)`));return n?n[1].trim():null}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>{e.experimentalHighlights||e.requestLayout()})},50)}mount(e,t){return this.wnd=e,t.register("decorate",qe.moduleName,(n,i)=>{const o=n;o.decoration&&o.decoration.locator&&(o.decoration.locator=F.deserialize(o.decoration.locator)),this.groups.has(o.group)||this.groups.set(o.group,new Co(e,t,`readium-decoration-${this.lastGroupId++}`,o.group));const a=this.groups.get(o.group);switch(o.action){case"add":a?.add(o.decoration);break;case"remove":a?.remove(o.decoration.id);break;case"clear":a?.clear();break;case"update":a?.update(o.decoration);break}i(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.body),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),this.backgroundObserver=new MutationObserver(n=>{n.some(o=>{if(o.type==="attributes"&&o.attributeName==="style"){const a=o.target,s=o.oldValue,l=a.getAttribute("style"),c=this.extractCustomProperty(s,"--USER__appearance"),h=this.extractCustomProperty(l,"--USER__appearance"),u=this.extractCustomProperty(s,"--USER__backgroundColor"),m=this.extractCustomProperty(l,"--USER__backgroundColor");return c!==h||u!==m}return!1})&&this.updateHighlightStyles()}),this.backgroundObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0,subtree:!0}),t.log("Decorator Mounted"),!0}unmount(e,t){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),t.unregisterAll(qe.moduleName),this.resizeObserver.disconnect(),this.backgroundObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}};qe.moduleName="decorator";let At=qe;const Xn="readium-snapper-style",Ke=class Ke extends fe{constructor(){super(...arguments),this.protected=!1}buildStyles(){return`
12
+ `.trim();const f=u.content.firstElementChild;if(e.decoration?.style?.layout==="bounds"){const d=f.cloneNode(!0);d.style.setProperty("pointer-events","none"),c(d,h,h),t.append(d)}else{let d=_o(e.range);d=d.sort((p,b)=>p.top<b.top?-1:p.top>b.top?1:0);for(let p of d){const b=f.cloneNode(!0);b.style.setProperty("pointer-events","none"),c(b,p,h),t.append(b)}}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(()=>{if(e=e.filter(n=>!this.experimentalHighlights||!!this.notTextFlag?.has(n.id)),!e||e.length===0)return;this.requireContainer().append(...e.map(n=>n.container).filter(n=>!!n))})}requireContainer(e=!1){if(e){let t;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));let n;return this.wnd.CSS.highlights.has(this.id)?n=this.wnd.CSS.highlights.get(this.id):(n=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,n)),[t,n]}return this.container||(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.wnd.document.body.append(this.container)),this.container}getCurrentDarkMode(){return Et(this.wnd,"--USER__appearance")==="readium-night-on"||Lt(Et(this.wnd,"--USER__backgroundColor"))||Lt(this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"))}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const Ye=class Ye extends fe{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(e=>e.clear()),this.groups.clear()}updateHighlightStyles(){this.groups.forEach(e=>{e.requestLayout()})}extractCustomProperty(e,t){if(!e)return null;const n=e.match(new RegExp(`${t}:\\s*([^;]+)`));return n?n[1].trim():null}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(e=>{e.experimentalHighlights||e.requestLayout()})},50)}mount(e,t){return this.wnd=e,t.register("decorate",Ye.moduleName,(n,i)=>{const o=n;o.decoration&&o.decoration.locator&&(o.decoration.locator=N.deserialize(o.decoration.locator)),this.groups.has(o.group)||this.groups.set(o.group,new Eo(e,t,`readium-decoration-${this.lastGroupId++}`,o.group));const a=this.groups.get(o.group);switch(o.action){case"add":a?.add(o.decoration);break;case"remove":a?.remove(o.decoration.id);break;case"clear":a?.clear();break;case"update":a?.update(o.decoration);break}i(!0)}),this.resizeObserver=new ResizeObserver(()=>e.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(e.document.body),e.addEventListener("orientationchange",this.handleResizer),e.addEventListener("resize",this.handleResizer),this.backgroundObserver=new MutationObserver(n=>{n.some(o=>{if(o.type==="attributes"&&o.attributeName==="style"){const a=o.target,s=o.oldValue,l=a.getAttribute("style"),c=this.extractCustomProperty(s,"--USER__appearance"),h=this.extractCustomProperty(l,"--USER__appearance"),u=this.extractCustomProperty(s,"--USER__backgroundColor"),m=this.extractCustomProperty(l,"--USER__backgroundColor");return c!==h||u!==m}return!1})&&this.updateHighlightStyles()}),this.backgroundObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"],attributeOldValue:!0,subtree:!0}),t.log("Decorator Mounted"),!0}unmount(e,t){return e.removeEventListener("orientationchange",this.handleResizer),e.removeEventListener("resize",this.handleResizer),t.unregisterAll(Ye.moduleName),this.resizeObserver.disconnect(),this.backgroundObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}};Ye.moduleName="decorator";let Ot=Ye;const Kn="readium-snapper-style",qe=class qe extends fe{constructor(){super(...arguments),this.protected=!1}buildStyles(){return`
13
13
  html, body {
14
14
  touch-action: manipulation;
15
15
  user-select: ${this.protected?"none":"auto"};
16
- }`}mount(e,t){const n=e.document.createElement("style");return n.dataset.readium="true",n.id=Xn,n.textContent=this.buildStyles(),e.document.head.appendChild(n),t.register("protect",Ke.moduleName,(i,o)=>{this.protected=!0,n.textContent=this.buildStyles(),o(!0)}),t.register("unprotect",Ke.moduleName,(i,o)=>{this.protected=!1,n.textContent=this.buildStyles(),o(!0)}),t.log("Snapper Mounted"),!0}unmount(e,t){return e.document.getElementById(Xn)?.remove(),t.log("Snapper Unmounted"),!0}};Ke.moduleName="snapper";let be=Ke;function xo(r){return(r.document.documentElement.dir||r.document.body.dir).toLowerCase()==="rtl"}function Lo(r){return(r.getComputedStyle(r.document.documentElement).writingMode||r.getComputedStyle(r.document.body).writingMode)==="vertical-lr"}function Yn(r){return parseInt(r.getComputedStyle(r.document.documentElement).getPropertyValue("column-count"))}function qn(r){const e=getComputedStyle(r),t=parseFloat(e.paddingTop||"0"),n=parseFloat(e.paddingBottom||"0");return r.clientHeight-t-n}function Kn(r){const e=Yn(r);if(!e)return!1;const t=r.document.querySelectorAll("div[id^='readium-virtual-page']");for(const c of t)c.remove();const n=t.length,i=r.document.scrollingElement.scrollWidth,o=r.visualViewport.width,s=Math.round(i/o*e)%e,l=e===1||s===0?0:e-s;if(l>0)for(let c=0;c<l;c++){const h=r.document.createElement("div");h.setAttribute("id",`readium-virtual-page-${c}`),h.dataset.readium="true",CSS.supports("break-before","column")?h.style.breakBefore="column":(CSS.supports("break-inside","avoid-column")&&(h.style.breakInside="avoid-column"),h.style.height=qn(r.document.documentElement)+"px"),h.innerHTML="&#8203;",r.document.body.appendChild(h)}return n!==l}function Ut(r){const e=r.document.createElement("style");e.appendChild(r.document.createTextNode("*{}")),r.document.body.appendChild(e),r.document.body.removeChild(e)}function zo(r){return r<.5?2*r*r:-1+(4-2*r)*r}function z(r){const e=r.getSelection();e&&e.removeAllRanges()}const Oo=["a","area","audio","button","canvas","details","input","label","option","select","submit","textarea","video"],Ao=["dialog","radiogroup","radio","menu","menuitem"];function Tt(r){return Uo(r)?null:Zn(r)?r:r.parentElement?Tt(r.parentElement):null}function Uo(r){return r?r.closest("[inert]")!==null||r.hasAttribute("disabled"):!0}function Zn(r){return r?r.role&&Ao.includes(r.role)||r.tabIndex>=0?!0:Oo.includes(r.nodeName.toLowerCase())||r.hasAttribute("contenteditable")&&r.getAttribute("contenteditable")?.toLowerCase()!=="false":!1}function lt(r,e){const t=Jn(r,r.document.body,e),n=r._readium_cssSelectorGenerator.getCssSelector(t,{selectors:["tag","id","class","nthchild","nthoftype","attribute"]});return new F({href:"#",type:"application/xhtml+xml",locations:new k({otherLocations:new Map([["cssSelector",n]])}),text:new oe({highlight:t.textContent||void 0})})}function Jn(r,e,t){for(var n=0;n<e.children.length;n++){const i=e.children[n];if(!Fo(i)&&To(r,i,t))return Mo(r,i)?i:Jn(r,i,t)}return e}function To(r,e,t){if(e===document.body||e===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const n=e.getBoundingClientRect();return t?n.bottom>0&&n.top<r.innerHeight:n.right>0&&n.left<r.innerWidth}function Mo(r,e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=r.innerHeight&&t.right<=r.innerWidth}function Fo(r){const e=getComputedStyle(r);if(e){const t=e.getPropertyValue("display");if(t!="block"&&t!="list-item"||e.getPropertyValue("opacity")==="0")return!0}return!1}const No={maxVelocity:200,minVariance:.01,historySize:20,minDirectionChanges:.2,maxConsistentScrolls:15},Mt={maxVelocity:200,minVariance:1e-5,historySize:100,minDirectionChanges:.1,maxConsistentScrolls:20},Qn={maxSelectionsPerSecond:500,minVariance:50,historySize:20},Io={enabled:!0,maxSelectionPercent:.1,minThreshold:100,absoluteMaxChars:5e3,historySize:20};class ct{constructor(e={}){this.history=[],this.consistentScrollCount=0,this.options={...No,...e}}analyze(e,t,n){if(n<=0)return!1;const i=Math.abs(t)/n,o=Date.now();if(this.history.push({timestamp:o,direction:e,velocity:i,distance:Math.abs(t)}),this.history=this.history.filter(p=>o-p.timestamp<2e3).slice(-(this.options.historySize||20)),this.history.length<3)return!1;if(i>this.options.maxVelocity)return this.resetAfterDetection(),!0;const a=this.history.map(p=>p.velocity),s=this.history.map(p=>p.distance),l=a.reduce((p,_)=>p+_,0)/a.length,c=s.reduce((p,_)=>p+_,0)/s.length,h=a.reduce((p,_)=>p+Math.pow(_-l,2),0)/a.length,u=s.reduce((p,_)=>p+Math.pow(_-c,2),0)/s.length;if(h<this.options.minVariance&&u<c*.1){if(this.consistentScrollCount++,this.consistentScrollCount>=(this.options.maxConsistentScrolls||10))return this.resetAfterDetection(),!0}else this.consistentScrollCount=Math.max(0,this.consistentScrollCount-1);let m=0,f=this.history[0].direction;for(let p=1;p<this.history.length;p++)this.history[p].direction!==f&&(m++,f=this.history[p].direction);return m/this.history.length>(this.options.minDirectionChanges||.3)?(this.resetAfterDetection(),!0):!1}resetAfterDetection(){this.history=this.history.slice(-3),this.consistentScrollCount=0}clear(){this.history=[],this.consistentScrollCount=0}}const ei="readium-column-snapper-style",Do=200,H=class H extends be{constructor(){super(...arguments),this.isSnapProtectionEnabled=!1,this.patternAnalyzer=null,this.lastTurnTime=0,this.rtl=!1,this.shakeTimeout=0,this.snappingCancelled=!1,this.alreadyScrollLeft=0,this.overscroll=0,this.cachedScrollWidth=0,this.touchState=0,this.startingX=void 0,this.endingX=void 0,this.onTouchStarter=this.onTouchStart.bind(this),this.onTouchEnder=this.onTouchEnd.bind(this),this.onWidthChanger=this.onWidthChange.bind(this),this.onTouchMover=this.onTouchMove.bind(this)}doc(){return this.wnd.document.scrollingElement}scrollOffset(){const e=this.doc().scrollLeft;return e!==0?e:this.alreadyScrollLeft}snapOffset(e){const t=e+(this.rtl?-1:1);return t-t%this.wnd.innerWidth}snapNormOffset(e){const t=e+1;return t-t%this.wnd.innerWidth}normScroll(){const e=this.doc().scrollLeft||this.alreadyScrollLeft;return this.rtl?Math.abs(e):Math.max(0,this.wnd.scrollX>0?this.wnd.scrollX:e)}reportProgress(){const e=this.cachedScrollWidth,t=this.wnd.innerWidth,n=this.normScroll(),i=Math.max(1,e-t),o=Math.max(0,Math.min(1,n/i)),a=Math.max(0,Math.min(1,(n+t)/e));this.comms.send("progress",{start:o,end:a})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const e=this.doc(),t=this.normScroll()<5,n=this.rtl?t?"readium-bounce-r":"readium-bounce-l":"readium-bounce-r";e.classList.add(n);const i=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{e.classList.remove(n),this.shakeTimeout=0,this.doc().scrollLeft=i},150)}takeOverSnap(){this.snappingCancelled=!0,this.clearTouches();const e=this.doc();this.overscroll=e.style.transform?.length>12?parseFloat(e.style.transform.slice(12).split("px")[0]):0}snapCurrentOffset(e=!1,t=!1){const n=this.doc(),i=Yn(this.wnd),o=this.cachedScrollWidth-this.wnd.innerWidth,a=Math.min(Math.max(0,this.normScroll()),o),s=this.dragOffset(),l=this.rtl?-s:s,c=this.wnd.innerWidth/3*(l>0?2:1),h=Math.min(o,Math.max(0,this.snapNormOffset(a+c))),u=this.rtl?-h:h,m=this.rtl?-a:a,f=u>m?"right":"left";if(this.checkSuspiciousSnap(f,Math.abs(u-m)),e&&u!==m){this.snappingCancelled=!1;const d=(U,Q,xe,Le)=>xe>Le?Q:U+(Q-U)*zo(xe/Le),p=Do*i;let _;const R=U=>{if(this.snappingCancelled)return;_||(_=U);const Q=U-_,xe=d(this.overscroll,0,Q,p),Le=d(m,u,Q,p);n.scrollLeft=Le,this.overscroll!==0&&(n.style.transform=`translate3d(${-xe}px, 0px, 0px)`),Q<p?this.wnd.requestAnimationFrame(R):(this.clearTouches(),n.style.removeProperty("transform"),n.scrollLeft=u,t||this.reportProgress())};this.wnd.requestAnimationFrame(R)}else n.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{n.scrollLeft=u,this.clearTouches(),t||this.reportProgress()})}dragOffset(){return(this.startingX??0)-(this.endingX??0)}clearTouches(){this.startingX=void 0,this.endingX=void 0,this.overscroll=0}onTouchStart(e){switch(e.stopPropagation(),this.takeOverSnap(),e.touches.length){case 1:break;case 2:this.onTouchEnd(e);return;default:{this.onTouchEnd(e),this.comms.send("tap_more",e.touches.length);return}}this.startingX=e.touches[0].clientX,this.alreadyScrollLeft=this.doc().scrollLeft,this.touchState=1}onTouchEnd(e){if(this.touchState===2){const t=this.dragOffset(),n=this.normScroll(),i=this.cachedScrollWidth-this.wnd.innerWidth,o=this.rtl?-t:t;this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),o>5&&this.comms.send("no_more",void 0),o<-5&&this.comms.send("no_less",void 0)):n<5&&o<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):i-n<5&&o>5&&(this.alreadyScrollLeft=this.rtl?-i:i,this.comms.send("no_more",void 0)),this.snapCurrentOffset(!0),this.comms.send("swipe",t)}this.touchState=0}onWidthChange(){this.cachedScrollWidth=this.doc().scrollWidth,this.comms.ready&&this.snapCurrentOffset()}onTouchMove(e){if(this.touchState===0)return;this.touchState===1&&(this.touchState=2,z(this.wnd)),this.endingX=e.touches[0].clientX;const t=this.dragOffset(),n=this.alreadyScrollLeft+t,i=this.rtl?-(this.cachedScrollWidth-this.wnd.innerWidth):0,o=this.rtl?0:this.cachedScrollWidth-this.wnd.innerWidth;n<i?(this.overscroll=n,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):n>o?(this.overscroll=n,this.doc().style.transform=`translate3d(${-n}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=n)}enableSnapProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct({maxVelocity:this.wnd.innerWidth,minVariance:.1,historySize:5,maxConsistentScrolls:3,minDirectionChanges:.3}),this.isSnapProtectionEnabled=!0,this.comms?.log("Snap protection enabled"))}checkSuspiciousSnap(e,t){if(!this.isSnapProtectionEnabled||!this.patternAnalyzer)return;const n=Date.now(),i=n-(this.lastTurnTime||n);this.lastTurnTime=n,this.patternAnalyzer.analyze(e,t,i)&&this.comms?.send("content_protection",{type:"suspicious_snapping",timestamp:Date.now(),event:null})}mount(e,t){if(this.wnd=e,this.comms=t,this.rtl=xo(e),!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const n=e.document.createElement("style");n.dataset.readium="true",n.id=ei,n.textContent=`
16
+ }`}mount(e,t){const n=e.document.createElement("style");return n.dataset.readium="true",n.id=Kn,n.textContent=this.buildStyles(),e.document.head.appendChild(n),t.register("protect",qe.moduleName,(i,o)=>{this.protected=!0,n.textContent=this.buildStyles(),o(!0)}),t.register("unprotect",qe.moduleName,(i,o)=>{this.protected=!1,n.textContent=this.buildStyles(),o(!0)}),t.log("Snapper Mounted"),!0}unmount(e,t){return e.document.getElementById(Kn)?.remove(),t.log("Snapper Unmounted"),!0}};qe.moduleName="snapper";let Se=qe;function xo(r){return(r.document.documentElement.dir||r.document.body.dir).toLowerCase()==="rtl"}function Fo(r){return(r.getComputedStyle(r.document.documentElement).writingMode||r.getComputedStyle(r.document.body).writingMode)==="vertical-lr"}function Xn(r){return parseInt(r.getComputedStyle(r.document.documentElement).getPropertyValue("column-count"))}function Yn(r){const e=getComputedStyle(r),t=parseFloat(e.paddingTop||"0"),n=parseFloat(e.paddingBottom||"0");return r.clientHeight-t-n}function qn(r){const e=Xn(r);if(!e)return!1;const t=r.document.querySelectorAll("div[id^='readium-virtual-page']");for(const c of t)c.remove();const n=t.length,i=r.document.scrollingElement.scrollWidth,o=r.visualViewport.width,s=Math.round(i/o*e)%e,l=e===1||s===0?0:e-s;if(l>0)for(let c=0;c<l;c++){const h=r.document.createElement("div");h.setAttribute("id",`readium-virtual-page-${c}`),h.dataset.readium="true",CSS.supports("break-before","column")?h.style.breakBefore="column":(CSS.supports("break-inside","avoid-column")&&(h.style.breakInside="avoid-column"),h.style.height=Yn(r.document.documentElement)+"px"),h.innerHTML="&#8203;",r.document.body.appendChild(h)}return n!==l}function At(r){const e=r.document.createElement("style");e.appendChild(r.document.createTextNode("*{}")),r.document.body.appendChild(e),r.document.body.removeChild(e)}function zo(r){return r<.5?2*r*r:-1+(4-2*r)*r}function z(r){const e=r.getSelection();e&&e.removeAllRanges()}const Lo=["a","area","audio","button","canvas","details","input","label","option","select","submit","textarea","video"],Oo=["dialog","radiogroup","radio","menu","menuitem"];function Ut(r){return Ao(r)?null:Jn(r)?r:r.parentElement?Ut(r.parentElement):null}function Ao(r){return r?r.closest("[inert]")!==null||r.hasAttribute("disabled"):!0}function Jn(r){return r?r.role&&Oo.includes(r.role)||r.tabIndex>=0?!0:Lo.includes(r.nodeName.toLowerCase())||r.hasAttribute("contenteditable")&&r.getAttribute("contenteditable")?.toLowerCase()!=="false":!1}function lt(r,e){const t=Zn(r,r.document.body,e),n=r._readium_cssSelectorGenerator.getCssSelector(t,{selectors:["tag","id","class","nthchild","nthoftype","attribute"]});return new N({href:"#",type:"application/xhtml+xml",locations:new C({otherLocations:new Map([["cssSelector",n]])}),text:new oe({highlight:t.textContent||void 0})})}function Zn(r,e,t){for(var n=0;n<e.children.length;n++){const i=e.children[n];if(!No(i)&&Uo(r,i,t))return To(r,i)?i:Zn(r,i,t)}return e}function Uo(r,e,t){if(e===document.body||e===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const n=e.getBoundingClientRect();return t?n.bottom>0&&n.top<r.innerHeight:n.right>0&&n.left<r.innerWidth}function To(r,e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=r.innerHeight&&t.right<=r.innerWidth}function No(r){const e=getComputedStyle(r);if(e){const t=e.getPropertyValue("display");if(t!="block"&&t!="list-item"||e.getPropertyValue("opacity")==="0")return!0}return!1}const Mo={maxVelocity:200,minVariance:.01,historySize:20,minDirectionChanges:.2,maxConsistentScrolls:15},Tt={maxVelocity:200,minVariance:1e-5,historySize:100,minDirectionChanges:.1,maxConsistentScrolls:20},Qn={maxSelectionsPerSecond:500,minVariance:50,historySize:20},Io={enabled:!0,maxSelectionPercent:.1,minThreshold:100,absoluteMaxChars:5e3,historySize:20};class ct{constructor(e={}){this.history=[],this.consistentScrollCount=0,this.options={...Mo,...e}}analyze(e,t,n){if(n<=0)return!1;const i=Math.abs(t)/n,o=Date.now();if(this.history.push({timestamp:o,direction:e,velocity:i,distance:Math.abs(t)}),this.history=this.history.filter(p=>o-p.timestamp<2e3).slice(-(this.options.historySize||20)),this.history.length<3)return!1;if(i>this.options.maxVelocity)return this.resetAfterDetection(),!0;const a=this.history.map(p=>p.velocity),s=this.history.map(p=>p.distance),l=a.reduce((p,b)=>p+b,0)/a.length,c=s.reduce((p,b)=>p+b,0)/s.length,h=a.reduce((p,b)=>p+Math.pow(b-l,2),0)/a.length,u=s.reduce((p,b)=>p+Math.pow(b-c,2),0)/s.length;if(h<this.options.minVariance&&u<c*.1){if(this.consistentScrollCount++,this.consistentScrollCount>=(this.options.maxConsistentScrolls||10))return this.resetAfterDetection(),!0}else this.consistentScrollCount=Math.max(0,this.consistentScrollCount-1);let m=0,f=this.history[0].direction;for(let p=1;p<this.history.length;p++)this.history[p].direction!==f&&(m++,f=this.history[p].direction);return m/this.history.length>(this.options.minDirectionChanges||.3)?(this.resetAfterDetection(),!0):!1}resetAfterDetection(){this.history=this.history.slice(-3),this.consistentScrollCount=0}clear(){this.history=[],this.consistentScrollCount=0}}const ei="readium-column-snapper-style",Ho=200,D=class D extends Se{constructor(){super(...arguments),this.isSnapProtectionEnabled=!1,this.patternAnalyzer=null,this.lastTurnTime=0,this.rtl=!1,this.shakeTimeout=0,this.snappingCancelled=!1,this.alreadyScrollLeft=0,this.overscroll=0,this.cachedScrollWidth=0,this.touchState=0,this.startingX=void 0,this.endingX=void 0,this.onTouchStarter=this.onTouchStart.bind(this),this.onTouchEnder=this.onTouchEnd.bind(this),this.onWidthChanger=this.onWidthChange.bind(this),this.onTouchMover=this.onTouchMove.bind(this)}doc(){return this.wnd.document.scrollingElement}scrollOffset(){const e=this.doc().scrollLeft;return e!==0?e:this.alreadyScrollLeft}snapOffset(e){const t=e+(this.rtl?-1:1);return t-t%this.wnd.innerWidth}snapNormOffset(e){const t=e+1;return t-t%this.wnd.innerWidth}normScroll(){const e=this.doc().scrollLeft||this.alreadyScrollLeft;return this.rtl?Math.abs(e):Math.max(0,this.wnd.scrollX>0?this.wnd.scrollX:e)}reportProgress(){const e=this.cachedScrollWidth,t=this.wnd.innerWidth,n=this.normScroll(),i=Math.max(1,e-t),o=Math.max(0,Math.min(1,n/i)),a=Math.max(0,Math.min(1,(n+t)/e));this.comms.send("progress",{start:o,end:a})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const e=this.doc(),t=this.normScroll()<5,n=this.rtl?t?"readium-bounce-r":"readium-bounce-l":"readium-bounce-r";e.classList.add(n);const i=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{e.classList.remove(n),this.shakeTimeout=0,this.doc().scrollLeft=i},150)}takeOverSnap(){this.snappingCancelled=!0,this.clearTouches();const e=this.doc();this.overscroll=e.style.transform?.length>12?parseFloat(e.style.transform.slice(12).split("px")[0]):0}snapCurrentOffset(e=!1,t=!1){const n=this.doc(),i=Xn(this.wnd),o=this.cachedScrollWidth-this.wnd.innerWidth,a=Math.min(Math.max(0,this.normScroll()),o),s=this.dragOffset(),l=this.rtl?-s:s,c=this.wnd.innerWidth/3*(l>0?2:1),h=Math.min(o,Math.max(0,this.snapNormOffset(a+c))),u=this.rtl?-h:h,m=this.rtl?-a:a,f=u>m?"right":"left";if(this.checkSuspiciousSnap(f,Math.abs(u-m)),e&&u!==m){this.snappingCancelled=!1;const d=(A,Q,xe,Fe)=>xe>Fe?Q:A+(Q-A)*zo(xe/Fe),p=Ho*i;let b;const P=A=>{if(this.snappingCancelled)return;b||(b=A);const Q=A-b,xe=d(this.overscroll,0,Q,p),Fe=d(m,u,Q,p);n.scrollLeft=Fe,this.overscroll!==0&&(n.style.transform=`translate3d(${-xe}px, 0px, 0px)`),Q<p?this.wnd.requestAnimationFrame(P):(this.clearTouches(),n.style.removeProperty("transform"),n.scrollLeft=u,t||this.reportProgress())};this.wnd.requestAnimationFrame(P)}else n.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{n.scrollLeft=u,this.clearTouches(),t||this.reportProgress()})}dragOffset(){return(this.startingX??0)-(this.endingX??0)}clearTouches(){this.startingX=void 0,this.endingX=void 0,this.overscroll=0}onTouchStart(e){switch(e.stopPropagation(),this.takeOverSnap(),e.touches.length){case 1:break;case 2:this.onTouchEnd(e);return;default:{this.onTouchEnd(e),this.comms.send("tap_more",e.touches.length);return}}this.startingX=e.touches[0].clientX,this.alreadyScrollLeft=this.doc().scrollLeft,this.touchState=1}onTouchEnd(e){if(this.touchState===2){const t=this.dragOffset(),n=this.normScroll(),i=this.cachedScrollWidth-this.wnd.innerWidth,o=this.rtl?-t:t;this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),o>5&&this.comms.send("no_more",void 0),o<-5&&this.comms.send("no_less",void 0)):n<5&&o<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):i-n<5&&o>5&&(this.alreadyScrollLeft=this.rtl?-i:i,this.comms.send("no_more",void 0)),this.snapCurrentOffset(!0),this.comms.send("swipe",t)}this.touchState=0}onWidthChange(){this.cachedScrollWidth=this.doc().scrollWidth,this.comms.ready&&this.snapCurrentOffset()}onTouchMove(e){if(this.touchState===0)return;this.touchState===1&&(this.touchState=2,z(this.wnd)),this.endingX=e.touches[0].clientX;const t=this.dragOffset(),n=this.alreadyScrollLeft+t,i=this.rtl?-(this.cachedScrollWidth-this.wnd.innerWidth):0,o=this.rtl?0:this.cachedScrollWidth-this.wnd.innerWidth;n<i?(this.overscroll=n,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):n>o?(this.overscroll=n,this.doc().style.transform=`translate3d(${-n}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=n)}enableSnapProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct({maxVelocity:this.wnd.innerWidth,minVariance:.1,historySize:5,maxConsistentScrolls:3,minDirectionChanges:.3}),this.isSnapProtectionEnabled=!0,this.comms?.log("Snap protection enabled"))}checkSuspiciousSnap(e,t){if(!this.isSnapProtectionEnabled||!this.patternAnalyzer)return;const n=Date.now(),i=n-(this.lastTurnTime||n);this.lastTurnTime=n,this.patternAnalyzer.analyze(e,t,i)&&this.comms?.send("content_protection",{type:"suspicious_snapping",timestamp:Date.now(),event:null})}mount(e,t){if(this.wnd=e,this.comms=t,this.rtl=xo(e),!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const n=e.document.createElement("style");n.dataset.readium="true",n.id=ei,n.textContent=`
17
17
  @keyframes readium-bounce-l-animation {
18
18
  0%, 100% {transform: translate3d(0, 0, 0);}
19
19
  50% {transform: translate3d(-50px, 0, 0);}
@@ -47,7 +47,7 @@
47
47
  body::-webkit-scrollbar {
48
48
  display: none; /* for Chrome, Safari, and Opera */
49
49
  }
50
- `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{e.requestAnimationFrame(()=>{e&&Kn(e)}),this.onWidthChange()}),this.resizeObserver.observe(e.document.body),this.mutationObserver=new MutationObserver(a=>{for(const s of a)if(s.target===this.wnd.document.documentElement){const l=s.oldValue,c=s.target.getAttribute("style"),h=/transform\s*:\s*([^;]+)/,u=l?.match(h),m=c?.match(h);(!u&&!m||u&&!m||u&&m&&u[1]!==m[1])&&(e.requestAnimationFrame(()=>{e&&Kn(e)}),this.onWidthChange())}else e.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),e.frameElement&&this.mutationObserver.observe(e.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(e.document,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"]}),t.register("scroll_protection",H.moduleName,(a,s)=>{this.enableSnapProtection(),s(!0)});const i=a=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(a),s!==this.doc().scrollLeft},o=a=>{const s=this.doc().scrollLeft,l=this.snapNormOffset(Math.max(0,Math.min(this.cachedScrollWidth-e.innerWidth,a)));return this.doc().scrollLeft=-l,s!==this.doc().scrollLeft};return e.addEventListener("orientationchange",this.onWidthChanger),e.addEventListener("resize",this.onWidthChanger),e.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),t.register("go_progression",H.moduleName,(a,s)=>{const l=a;if(l<0||l>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),s(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const h=(this.cachedScrollWidth-e.innerWidth)*l;this.rtl?this.doc().scrollLeft=-this.snapNormOffset(h):this.doc().scrollLeft=this.snapOffset(h),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_id",H.moduleName,(a,s)=>{const l=e.document.getElementById(a);if(!l){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.rtl?this.doc().scrollLeft=-this.snapNormOffset(l.getBoundingClientRect().left+e.scrollX):this.doc().scrollLeft=this.snapOffset(l.getBoundingClientRect().left+e.scrollX),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_text",H.moduleName,(a,s)=>{let l;Array.isArray(a)&&(a.length>1&&(l=a[1]),a=a[0]);const c=oe.deserialize(a),h=Oe(this.wnd.document,new F({href:e.location.href,type:"text/html",text:c,locations:l?new k({otherLocations:new Map([["cssSelector",l]])}):void 0}));if(!h){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.rtl?this.doc().scrollLeft=-this.snapNormOffset(h.getBoundingClientRect().left+e.scrollX):this.doc().scrollLeft=this.snapOffset(h.getBoundingClientRect().left+e.scrollX),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_end",H.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;if(this.rtl?l=-this.snapNormOffset(this.cachedScrollWidth-e.innerWidth):l=this.snapOffset(this.cachedScrollWidth),this.doc().scrollLeft===l)return s(!1);this.doc().scrollLeft=l,this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_start",H.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return s(!1);this.doc().scrollLeft=0,this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_prev",H.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;this.rtl?l=o(this.normScroll()-e.innerWidth):l=i(e.scrollX-e.innerWidth),this.reportProgress(),l&&(z(this.wnd),this.checkSuspiciousSnap("left",this.wnd.innerWidth)),s(l)})}),t.register("go_next",H.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;this.rtl?l=o(this.normScroll()+e.innerWidth):l=i(e.scrollX+e.innerWidth),this.reportProgress(),l&&(z(this.wnd),this.checkSuspiciousSnap("right",this.wnd.innerWidth)),s(l)})}),t.register("unfocus",H.moduleName,(a,s)=>{this.snappingCancelled=!0,z(this.wnd),s(!0)}),t.register("shake",H.moduleName,(a,s)=>{this.shake(),s(!0)}),t.register("focus",H.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),s(!0)})}),t.register("first_visible_locator",H.moduleName,(a,s)=>{const l=lt(e,!1);this.comms.send("first_visible_locator",l.serialize()),s(!0)}),e.addEventListener("touchstart",this.onTouchStarter,{passive:!0}),e.addEventListener("touchend",this.onTouchEnder,{passive:!0}),e.addEventListener("touchmove",this.onTouchMover,{passive:!0}),e.document.addEventListener("touchstart",()=>{}),t.log("ColumnSnapper Mounted"),!0}unmount(e,t){return this.snappingCancelled=!0,t.unregisterAll(H.moduleName),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isSnapProtectionEnabled=!1),e.removeEventListener("touchstart",this.onTouchStarter),e.removeEventListener("touchend",this.onTouchEnder),e.removeEventListener("touchmove",this.onTouchMover),e.removeEventListener("orientationchange",this.onWidthChanger),e.removeEventListener("resize",this.onWidthChanger),e.document.getElementById(ei)?.remove(),t.log("ColumnSnapper Unmounted"),super.unmount(e,t)}};H.moduleName="column_snapper";let Ft=H;const ti="readium-scroll-snapper-style",W=class W extends be{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,n=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"down":"up",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,n=this.wnd.innerHeight,i=Math.max(0,Math.min(1,e/t)),o=Math.max(0,Math.min(1,(e+n)/t));this.comms.send("progress",{start:i,end:o})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Mt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="scrolling");const n=e.document.createElement("style");return n.dataset.readium="true",n.id=ti,n.textContent=`
50
+ `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{e.requestAnimationFrame(()=>{e&&qn(e)}),this.onWidthChange()}),this.resizeObserver.observe(e.document.body),this.mutationObserver=new MutationObserver(a=>{for(const s of a)if(s.target===this.wnd.document.documentElement){const l=s.oldValue,c=s.target.getAttribute("style"),h=/transform\s*:\s*([^;]+)/,u=l?.match(h),m=c?.match(h);(!u&&!m||u&&!m||u&&m&&u[1]!==m[1])&&(e.requestAnimationFrame(()=>{e&&qn(e)}),this.onWidthChange())}else e.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),e.frameElement&&this.mutationObserver.observe(e.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(e.document,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(e.document.documentElement,{attributes:!0,attributeFilter:["style"]}),t.register("scroll_protection",D.moduleName,(a,s)=>{this.enableSnapProtection(),s(!0)});const i=a=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(a),s!==this.doc().scrollLeft},o=a=>{const s=this.doc().scrollLeft,l=this.snapNormOffset(Math.max(0,Math.min(this.cachedScrollWidth-e.innerWidth,a)));return this.doc().scrollLeft=-l,s!==this.doc().scrollLeft};return e.addEventListener("orientationchange",this.onWidthChanger),e.addEventListener("resize",this.onWidthChanger),e.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),t.register("go_progression",D.moduleName,(a,s)=>{const l=a;if(l<0||l>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),s(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const h=(this.cachedScrollWidth-e.innerWidth)*l;this.rtl?this.doc().scrollLeft=-this.snapNormOffset(h):this.doc().scrollLeft=this.snapOffset(h),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_id",D.moduleName,(a,s)=>{const l=e.document.getElementById(a);if(!l){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.rtl?this.doc().scrollLeft=-this.snapNormOffset(l.getBoundingClientRect().left+e.scrollX):this.doc().scrollLeft=this.snapOffset(l.getBoundingClientRect().left+e.scrollX),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_text",D.moduleName,(a,s)=>{let l;Array.isArray(a)&&(a.length>1&&(l=a[1]),a=a[0]);const c=oe.deserialize(a),h=Le(this.wnd.document,new N({href:e.location.href,type:"text/html",text:c,locations:l?new C({otherLocations:new Map([["cssSelector",l]])}):void 0}));if(!h){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.rtl?this.doc().scrollLeft=-this.snapNormOffset(h.getBoundingClientRect().left+e.scrollX):this.doc().scrollLeft=this.snapOffset(h.getBoundingClientRect().left+e.scrollX),this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_end",D.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;if(this.rtl?l=-this.snapNormOffset(this.cachedScrollWidth-e.innerWidth):l=this.snapOffset(this.cachedScrollWidth),this.doc().scrollLeft===l)return s(!1);this.doc().scrollLeft=l,this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_start",D.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return s(!1);this.doc().scrollLeft=0,this.reportProgress(),z(this.wnd),s(!0)})}),t.register("go_prev",D.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;this.rtl?l=o(this.normScroll()-e.innerWidth):l=i(e.scrollX-e.innerWidth),this.reportProgress(),l&&(z(this.wnd),this.checkSuspiciousSnap("left",this.wnd.innerWidth)),s(l)})}),t.register("go_next",D.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;let l;this.rtl?l=o(this.normScroll()+e.innerWidth):l=i(e.scrollX+e.innerWidth),this.reportProgress(),l&&(z(this.wnd),this.checkSuspiciousSnap("right",this.wnd.innerWidth)),s(l)})}),t.register("unfocus",D.moduleName,(a,s)=>{this.snappingCancelled=!0,z(this.wnd),s(!0)}),t.register("shake",D.moduleName,(a,s)=>{this.shake(),s(!0)}),t.register("focus",D.moduleName,(a,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),s(!0)})}),t.register("first_visible_locator",D.moduleName,(a,s)=>{const l=lt(e,!1);this.comms.send("first_visible_locator",l.serialize()),s(!0)}),e.addEventListener("touchstart",this.onTouchStarter,{passive:!0}),e.addEventListener("touchend",this.onTouchEnder,{passive:!0}),e.addEventListener("touchmove",this.onTouchMover,{passive:!0}),e.document.addEventListener("touchstart",()=>{}),t.log("ColumnSnapper Mounted"),!0}unmount(e,t){return this.snappingCancelled=!0,t.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isSnapProtectionEnabled=!1),e.removeEventListener("touchstart",this.onTouchStarter),e.removeEventListener("touchend",this.onTouchEnder),e.removeEventListener("touchmove",this.onTouchMover),e.removeEventListener("orientationchange",this.onWidthChanger),e.removeEventListener("resize",this.onWidthChanger),e.document.getElementById(ei)?.remove(),t.log("ColumnSnapper Unmounted"),super.unmount(e,t)}};D.moduleName="column_snapper";let Nt=D;const ti="readium-scroll-snapper-style",W=class W extends Se{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,n=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"down":"up",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,n=this.wnd.innerHeight,i=Math.max(0,Math.min(1,e/t)),o=Math.max(0,Math.min(1,(e+n)/t));this.comms.send("progress",{start:i,end:o})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Tt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="scrolling");const n=e.document.createElement("style");return n.dataset.readium="true",n.id=ti,n.textContent=`
51
51
  * {
52
52
  scrollbar-width: none; /* for Firefox */
53
53
  }
@@ -55,7 +55,7 @@
55
55
  body::-webkit-scrollbar {
56
56
  display: none; /* for Chrome, Safari, and Opera */
57
57
  }
58
- `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",W.moduleName,()=>{Ut(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,o)=>{const a=i;if(a<0||a>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*a,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_id",W.moduleName,(i,o)=>{const a=e.document.getElementById(i);if(!a){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_text",W.moduleName,(i,o)=>{let a;Array.isArray(i)&&(i.length>1&&(a=i[1]),i=i[0]);const s=oe.deserialize(i),l=Oe(this.wnd.document,new F({href:e.location.href,type:"text/html",text:s,locations:a?new k({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!l){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_start",W.moduleName,(i,o)=>{if(this.doc().scrollTop===0)return o(!1);this.doc().scrollTop=0,this.reportProgress(),o(!0)}),t.register("go_end",W.moduleName,(i,o)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return o(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),o(!0)}),t.register("unfocus",W.moduleName,(i,o)=>{z(this.wnd),o(!0)}),t.register("scroll_protection",W.moduleName,(i,o)=>{this.enableScrollProtection(),o(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,o)=>o(!1)),t.register("focus",W.moduleName,(i,o)=>{this.reportProgress(),o(!0)}),t.register("first_visible_locator",W.moduleName,(i,o)=>{const a=lt(e,!0);this.comms.send("first_visible_locator",a.serialize()),o(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(ti)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};W.moduleName="scroll_snapper";let Nt=W;const B=class B extends be{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,n=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"down":"up",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,n=this.wnd.innerHeight,i=Math.max(0,Math.min(1,e/t)),o=Math.max(0,Math.min(1,(e+n)/t));this.comms.send("progress",{start:i,end:o})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Mt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){return this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",B.moduleName,()=>{Ut(this.wnd);const n=this.doc().scrollTop;n>1?this.doc().scrollTop=n-1:this.doc().scrollTop=n+1,this.doc().scrollTop=n}),t.register("go_progression",B.moduleName,(n,i)=>{const o=n;if(o<0||o>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*o,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_id",B.moduleName,(n,i)=>{const o=e.document.getElementById(n);if(!o){i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=o.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_text",B.moduleName,(n,i)=>{let o;Array.isArray(n)&&(n.length>1&&(o=n[1]),n=n[0]);const a=oe.deserialize(n),s=Oe(this.wnd.document,new F({href:e.location.href,type:"text/html",text:a,locations:o?new k({otherLocations:new Map([["cssSelector",o]])}):void 0}));if(!s){i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_start",B.moduleName,(n,i)=>{if(this.doc().scrollTop===0)return i(!1);this.doc().scrollTop=0,this.reportProgress(),i(!0)}),t.register("go_end",B.moduleName,(n,i)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return i(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),i(!0)}),t.register("unfocus",B.moduleName,(n,i)=>{z(this.wnd),i(!0)}),t.register("scroll_protection",B.moduleName,(n,i)=>{this.enableScrollProtection(),i(!0)}),t.register(["go_next","go_prev"],B.moduleName,(n,i)=>i(!1)),t.register("focus",B.moduleName,(n,i)=>{this.reportProgress(),i(!0)}),t.register("first_visible_locator",B.moduleName,(n,i)=>{const o=lt(e,!0);t.send("first_visible_locator",o.serialize()),i(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(B.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("WebPubSnapper Unmounted"),!0}};B.moduleName="webpub_snapper";let It=B;class Ho{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(n=>e-n.timestamp<1e4),this.copyHistory.length>this.options.historySize&&(this.copyHistory=this.copyHistory.slice(-this.options.historySize))}isSuspiciousPattern(e){return this.copyHistory.length<3?!1:this.copyHistory.filter(i=>e-i.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((i,o)=>i.timestamp-o.timestamp).every((i,o,a)=>o===0?!0:i.length>a[o-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const i=t.toString().length,o=this.window.document.body.innerText.length,a=Date.now();if(this.cleanupOldHistory(a),i<this.options.minThreshold)return this.copyHistory.push({timestamp:a,length:i,wasBlocked:!1}),!0;const l=a-this.lastSelectionTime<100&&i>this.lastSelectionLength*1.5,c=Math.min(o*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(a),u=i>c||l||h;return this.copyHistory.push({timestamp:a,length:i,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=i,this.lastSelectionTime=a,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class Wo{constructor(e=Qn){this.options=e,this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}analyze(e){if(!e)return this.clear(),!1;const t=e.toString();if(t.length===0)return this.clear(),!1;if(e.type!=="Range"||!e.rangeCount)return!1;const n=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=n,this.lastSelectedText=t,!1;if(n-this.selectionStartTime<500)return!1;n-this.lastSelectionTime>1e3&&(this.lastSelectionTime=n),this.selectionStartTime===0&&(this.selectionStartTime=n),this.lastSelectedText=t;const o=this.analyzeSelectionPattern(e,n);return this.cleanup(n),o}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const n=e.getRangeAt(0),i=n.toString(),o=(t-this.selectionStartTime)/1e3;if(i.length/Math.max(1,o)>this.options.maxSelectionsPerSecond)return!0;const s=n.startOffset,l=Math.abs(s-this.lastSelectionPosition);return this.selectionPatterns.push(l),this.selectionPatterns.length>this.options.historySize&&(this.selectionPatterns.shift(),this.calculateVariance(this.selectionPatterns)<this.options.minVariance)?!0:(this.lastSelectionPosition=s,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+Math.pow(i-t,2),0)/e.length}cleanup(e){this.events=this.events.filter(t=>e-t.timestamp<=1e3)}clear(){this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}}class ni{match(e,t){for(const n of t)if(this.matchesCombo(e,n))return!0;return!1}matchesCombo(e,t){return e.keyCode===t.keyCode&&this.matchesModifier(e.ctrlKey,t.ctrl)&&this.matchesModifier(e.shiftKey,t.shift)&&this.matchesModifier(e.altKey,t.alt)&&this.matchesModifier(e.metaKey,t.meta)}matchesModifier(e,t){return t===void 0?!e:e===t}createKeyHandler(e,t){return n=>{this.match(n,e)&&(n.preventDefault(),n.stopPropagation(),t(n))}}createActivityEvent(e,t,n,i){let o,a;if(i){const s=i.getSelection(),l=s?.toString()||"",h=(l&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&l&&(o={text:l,x:h.x,y:h.y,width:h.width,height:h.height});const u=i.document.activeElement;u&&u!==i.document.body&&(a=Tt(u)?.outerHTML)}return{type:t,timestamp:Date.now(),key:e.key,code:e.code,keyCode:e.keyCode,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,targetFrameSrc:n,selectedText:o,interactiveElement:a}}createKeyboardHandlers(e,t,n,i){const o=[];return t.forEach(a=>{o.push(...a.keyCombos.map(s=>({...s,handler:l=>{const c=a.type,h=this.createActivityEvent(l,c,e,i);n(h)}})))}),o}createUnifiedHandler(e,t,n,i){const o=this.createKeyboardHandlers(e,t,n,i);return a=>{for(const s of o)if(this.match(a,[s])){const l=s.suppressOnInteractiveElement;if(l){const c=(i?.document??document).activeElement;if(Array.isArray(l)?l.some(h=>c?.matches(h)):Zn(c))return}a.preventDefault(),a.stopPropagation(),s.handler(a);return}}}}const Ce=class Ce extends fe{constructor(){super(...arguments),this.configApplied=!1,this.cleanupCallbacks=[],this.pointerMoved=!1,this.isContextMenuEnabled=!1,this.isDragAndDropEnabled=!1,this.isSelectionMonitoringEnabled=!1,this.isBulkCopyProtectionEnabled=!1,this.selectionAnalyzer=null,this.currentSelection=null,this.bulkCopyProtector=null,this.keyManager=new ni,this.keyDownHandler=null,this.preventBulkCopy=e=>{if(!this.isBulkCopyProtectionEnabled||!this.bulkCopyProtector)return!0;if(!this.bulkCopyProtector.shouldAllowCopy(e)){e.preventDefault();const t=this.wnd.getSelection(),n=t?.toString()||"",o=(n?t?.getRangeAt(0)?.getClientRects():null)?.[0],a={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:o?{text:n,x:o.x,y:o.y,width:o.width,height:o.height}:void 0,selectionLength:n.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",a),!1}return!0},this.handleSelection=e=>{if(!this.isSelectionMonitoringEnabled||!this.wnd||!this.selectionAnalyzer)return;const t=this.wnd.getSelection();if(t){if(this.currentSelection=t.toString(),this.selectionAnalyzer.analyze(t)&&this.currentSelection){const i=this.wnd.getSelection(),o=i?.toString()||"",s=(o&&i?.rangeCount?i.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:o.length,selectedText:{text:o,x:s?.x??0,y:s?.y??0,width:s?.width??0,height:s?.height??0},eventType:e?.type||"selectionchange",targetFrameSrc:this.wnd.location.href};this.comms?.send("content_protection",l)}}else this.currentSelection=null},this.onDragOver=e=>{this.isDragAndDropEnabled&&(e.preventDefault(),e.stopPropagation())},this.onDragStart=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t={type:"drag_detected",timestamp:Date.now(),dataTransferTypes:e.dataTransfer?.types?[...e.dataTransfer.types]:[],targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",t),!1}else return!0},this.onDrop=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t=e.dataTransfer,n={type:"drop_detected",timestamp:Date.now(),dataTransferTypes:t?.types?[...t.types]:[],fileCount:t?.files?.length||0,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",n),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),n=t?.toString()||"",o=(n&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],a={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...o&&{selectedText:{text:n,x:o.x,y:o.y,width:o.width,height:o.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",a)}},this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onClicker=this.onClick.bind(this)}addContextMenuPrevention(){this.isContextMenuEnabled||!this.wnd||(this.wnd.document.addEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!0)}removeContextMenuPrevention(){!this.isContextMenuEnabled||!this.wnd||(this.wnd.document.removeEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!1)}addDragAndDropPrevention(){this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.addEventListener("dragstart",this.onDragStart),this.wnd.document.addEventListener("dragover",this.onDragOver),this.wnd.document.addEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!0)}removeDragAndDropPrevention(){!this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.removeEventListener("dragstart",this.onDragStart),this.wnd.document.removeEventListener("dragover",this.onDragOver),this.wnd.document.removeEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!1)}enableKeyboardPeripherals(e=[]){this.disableKeyboardPeripherals();const t=n=>{this.comms?.send("keyboard_peripherals",n)};this.keyDownHandler=this.keyManager.createUnifiedHandler(this.wnd.location.href,e,t,this.wnd),this.wnd&&this.wnd.document.addEventListener("keydown",this.keyDownHandler,{capture:!0})}disableKeyboardPeripherals(){this.wnd&&this.keyDownHandler&&(this.wnd.document.removeEventListener("keydown",this.keyDownHandler,{capture:!0}),this.keyDownHandler=null)}addBulkCopyProtection(e={}){if(this.isBulkCopyProtectionEnabled||!this.wnd)return;const t=Io,n=e?{...t,...e}:t;this.bulkCopyProtector=new Ho(this.wnd,n),this.wnd.document.addEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.addEventListener("cut",this.preventBulkCopy,!0),this.isBulkCopyProtectionEnabled=!0}removeBulkCopyProtection(){!this.isBulkCopyProtectionEnabled||!this.wnd||(this.wnd.document.removeEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.removeEventListener("cut",this.preventBulkCopy,!0),this.bulkCopyProtector?.destroy(),this.bulkCopyProtector=null,this.isBulkCopyProtectionEnabled=!1)}addSelectionMonitoring(e){if(this.isSelectionMonitoringEnabled||!this.wnd)return;const t=e||Qn;this.selectionAnalyzer=new Wo(t),this.wnd.document.addEventListener("selectionchange",this.handleSelection),this.isSelectionMonitoringEnabled=!0}removeSelectionMonitoring(){!this.isSelectionMonitoringEnabled||!this.wnd||(this.wnd.document.removeEventListener("selectionchange",this.handleSelection),this.selectionAnalyzer?.clear(),this.selectionAnalyzer=null,this.isSelectionMonitoringEnabled=!1)}onPointUp(e){const t=this.wnd.getSelection();if(t&&t.toString()?.length>0){const i=t.getRangeAt(0)?.getClientRects();if(!i||i.length===0)return;const o=i[0],a={text:t.toString(),x:o.x,y:o.y,width:o.width,height:o.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",a)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const n=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*n,y:e.clientY*n,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Tt(e.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(e.target)}),this.pointerMoved=!1}onPointMove(e){if(e.movementY!==void 0&&e.movementX!==void 0){(Math.abs(e.movementX)>1||Math.abs(e.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onClick(e){if(e.preventDefault(),!e.isTrusted){const t=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:e.clientX,clientY:e.clientY});Object.defineProperty(t,"target",{writable:!1,value:e.target}),Object.defineProperty(t,"defaultPrevented",{writable:!1,value:e.defaultPrevented}),this.onPointUp(t)}}registerProtectionHandlers(){this.comms?.register("peripherals_protection",Ce.moduleName,(e,t)=>{const n=e;if(!this.configApplied){if(this.configApplied=!0,n.monitorSelection){const i=typeof n.monitorSelection=="boolean"?void 0:n.monitorSelection;this.addSelectionMonitoring(i),this.comms?.log("Selection monitoring enabled")}typeof n.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...n.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):n.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),n.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),n.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",Ce.moduleName,(e,t)=>{const n=e;n&&n.length>0&&(this.enableKeyboardPeripherals(n),this.comms?.log(`Keyboard peripherals enabled: ${n.map(i=>i.type).join(", ")}`)),t(!0)})}mount(e,t){return this.wnd=e,this.comms=t,this.registerProtectionHandlers(),e.document.addEventListener("pointerdown",this.onPointerDown),e.document.addEventListener("pointerup",this.onPointerUp),e.document.addEventListener("pointermove",this.onPointerMove),e.document.addEventListener("click",this.onClicker),t.log("Peripherals Mounted"),!0}unmount(e,t){return this.removeBulkCopyProtection(),this.removeSelectionMonitoring(),this.removeContextMenuPrevention(),this.removeDragAndDropPrevention(),this.disableKeyboardPeripherals(),this.cleanupCallbacks.forEach(n=>n()),this.cleanupCallbacks=[],e.document.removeEventListener("pointerdown",this.onPointerDown),e.document.removeEventListener("pointerup",this.onPointerUp),e.document.removeEventListener("pointermove",this.onPointerMove),e.document.removeEventListener("click",this.onClicker),t.unregisterAll(Ce.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};Ce.moduleName="peripherals";let Dt=Ce;const Ze=class Ze extends fe{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}unblock(e){for(e._readium_blockEvents=!1;e._readium_blockedEvents?.length>0;){const t=e._readium_blockedEvents.shift();switch(t[0]){case 0:Reflect.apply(t[1],t[2],t[3]);break;case 1:const n=t[1],i=t[2];e.removeEventListener(n.type,e._readium_eventBlocker,!0);const o=new Event(n.type,{bubbles:n.bubbles,cancelable:n.cancelable});i?i.dispatchEvent(o):e.dispatchEvent(o);break}}}onMediaPlayEvent(){this.mediaPlayingCount++,this.comms?.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){this.mediaPlayingCount>0&&this.mediaPlayingCount--,this.comms?.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(e){const t=e.document.querySelectorAll("audio,video");for(let n=0;n<t.length;n++)t[n].pause()}mount(e,t){this.comms=t,e.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(e.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.5.2-beta.5",hasFeature:(i,o="")=>{switch(i){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in e.document&&e.document.getAnimations().forEach(i=>{i.cancel(),this.allAnimations.add(i)}),t.register("activate",Ze.moduleName,(i,o)=>{this.allAnimations.forEach(a=>{a.cancel(),a.play()}),o(!0)}),t.register("unfocus",Ze.moduleName,(i,o)=>{this.pauseAllMedia(e),this.allAnimations.forEach(a=>a.pause()),o(!0)});const n=e.document.querySelectorAll("audio,video");for(let i=0;i<n.length;i++){const o=n[i];o.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),o.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return t.log("Setup Mounted"),!0}unmount(e,t){return e.removeEventListener("error",this.wndOnErr),e.removeEventListener("play",this.onMediaPlayEvent),e.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(n=>n.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};Ze.moduleName="setup";let ht=Ze;const ii="readium-viewport",ne=class ne extends ht{onViewportWidthChanged(e){const t=e.target;Ae(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const n=e.document.createElement("meta");return n.dataset.readium="true",n.setAttribute("name","viewport"),n.setAttribute("id",ii),n.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(n),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",ne.moduleName,(i,o)=>{Et(e),o(!0)}),t.register("update_properties",ne.moduleName,(i,o)=>{i["--RS__viewportWidth"]=`${e.innerWidth}px`,Bn(e,i),o(!0)}),t.register("set_property",ne.moduleName,(i,o)=>{const a=i;Ae(e,a[0],a[1]),o(!0)}),t.register("remove_property",ne.moduleName,(i,o)=>{rt(e,i),o(!0)}),t.register("activate",ne.moduleName,(i,o)=>{this.unblock(e),o(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ne.moduleName),e.document.head.querySelector(`#${ii}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};ne.moduleName="reflowable_setup";let Ht=ne;const oi="readium-fixed-style",J=class J extends ht{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const n=e.document.createElement("style");return n.id=oi,n.dataset.readium="true",n.textContent=`
58
+ `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",W.moduleName,()=>{At(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,o)=>{const a=i;if(a<0||a>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*a,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_id",W.moduleName,(i,o)=>{const a=e.document.getElementById(i);if(!a){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_text",W.moduleName,(i,o)=>{let a;Array.isArray(i)&&(i.length>1&&(a=i[1]),i=i[0]);const s=oe.deserialize(i),l=Le(this.wnd.document,new N({href:e.location.href,type:"text/html",text:s,locations:a?new C({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!l){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_start",W.moduleName,(i,o)=>{if(this.doc().scrollTop===0)return o(!1);this.doc().scrollTop=0,this.reportProgress(),o(!0)}),t.register("go_end",W.moduleName,(i,o)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return o(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),o(!0)}),t.register("unfocus",W.moduleName,(i,o)=>{z(this.wnd),o(!0)}),t.register("scroll_protection",W.moduleName,(i,o)=>{this.enableScrollProtection(),o(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,o)=>o(!1)),t.register("focus",W.moduleName,(i,o)=>{this.reportProgress(),o(!0)}),t.register("first_visible_locator",W.moduleName,(i,o)=>{const a=lt(e,!0);this.comms.send("first_visible_locator",a.serialize()),o(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(ti)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};W.moduleName="scroll_snapper";let Mt=W;const B=class B extends Se{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce=null,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollTop=this.doc().scrollTop,this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=this.doc().scrollTop,n=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"down":"up",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}reportProgress(){if(!this.comms.ready)return;const e=Math.ceil(this.doc().scrollTop),t=this.doc().scrollHeight,n=this.wnd.innerHeight,i=Math.max(0,Math.min(1,e/t)),o=Math.max(0,Math.min(1,(e+n)/t));this.comms.send("progress",{start:i,end:o})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Tt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){return this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollTop=0,this.isResizing=!1,this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",B.moduleName,()=>{At(this.wnd);const n=this.doc().scrollTop;n>1?this.doc().scrollTop=n-1:this.doc().scrollTop=n+1,this.doc().scrollTop=n}),t.register("go_progression",B.moduleName,(n,i)=>{const o=n;if(o<0||o>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*o,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_id",B.moduleName,(n,i)=>{const o=e.document.getElementById(n);if(!o){i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=o.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_text",B.moduleName,(n,i)=>{let o;Array.isArray(n)&&(n.length>1&&(o=n[1]),n=n[0]);const a=oe.deserialize(n),s=Le(this.wnd.document,new N({href:e.location.href,type:"text/html",text:a,locations:o?new C({otherLocations:new Map([["cssSelector",o]])}):void 0}));if(!s){i(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),z(this.wnd),i(!0)})}),t.register("go_start",B.moduleName,(n,i)=>{if(this.doc().scrollTop===0)return i(!1);this.doc().scrollTop=0,this.reportProgress(),i(!0)}),t.register("go_end",B.moduleName,(n,i)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return i(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),i(!0)}),t.register("unfocus",B.moduleName,(n,i)=>{z(this.wnd),i(!0)}),t.register("scroll_protection",B.moduleName,(n,i)=>{this.enableScrollProtection(),i(!0)}),t.register(["go_next","go_prev"],B.moduleName,(n,i)=>i(!1)),t.register("focus",B.moduleName,(n,i)=>{this.reportProgress(),i(!0)}),t.register("first_visible_locator",B.moduleName,(n,i)=>{const o=lt(e,!0);t.send("first_visible_locator",o.serialize()),i(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(B.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("WebPubSnapper Unmounted"),!0}};B.moduleName="webpub_snapper";let It=B;class Do{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(n=>e-n.timestamp<1e4),this.copyHistory.length>this.options.historySize&&(this.copyHistory=this.copyHistory.slice(-this.options.historySize))}isSuspiciousPattern(e){return this.copyHistory.length<3?!1:this.copyHistory.filter(i=>e-i.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((i,o)=>i.timestamp-o.timestamp).every((i,o,a)=>o===0?!0:i.length>a[o-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const i=t.toString().length,o=this.window.document.body.innerText.length,a=Date.now();if(this.cleanupOldHistory(a),i<this.options.minThreshold)return this.copyHistory.push({timestamp:a,length:i,wasBlocked:!1}),!0;const l=a-this.lastSelectionTime<100&&i>this.lastSelectionLength*1.5,c=Math.min(o*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(a),u=i>c||l||h;return this.copyHistory.push({timestamp:a,length:i,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=i,this.lastSelectionTime=a,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class Wo{constructor(e=Qn){this.options=e,this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}analyze(e){if(!e)return this.clear(),!1;const t=e.toString();if(t.length===0)return this.clear(),!1;if(e.type!=="Range"||!e.rangeCount)return!1;const n=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=n,this.lastSelectedText=t,!1;if(n-this.selectionStartTime<500)return!1;n-this.lastSelectionTime>1e3&&(this.lastSelectionTime=n),this.selectionStartTime===0&&(this.selectionStartTime=n),this.lastSelectedText=t;const o=this.analyzeSelectionPattern(e,n);return this.cleanup(n),o}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const n=e.getRangeAt(0),i=n.toString(),o=(t-this.selectionStartTime)/1e3;if(i.length/Math.max(1,o)>this.options.maxSelectionsPerSecond)return!0;const s=n.startOffset,l=Math.abs(s-this.lastSelectionPosition);return this.selectionPatterns.push(l),this.selectionPatterns.length>this.options.historySize&&(this.selectionPatterns.shift(),this.calculateVariance(this.selectionPatterns)<this.options.minVariance)?!0:(this.lastSelectionPosition=s,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+Math.pow(i-t,2),0)/e.length}cleanup(e){this.events=this.events.filter(t=>e-t.timestamp<=1e3)}clear(){this.events=[],this.selectionStartTime=0,this.lastSelectionTime=0,this.lastSelectionPosition=0,this.selectionPatterns=[],this.lastSelectedText=""}}class ni{match(e,t){for(const n of t)if(this.matchesCombo(e,n))return!0;return!1}matchesCombo(e,t){return e.keyCode===t.keyCode&&this.matchesModifier(e.ctrlKey,t.ctrl)&&this.matchesModifier(e.shiftKey,t.shift)&&this.matchesModifier(e.altKey,t.alt)&&this.matchesModifier(e.metaKey,t.meta)}matchesModifier(e,t){return t===void 0?!e:e===t}createKeyHandler(e,t){return n=>{this.match(n,e)&&(n.preventDefault(),n.stopPropagation(),t(n))}}createActivityEvent(e,t,n,i){let o,a;if(i){const s=i.getSelection(),l=s?.toString()||"",h=(l&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&l&&(o={text:l,x:h.x,y:h.y,width:h.width,height:h.height});const u=i.document.activeElement;u&&u!==i.document.body&&(a=Ut(u)?.outerHTML)}return{type:t,timestamp:Date.now(),key:e.key,code:e.code,keyCode:e.keyCode,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,targetFrameSrc:n,selectedText:o,interactiveElement:a}}createKeyboardHandlers(e,t,n,i){const o=[];return t.forEach(a=>{o.push(...a.keyCombos.map(s=>({...s,handler:l=>{const c=a.type,h=this.createActivityEvent(l,c,e,i);n(h)}})))}),o}createUnifiedHandler(e,t,n,i){const o=this.createKeyboardHandlers(e,t,n,i);return a=>{for(const s of o)if(this.match(a,[s])){const l=s.suppressOnInteractiveElement;if(l){const c=(i?.document??document).activeElement;if(Array.isArray(l)?l.some(h=>c?.matches(h)):Jn(c))return}a.preventDefault(),a.stopPropagation(),s.handler(a);return}}}}const Ee=class Ee extends fe{constructor(){super(...arguments),this.configApplied=!1,this.cleanupCallbacks=[],this.pointerMoved=!1,this.isContextMenuEnabled=!1,this.isDragAndDropEnabled=!1,this.isSelectionMonitoringEnabled=!1,this.isBulkCopyProtectionEnabled=!1,this.selectionAnalyzer=null,this.currentSelection=null,this.bulkCopyProtector=null,this.keyManager=new ni,this.keyDownHandler=null,this.preventBulkCopy=e=>{if(!this.isBulkCopyProtectionEnabled||!this.bulkCopyProtector)return!0;if(!this.bulkCopyProtector.shouldAllowCopy(e)){e.preventDefault();const t=this.wnd.getSelection(),n=t?.toString()||"",o=(n?t?.getRangeAt(0)?.getClientRects():null)?.[0],a={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:o?{text:n,x:o.x,y:o.y,width:o.width,height:o.height}:void 0,selectionLength:n.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",a),!1}return!0},this.handleSelection=e=>{if(!this.isSelectionMonitoringEnabled||!this.wnd||!this.selectionAnalyzer)return;const t=this.wnd.getSelection();if(t){if(this.currentSelection=t.toString(),this.selectionAnalyzer.analyze(t)&&this.currentSelection){const i=this.wnd.getSelection(),o=i?.toString()||"",s=(o&&i?.rangeCount?i.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:o.length,selectedText:{text:o,x:s?.x??0,y:s?.y??0,width:s?.width??0,height:s?.height??0},eventType:e?.type||"selectionchange",targetFrameSrc:this.wnd.location.href};this.comms?.send("content_protection",l)}}else this.currentSelection=null},this.onDragOver=e=>{this.isDragAndDropEnabled&&(e.preventDefault(),e.stopPropagation())},this.onDragStart=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t={type:"drag_detected",timestamp:Date.now(),dataTransferTypes:e.dataTransfer?.types?[...e.dataTransfer.types]:[],targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",t),!1}else return!0},this.onDrop=e=>{if(this.isDragAndDropEnabled){e.preventDefault();const t=e.dataTransfer,n={type:"drop_detected",timestamp:Date.now(),dataTransferTypes:t?.types?[...t.types]:[],fileCount:t?.files?.length||0,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",n),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),n=t?.toString()||"",o=(n&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],a={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...o&&{selectedText:{text:n,x:o.x,y:o.y,width:o.width,height:o.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",a)}},this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onClicker=this.onClick.bind(this)}addContextMenuPrevention(){this.isContextMenuEnabled||!this.wnd||(this.wnd.document.addEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!0)}removeContextMenuPrevention(){!this.isContextMenuEnabled||!this.wnd||(this.wnd.document.removeEventListener("contextmenu",this.onContext),this.isContextMenuEnabled=!1)}addDragAndDropPrevention(){this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.addEventListener("dragstart",this.onDragStart),this.wnd.document.addEventListener("dragover",this.onDragOver),this.wnd.document.addEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!0)}removeDragAndDropPrevention(){!this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.removeEventListener("dragstart",this.onDragStart),this.wnd.document.removeEventListener("dragover",this.onDragOver),this.wnd.document.removeEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!1)}enableKeyboardPeripherals(e=[]){this.disableKeyboardPeripherals();const t=n=>{this.comms?.send("keyboard_peripherals",n)};this.keyDownHandler=this.keyManager.createUnifiedHandler(this.wnd.location.href,e,t,this.wnd),this.wnd&&this.wnd.document.addEventListener("keydown",this.keyDownHandler,{capture:!0})}disableKeyboardPeripherals(){this.wnd&&this.keyDownHandler&&(this.wnd.document.removeEventListener("keydown",this.keyDownHandler,{capture:!0}),this.keyDownHandler=null)}addBulkCopyProtection(e={}){if(this.isBulkCopyProtectionEnabled||!this.wnd)return;const t=Io,n=e?{...t,...e}:t;this.bulkCopyProtector=new Do(this.wnd,n),this.wnd.document.addEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.addEventListener("cut",this.preventBulkCopy,!0),this.isBulkCopyProtectionEnabled=!0}removeBulkCopyProtection(){!this.isBulkCopyProtectionEnabled||!this.wnd||(this.wnd.document.removeEventListener("copy",this.preventBulkCopy,!0),this.wnd.document.removeEventListener("cut",this.preventBulkCopy,!0),this.bulkCopyProtector?.destroy(),this.bulkCopyProtector=null,this.isBulkCopyProtectionEnabled=!1)}addSelectionMonitoring(e){if(this.isSelectionMonitoringEnabled||!this.wnd)return;const t=e||Qn;this.selectionAnalyzer=new Wo(t),this.wnd.document.addEventListener("selectionchange",this.handleSelection),this.isSelectionMonitoringEnabled=!0}removeSelectionMonitoring(){!this.isSelectionMonitoringEnabled||!this.wnd||(this.wnd.document.removeEventListener("selectionchange",this.handleSelection),this.selectionAnalyzer?.clear(),this.selectionAnalyzer=null,this.isSelectionMonitoringEnabled=!1)}onPointUp(e){const t=this.wnd.getSelection();if(t&&t.toString()?.length>0){const i=t.getRangeAt(0)?.getClientRects();if(!i||i.length===0)return;const o=i[0],a={text:t.toString(),x:o.x,y:o.y,width:o.width,height:o.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",a)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const n=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*n,y:e.clientY*n,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Ut(e.target)?.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(e.target)}),this.pointerMoved=!1}onPointMove(e){if(e.movementY!==void 0&&e.movementX!==void 0){(Math.abs(e.movementX)>1||Math.abs(e.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onClick(e){if(e.preventDefault(),!e.isTrusted){const t=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:e.clientX,clientY:e.clientY});Object.defineProperty(t,"target",{writable:!1,value:e.target}),Object.defineProperty(t,"defaultPrevented",{writable:!1,value:e.defaultPrevented}),this.onPointUp(t)}}registerProtectionHandlers(){this.comms?.register("peripherals_protection",Ee.moduleName,(e,t)=>{const n=e;if(!this.configApplied){if(this.configApplied=!0,n.monitorSelection){const i=typeof n.monitorSelection=="boolean"?void 0:n.monitorSelection;this.addSelectionMonitoring(i),this.comms?.log("Selection monitoring enabled")}typeof n.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...n.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):n.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),n.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),n.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",Ee.moduleName,(e,t)=>{const n=e;n&&n.length>0&&(this.enableKeyboardPeripherals(n),this.comms?.log(`Keyboard peripherals enabled: ${n.map(i=>i.type).join(", ")}`)),t(!0)})}mount(e,t){return this.wnd=e,this.comms=t,this.registerProtectionHandlers(),e.document.addEventListener("pointerdown",this.onPointerDown),e.document.addEventListener("pointerup",this.onPointerUp),e.document.addEventListener("pointermove",this.onPointerMove),e.document.addEventListener("click",this.onClicker),t.log("Peripherals Mounted"),!0}unmount(e,t){return this.removeBulkCopyProtection(),this.removeSelectionMonitoring(),this.removeContextMenuPrevention(),this.removeDragAndDropPrevention(),this.disableKeyboardPeripherals(),this.cleanupCallbacks.forEach(n=>n()),this.cleanupCallbacks=[],e.document.removeEventListener("pointerdown",this.onPointerDown),e.document.removeEventListener("pointerup",this.onPointerUp),e.document.removeEventListener("pointermove",this.onPointerMove),e.document.removeEventListener("click",this.onClicker),t.unregisterAll(Ee.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};Ee.moduleName="peripherals";let Ht=Ee;const Je=class Je extends fe{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}unblock(e){for(e._readium_blockEvents=!1;e._readium_blockedEvents?.length>0;){const t=e._readium_blockedEvents.shift();switch(t[0]){case 0:Reflect.apply(t[1],t[2],t[3]);break;case 1:const n=t[1],i=t[2];e.removeEventListener(n.type,e._readium_eventBlocker,!0);const o=new Event(n.type,{bubbles:n.bubbles,cancelable:n.cancelable});i?i.dispatchEvent(o):e.dispatchEvent(o);break}}}onMediaPlayEvent(){this.mediaPlayingCount++,this.comms?.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){this.mediaPlayingCount>0&&this.mediaPlayingCount--,this.comms?.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(e){const t=e.document.querySelectorAll("audio,video");for(let n=0;n<t.length;n++)t[n].pause()}mount(e,t){this.comms=t,e.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(e.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.5.3",hasFeature:(i,o="")=>{switch(i){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in e.document&&e.document.getAnimations().forEach(i=>{i.cancel(),this.allAnimations.add(i)}),t.register("activate",Je.moduleName,(i,o)=>{this.allAnimations.forEach(a=>{a.cancel(),a.play()}),o(!0)}),t.register("unfocus",Je.moduleName,(i,o)=>{this.pauseAllMedia(e),this.allAnimations.forEach(a=>a.pause()),o(!0)});const n=e.document.querySelectorAll("audio,video");for(let i=0;i<n.length;i++){const o=n[i];o.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),o.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return t.log("Setup Mounted"),!0}unmount(e,t){return e.removeEventListener("error",this.wndOnErr),e.removeEventListener("play",this.onMediaPlayEvent),e.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(n=>n.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};Je.moduleName="setup";let ht=Je;const ii="readium-viewport",ne=class ne extends ht{onViewportWidthChanged(e){const t=e.target;Oe(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const n=e.document.createElement("meta");return n.dataset.readium="true",n.setAttribute("name","viewport"),n.setAttribute("id",ii),n.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(n),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",ne.moduleName,(i,o)=>{kt(e),o(!0)}),t.register("update_properties",ne.moduleName,(i,o)=>{i["--RS__viewportWidth"]=`${e.innerWidth}px`,Bn(e,i),o(!0)}),t.register("set_property",ne.moduleName,(i,o)=>{const a=i;Oe(e,a[0],a[1]),o(!0)}),t.register("remove_property",ne.moduleName,(i,o)=>{rt(e,i),o(!0)}),t.register("activate",ne.moduleName,(i,o)=>{this.unblock(e),o(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ne.moduleName),e.document.head.querySelector(`#${ii}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};ne.moduleName="reflowable_setup";let Dt=ne;const oi="readium-fixed-style",Z=class Z extends ht{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const n=e.document.createElement("style");return n.id=oi,n.dataset.readium="true",n.textContent=`
59
59
  html, body {
60
60
  text-size-adjust: none;
61
61
  -ms-text-size-adjust: none;
@@ -67,7 +67,7 @@
67
67
  min-height: 100%;
68
68
 
69
69
  /*cursor: var() TODO*/
70
- }`,e.document.head.appendChild(n),t.register("set_property",J.moduleName,(i,o)=>{const a=i;Ae(e,a[0],a[1]),o(!0)}),t.register("remove_property",J.moduleName,(i,o)=>{rt(e,i),o(!0)}),t.register("first_visible_locator",J.moduleName,(i,o)=>o(!1)),t.register("unfocus",J.moduleName,(i,o)=>{z(e),o(!0)}),t.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],J.moduleName,(i,o)=>o(!0)),t.register("activate",J.moduleName,(i,o)=>{this.unblock(e),o(!0)}),t.log("FixedSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(J.moduleName),e.document.getElementById(oi)?.remove(),t.log("FixedSetup Unmounted"),super.unmount(e,t)}};J.moduleName="fixed_setup";let Wt=J;const ie=class ie extends fe{wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}mount(e,t){return this.comms=t,e.addEventListener("error",this.wndOnErr,!1),t.register("get_properties",ie.moduleName,(n,i)=>{Et(e),i(!0)}),t.register("update_properties",ie.moduleName,(n,i)=>{Bn(e,n),i(!0)}),t.register("set_property",ie.moduleName,(n,i)=>{const o=n;Ae(e,o[0],o[1]),i(!0)}),t.register("remove_property",ie.moduleName,(n,i)=>{rt(e,n),i(!0)}),t.register("activate",ie.moduleName,(n,i)=>{i(!0)}),t.log("WebPubSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ie.moduleName),e.removeEventListener("error",this.wndOnErr),t.log("WebPubSetup Unmounted"),!0}};ie.moduleName="webpub_setup";let Bt=ie,Bo=(ae=class extends fe{constructor(){super(...arguments),this.styleElement=null,this.beforePrintHandler=null,this.configApplied=!1}setupPrintProtection(e,t){if(!t.disable)return;const n=e.document.createElement("style");n.textContent=`
70
+ }`,e.document.head.appendChild(n),t.register("set_property",Z.moduleName,(i,o)=>{const a=i;Oe(e,a[0],a[1]),o(!0)}),t.register("remove_property",Z.moduleName,(i,o)=>{rt(e,i),o(!0)}),t.register("first_visible_locator",Z.moduleName,(i,o)=>o(!1)),t.register("unfocus",Z.moduleName,(i,o)=>{z(e),o(!0)}),t.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],Z.moduleName,(i,o)=>o(!0)),t.register("activate",Z.moduleName,(i,o)=>{this.unblock(e),o(!0)}),t.log("FixedSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(Z.moduleName),e.document.getElementById(oi)?.remove(),t.log("FixedSetup Unmounted"),super.unmount(e,t)}};Z.moduleName="fixed_setup";let Wt=Z;const ie=class ie extends fe{wndOnErr(e){this.comms?.send("error",{message:e.message,filename:e.filename,lineno:e.lineno,colno:e.colno})}mount(e,t){return this.comms=t,e.addEventListener("error",this.wndOnErr,!1),t.register("get_properties",ie.moduleName,(n,i)=>{kt(e),i(!0)}),t.register("update_properties",ie.moduleName,(n,i)=>{Bn(e,n),i(!0)}),t.register("set_property",ie.moduleName,(n,i)=>{const o=n;Oe(e,o[0],o[1]),i(!0)}),t.register("remove_property",ie.moduleName,(n,i)=>{rt(e,n),i(!0)}),t.register("activate",ie.moduleName,(n,i)=>{i(!0)}),t.log("WebPubSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ie.moduleName),e.removeEventListener("error",this.wndOnErr),t.log("WebPubSetup Unmounted"),!0}};ie.moduleName="webpub_setup";let Bt=ie,Bo=(ae=class extends fe{constructor(){super(...arguments),this.styleElement=null,this.beforePrintHandler=null,this.configApplied=!1}setupPrintProtection(e,t){if(!t.disable)return;const n=e.document.createElement("style");n.textContent=`
71
71
  @media print {
72
72
  body * {
73
73
  display: none !important;
@@ -81,7 +81,7 @@
81
81
  transform: translateY(-50%);
82
82
  }
83
83
  }
84
- `,e.document.head.appendChild(n),this.styleElement=n,this.beforePrintHandler=i=>(i.preventDefault(),!1),e.addEventListener("beforeprint",this.beforePrintHandler)}registerPrintHandlers(){this.comms?.register("print_protection",ae.moduleName,e=>{const t=e;return this.configApplied||(this.configApplied=!0,this.setupPrintProtection(this.wnd,t),this.comms?.log("Print protection configuration applied")),!0})}mount(e,t){return this.wnd=e,this.comms=t,this.registerPrintHandlers(),!0}unmount(e,t){return this.beforePrintHandler&&(e.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null),this.comms?.unregisterAll(ae.moduleName),this.configApplied=!1,!0}},ae.moduleName="print_protection",ae);const ri="readium-cjk-vertical-snapper-style",j=class j extends be{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollLeft=0,this.isResizing=!1,this.resizeDebounce=null,this.verticalLR=!1,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollLeft=Math.abs(this.doc().scrollLeft),this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=Math.abs(this.doc().scrollLeft),n=t-this.lastScrollLeft;if(this.lastScrollLeft=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"left":"right",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}scrollable(){return Math.max(0,this.doc().scrollWidth-this.wnd.innerWidth)}reportProgress(){if(!this.comms.ready)return;const e=this.doc().scrollWidth,t=this.wnd.innerWidth,n=Math.max(1,e-t),i=Math.abs(this.doc().scrollLeft),o=Math.max(0,Math.min(1,i/n)),a=Math.max(0,Math.min(1,(i+t)/e));this.comms.send("progress",{start:o,end:a})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Mt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollLeft=0,this.isResizing=!1,this.verticalLR=Lo(e),this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="scrolling");const n=e.document.createElement("style");return n.dataset.readium="true",n.id=ri,n.textContent=`
84
+ `,e.document.head.appendChild(n),this.styleElement=n,this.beforePrintHandler=i=>(i.preventDefault(),!1),e.addEventListener("beforeprint",this.beforePrintHandler)}registerPrintHandlers(){this.comms?.register("print_protection",ae.moduleName,e=>{const t=e;return this.configApplied||(this.configApplied=!0,this.setupPrintProtection(this.wnd,t),this.comms?.log("Print protection configuration applied")),!0})}mount(e,t){return this.wnd=e,this.comms=t,this.registerPrintHandlers(),!0}unmount(e,t){return this.beforePrintHandler&&(e.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null),this.comms?.unregisterAll(ae.moduleName),this.configApplied=!1,!0}},ae.moduleName="print_protection",ae);const ri="readium-cjk-vertical-snapper-style",j=class j extends Se{constructor(){super(...arguments),this.patternAnalyzer=null,this.lastScrollTime=0,this.isScrollProtectionEnabled=!1,this.initialScrollHandled=!1,this.isScrolling=!1,this.lastScrollLeft=0,this.isResizing=!1,this.resizeDebounce=null,this.verticalLR=!1,this.handleScroll=e=>{if(this.comms.ready&&!this.isResizing){if(!this.initialScrollHandled){this.lastScrollLeft=Math.abs(this.doc().scrollLeft),this.initialScrollHandled=!0,this.reportProgress();return}this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress();const t=Math.abs(this.doc().scrollLeft),n=t-this.lastScrollLeft;if(this.lastScrollLeft=t,this.isScrollProtectionEnabled&&Math.abs(n)>5){const i=Date.now(),o=i-(this.lastScrollTime||i);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(n>0?"down":"up",Math.abs(n),o)){const s=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:n,scrollDirection:n>0?"left":"right",targetElement:s})}this.lastScrollTime=i}this.comms.send("scroll",n),this.isScrolling=!1}))}}}doc(){return this.wnd.document.scrollingElement}scrollable(){return Math.max(0,this.doc().scrollWidth-this.wnd.innerWidth)}reportProgress(){if(!this.comms.ready)return;const e=this.doc().scrollWidth,t=this.wnd.innerWidth,n=Math.max(1,e-t),i=Math.abs(this.doc().scrollLeft),o=Math.max(0,Math.min(1,i/n)),a=Math.max(0,Math.min(1,(i+t)/e));this.comms.send("progress",{start:o,end:a})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new ct(Tt),this.isScrollProtectionEnabled=!0,this.comms?.log("Scroll protection enabled"))}mount(e,t){this.wnd=e,this.comms=t,this.initialScrollHandled=!1,this.lastScrollLeft=0,this.isResizing=!1,this.verticalLR=Fo(e),this.resizeDebounce&&(this.wnd.clearTimeout(this.resizeDebounce),this.resizeDebounce=null),e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="scrolling");const n=e.document.createElement("style");return n.dataset.readium="true",n.id=ri,n.textContent=`
85
85
  * {
86
86
  scrollbar-width: none;
87
87
  }
@@ -92,9 +92,9 @@
92
92
  overflow-x: auto !important;
93
93
  overflow-y: hidden !important;
94
94
  }
95
- `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",j.moduleName,()=>{Ut(this.wnd);const i=this.doc().scrollLeft;this.verticalLR?this.doc().scrollLeft=i>1?i-1:i+1:this.doc().scrollLeft=i<-1?i+1:i-1,this.doc().scrollLeft=i}),t.register("go_progression",j.moduleName,(i,o)=>{const a=i;if(a<0||a>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),o(!1);return}this.wnd.requestAnimationFrame(()=>{const s=this.scrollable()*a;this.doc().scrollLeft=this.verticalLR?s:-s,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_id",j.moduleName,(i,o)=>{const a=e.document.getElementById(i);if(!a){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft+=a.getBoundingClientRect().left-e.innerWidth/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_text",j.moduleName,(i,o)=>{let a;Array.isArray(i)&&(i.length>1&&(a=i[1]),i=i[0]);const s=oe.deserialize(i),l=Oe(this.wnd.document,new F({href:e.location.href,type:"text/html",text:s,locations:a?new k({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!l){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft+=l.getBoundingClientRect().left-e.innerWidth/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_start",j.moduleName,(i,o)=>{if(this.doc().scrollLeft===0)return o(!1);this.doc().scrollLeft=0,this.reportProgress(),o(!0)}),t.register("go_end",j.moduleName,(i,o)=>{if(Math.abs(this.doc().scrollLeft)===this.scrollable())return o(!1);this.doc().scrollLeft=this.verticalLR?this.scrollable():-this.scrollable(),this.reportProgress(),o(!0)}),t.register(["go_next","go_prev"],j.moduleName,(i,o)=>o(!1)),t.register("unfocus",j.moduleName,(i,o)=>{z(this.wnd),o(!0)}),t.register("scroll_protection",j.moduleName,(i,o)=>{this.enableScrollProtection(),o(!0)}),t.register("focus",j.moduleName,(i,o)=>{this.reportProgress(),o(!0)}),t.register("first_visible_locator",j.moduleName,(i,o)=>{const a=lt(e,!0);this.comms.send("first_visible_locator",a.serialize()),o(!0)}),t.log("CJKVerticalSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(j.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(ri)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("CJKVerticalSnapper Unmounted"),!0}};j.moduleName="cjk_vertical_snapper";let jt=j;const jo=["fixed_setup","decorator","peripherals","print_protection"],Go=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper","cjk_vertical_snapper","print_protection"],Vo=["webpub_setup","webpub_snapper","decorator","peripherals","print_protection"],Gt=new Map([Wt,Ht,Bt,It,Dt,At,Ft,Nt,jt,Bo].map(r=>[r.moduleName,r]));class _e{constructor(e=window,t=[]){this.loadedModules=[],this.wnd=e,this.comms=new uo(e);const n=[...new Set(t)];if(n.length){if(typeof e>"u")throw Error("Loader is not in a web browser");e.parent!==e&&this.comms.log("Loader is probably in a frame"),this.loadedModules=n.map(i=>{const o=this.loadModule(i);if(o)return o.mount(this.wnd,this.comms),o}).filter(i=>i!==void 0)}}loadModule(e){const t=Gt.get(e);return t===void 0?(this.comms.log(`Module "${name}" does not exist in the library`),t):new t}addModule(e){const t=this.loadModule(e);return!t||!t.mount(this.wnd,this.comms)?!1:(this.loadedModules.push(t),!0)}removeModule(e){const t=Gt.get(e);if(t===void 0)return this.comms.log(`Module "${e}" does not exist in the library`),!1;const n=this.loadedModules.findIndex(i=>i instanceof t);return n<0?!1:(this.loadedModules[n].unmount(this.wnd,this.comms),this.loadedModules.splice(n,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(e=>e.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const $o={type:"developer_tools",keyCombos:[{keyCode:73,meta:!0,alt:!0},{keyCode:73,ctrl:!0,shift:!0},{keyCode:74,meta:!0,alt:!0},{keyCode:74,ctrl:!0,shift:!0},{keyCode:85,meta:!0,alt:!0},{keyCode:67,meta:!0,alt:!0},{keyCode:67,meta:!0,shift:!0},{keyCode:67,ctrl:!0,shift:!0},{keyCode:65,meta:!0,alt:!0},{keyCode:84,meta:!0,shift:!0,alt:!0},{keyCode:67,shift:!0,alt:!0},{keyCode:123},{keyCode:123,shift:!0},{keyCode:123,ctrl:!0,shift:!0},{keyCode:123,meta:!0,alt:!0}]},Xo={type:"select_all",keyCombos:[{keyCode:65,meta:!0},{keyCode:65,ctrl:!0}]},Yo={type:"print",keyCombos:[{keyCode:80,meta:!0},{keyCode:80,ctrl:!0},{keyCode:80,meta:!0,shift:!0},{keyCode:80,ctrl:!0,shift:!0},{keyCode:80,meta:!0,alt:!0},{keyCode:80,ctrl:!0,alt:!0}]},qo={type:"save",keyCombos:[{keyCode:83,meta:!0},{keyCode:83,ctrl:!0}]};class Vt{mergeKeyboardPeripherals(e,t=[]){const n=[],i=t.filter(o=>!["developer_tools","select_all","print","save"].includes(o.type));e.disableSelectAll&&n.push(Xo),e.disableSave&&n.push(qo),e.monitorDevTools&&n.push($o),e.protectPrinting?.disable&&n.push(Yo);for(const o of i){const a=o.keyCombos.filter(s=>!n.some(l=>l.keyCombos.some(c=>s.keyCode===c.keyCode&&s.ctrl===c.ctrl&&s.shift===c.shift&&s.alt===c.alt&&s.meta===c.meta)));a.length>0&&n.push({...o,keyCombos:a})}return n}}class $t extends Vt{goLeft(e=!1,t){this.readingProgression===N.ltr?this.goBackward(e,t):this.readingProgression===N.rtl&&this.goForward(e,t)}goRight(e=!1,t){this.readingProgression===N.ltr?this.goForward(e,t):this.readingProgression===N.rtl&&this.goBackward(e,t)}}class ai extends Vt{}class si{constructor(e,t,n,i){this.injector=null,this.pub=e,this.item=n,this.burl=n.toURL(t)||"",this.cssProperties=i.cssProperties,this.injector=i.injector??null}async build(){if(!this.item.mediaType.isHTML)throw new Error(`Unsupported media type for WebPub: ${this.item.mediaType.string}`);return await this.buildHtmlFrame()}async buildHtmlFrame(){const e=await this.pub.get(this.item).readAsString();if(!e)throw new Error(`Failed reading item ${this.item.href}`);const t=new DOMParser().parseFromString(e,this.item.mediaType.string),n=t.querySelector("parsererror");if(n){const i=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${i?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(t,this.item),this.finalizeDOM(t,this.burl,this.item.mediaType,e,this.cssProperties)}setProperties(e,t){for(const n in e){const i=e[n];i&&t.documentElement.style.setProperty(n,i)}}finalizeDOM(e,t,n,i,o){if(!e)return"";if(o&&this.setProperties(o,e),e.body.querySelectorAll("img").forEach(s=>{s.setAttribute("fetchpriority","high")}),t!==void 0){const s=e.createElement("base");s.href=t,s.dataset.readium="true",e.head.firstChild.before(s)}let a;return n.string==="application/xhtml+xml"?a=new XMLSerializer().serializeToString(e):a=this.serializeAsHTML(e,i||""),URL.createObjectURL(new Blob([a],{type:n.isHTML?n.string:"application/xhtml+xml"}))}serializeAsHTML(e,t){const n=t.match(/<!DOCTYPE[^>]*>/i),i=n?n[0]+`
96
- `:"";let a=e.documentElement.outerHTML;return i+a}}const Ko=1e4;class ve{constructor(e,t){this.registry=new Map,this._ready=!1,this.listenerBuffer=[],this.handler=this.handle.bind(this),this.wnd=e,this.origin=t;try{this.channelId=window.crypto.randomUUID()}catch{this.channelId=Pt()}this.gc=setInterval(()=>{this.registry.forEach((n,i)=>{performance.now()-n.time>Ko&&(console.warn(i,"event for",n.key,"was never handled!"),this.registry.delete(i))})},5e3),window.addEventListener("message",this.handler),this.send("_ping",void 0)}set listener(e){this.listenerBuffer.length>0&&this.listenerBuffer.forEach(t=>e(t[0],t[1])),this.listenerBuffer=[],this._listener=e}clearListener(){typeof this._listener=="function"&&(this._listener=void 0)}halt(){this._ready=!1,window.removeEventListener("message",this.handler),clearInterval(this.gc),this._listener=void 0,this.registry.clear()}resume(){window.addEventListener("message",this.handler),this._ready=!0}handle(e){const t=e.data;if(!t._readium){console.warn("Ignoring",t);return}if(t._channel===this.channelId)switch(t.key){case"_ack":{if(!t.id)return;const n=this.registry.get(t.id);if(!n)return;this.registry.delete(t.id),n.cb(!!t.data);return}case"_pong":this._ready=!0;default:{if(!this.ready)return;typeof this._listener=="function"?this._listener(t.key,t.data):this.listenerBuffer.push([t.key,t.data])}}}get ready(){return this._ready}send(e,t,n,i=!1,o=[]){const a=Pt();return n&&this.registry.set(a,{cb:n,time:performance.now(),key:e}),this.wnd.postMessage({_readium:ge,_channel:this.channelId,id:a,data:t,key:e,strict:i},"/",o),a}}const Zo={RS__oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif"},Jo=16,li=Zo.RS__oldStyleTf;class we{constructor(e){this._optimalLineLength=null,this._canvas=document.createElement("canvas"),this._optimalChars=e.optimalChars,this._minChars=e.minChars,this._maxChars=e.maxChars,this._baseFontSize=e.baseFontSize||Jo,this._fontFace=e.fontFace||li,this._sample=e.sample||null,this._padding=e.padding??0,this._letterSpacing=e.letterSpacing?Math.round(e.letterSpacing*this._baseFontSize):0,this._wordSpacing=e.wordSpacing?Math.round(e.wordSpacing*this._baseFontSize):0,this._isCJK=e.isCJK||!1,this._getRelative=e.getRelative||!1,this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1,this._approximatedWordSpaces=we.approximateWordSpaces(this._optimalChars,this._sample)}updateMultipliers(){this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1}update(e){e.optimalChars&&(this._optimalChars=e.optimalChars),e.minChars!==void 0&&(this._minChars=e.minChars),e.maxChars!==void 0&&(this._maxChars=e.maxChars),e.baseFontSize&&(this._baseFontSize=e.baseFontSize),e.fontFace!==void 0&&(this._fontFace=e.fontFace||li),e.letterSpacing&&(this._letterSpacing=e.letterSpacing),e.wordSpacing&&(this._wordSpacing=e.wordSpacing),e.isCJK!=null&&(this._isCJK=e.isCJK),e.padding!==void 0&&(this._padding=e.padding??0),e.getRelative&&(this._getRelative=e.getRelative),e.sample&&(this._sample=e.sample,this._approximatedWordSpaces=we.approximateWordSpaces(this._optimalChars,this._sample)),this.updateMultipliers(),this._optimalLineLength=this.getOptimalLineLength()}get baseFontSize(){return this._baseFontSize}get minimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._minDivider!==null?Math.round(this._optimalLineLength/this._minDivider+this._padding)/(this._getRelative?this._baseFontSize:1):null}get maximalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._maxMultiplier!==null?Math.round(this._optimalLineLength*this._maxMultiplier+this._padding)/(this._getRelative?this._baseFontSize:1):null}get optimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),Math.round(this._optimalLineLength+this._padding)/(this._getRelative?this._baseFontSize:1)}get all(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),{min:this.minimalLineLength,max:this.maximalLineLength,optimal:this.optimalLineLength,baseFontSize:this._baseFontSize}}static approximateWordSpaces(e,t){let n=0;if(t&&t.length>=e){const i=t.match(/([\s]+)/gi);n=(i?i.length:0)*(e/t.length)}return n}getLineLengthFallback(){const e=this._letterSpacing*(this._optimalChars-1),t=this._wordSpacing*this._approximatedWordSpaces;return this._optimalChars*(this._baseFontSize*.5)+e+t}getOptimalLineLength(){if(this._fontFace){if(typeof this._fontFace=="string")return this.measureText(this._fontFace);{const e=new FontFace(this._fontFace.name,`url(${this._fontFace.url})`);e.load().then(()=>(document.fonts.add(e),this.measureText(e.family)),t=>{})}}return this.getLineLengthFallback()}measureText(e){const t=this._canvas.getContext("2d");if(t&&e){let n=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(t.font=`${this._baseFontSize}px ${e}`,this._sample&&this._sample.length>=this._optimalChars&&(n=this._sample.slice(0,this._optimalChars)),Object.hasOwn(t,"letterSpacing")&&Object.hasOwn(t,"wordSpacing"))return t.letterSpacing=this._letterSpacing.toString()+"px",t.wordSpacing=this._wordSpacing.toString()+"px",t.measureText(n).width;{const i=this._letterSpacing*(this._optimalChars-1),o=this._wordSpacing*we.approximateWordSpaces(this._optimalChars,this._sample);return t.measureText(n).width+i+o}}else return this.getLineLengthFallback()}}const ci=()=>typeof navigator>"u"?"":navigator.userAgent||"",hi=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class di{constructor(){const e=hi(),t=ci(),n=o=>(typeof o=="string"||typeof o=="number")&&o?String(o).replace(/_/g,".").split(".").map(a=>parseInt(a)||0):[],i=(o="")=>{if(!o)return[];const a=new RegExp("^.*"+o+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return a.test(t)?n(t.replace(a,"$1")):[]};this.OS=(o=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(o.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?o.iOS=o.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?o.iOS=o.iPadOS=i():o.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?o.Windows=(a=>a[0]!==6||!a[1]?a:a[1]===1?[7]:a[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(t)?o.Android=i("Android"):/CrOS/.test(t)?o.ChromeOS=i():/X11;/.test(t)&&(o.Linux=i()),o))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(o=>(a=>{const s=o.platform,l=o.platformVersion;if(!(!s||!l)){if(/^i(OS|P(hone|od touch))$/.test(s))a.iOS=n(l);else if(/^iPad(OS)?$/.test(s))a.iOS=a.iPadOS=n(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(s))document.ontouchend!==void 0?a.iOS=a.iPadOS=n():a.macOS=n(l);else if(/^(Microsoft )?Windows$/.test(s))a.Windows=n(l);else if(/^(Google )?Android$/.test(s))a.Android=n(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(s))a.ChromeOS=n(l);else if(/^(Linux|Ubuntu|X11)$/.test(s))a.Linux=n(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,a)}})({})),this.UA=(o=>{let a=!1;if(e&&Array.isArray(e.brands)){const s=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});s["Google Chrome"]?(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Chrome=s["Google Chrome"]):s["Microsoft Edge"]?(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Edge=s["Microsoft Edge"]):s.Opera&&(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Opera=s.Opera)}return a||(/ Gecko\/\d/.test(t)?(o.Gecko=i("rv"),/ Waterfox\/\d/.test(t)?o.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(t)&&(o.Firefox=i("Firefox"))):/ Edge\/\d/.test(t)?(o.EdgeHTML=i("Edge"),o.Edge=o.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(o.Blink=o.Chromium=(s=>s[0]?s:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(t)?o.Edge=(s=>s[0]?s:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(t)?o.Opera=i("OPR"):/ Vivaldi\/\d/.test(t)?o.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(t)?o.Silk=i("Silk"):/ UCBrowser\/\d/.test(t)?o.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(t)?o.Phoebe=i("Phoebe"):o.Chrome=(s=>s[0]?s:o.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(t)?(o.WebKit=i("AppleWebKit"),/ CriOS \d/.test(t)?o.Chrome=i("CriOS"):/ FxiOS \d/.test(t)?o.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(t)?o.Edge=i("EdgiOS"):/ Version\/\d/.test(t)&&(o.Safari=i("Version"))):/ Trident\/\d/.test(t)&&(o.Trident=i("Trident"),o.InternetExplorer=(s=>s[0]?s:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(o.Facebook=i("FBAV")),/ Line\/\d/.test(t)&&(o.LINE=i("Line")),o})({}),this.Env={get:()=>[this.OS,this.UA].reduce((o,a)=>{for(const s in a)a[s]&&o.push(s);return o},[])}}}class Qo extends di{get iOSRequest(){const e=hi(),t=ci();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 q=new di,O=new Qo;function se(r){const e=r.languages?.[0]?.toLowerCase(),t=r.readingProgression;if(e){if(e.startsWith("zh")||e.startsWith("ja")||e.startsWith("ko"))return t===N.rtl?"cjk-vertical":"cjk-horizontal";if(e.startsWith("mn-mong"))return"mongolian-vertical";if(e.startsWith("ar")||e.startsWith("fa")||e.startsWith("he"))return"rtl"}return"ltr"}class Xt{constructor(e,t){this.config=e,this.onUpdate=t,this.unsubs=[],this.conditionValues=new Map}setup(){let e=!0;this.config.forEach(t=>t.keyCombos.forEach(n=>{if(n.condition){const i=n.condition.subscribe(o=>{this.conditionValues.set(n,o),e||this.onUpdate(this.buildSerializable())});this.unsubs.push(i)}})),e=!1,this.onUpdate(this.buildSerializable())}buildSerializable(){return this.config.map(e=>({...e,keyCombos:e.keyCombos.filter(t=>!t.condition||this.conditionValues.get(t)===!0).map(({condition:t,...n})=>n)})).filter(e=>e.keyCombos.length>0)}destroy(){this.unsubs.forEach(e=>e()),this.unsubs=[],this.conditionValues.clear()}}class ui{constructor(e,t={},n=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.frame.style.backgroundColor="#FFFFFF",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...n]}async load(e=[]){return new Promise((t,n)=>{if(this.loader){const i=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(i)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new _e(i,e),this.currModules=e,this.comms=void 0;try{t(i)}catch{}return}this.frame.onload=()=>{const i=this.frame.contentWindow;this.loader=new _e(i,e),this.currModules=e;try{t(i)}catch{}},this.frame.onerror=i=>{try{n(i)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Xt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){this.conditionBridge?.destroy(),await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),new Promise((t,n)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const i=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,q.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,i):i()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new ve(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get msg(){return this.comms}get ldr(){return this.loader}}class mi{constructor(e,t,n,i={},o=[]){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.currentCssProperties=t,this.injector=n,this.contentProtectionConfig=i,this.keyboardPeripheralsConfig=[...o]}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>{this.injector?.releaseBlobUrl?.(a),URL.revokeObjectURL(a)}),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}async update(e,t,n){const i=e.readingOrder.items;let o=i.findIndex(l=>l.href===t.href);if(o<0)throw Error(`Locator not found in reading order: ${t.href}`);const a=i[o].href;this.inprogress.has(a)&&await this.inprogress.get(a);const s=new Promise(async(l,c)=>{const h=[],u=[];e.readingOrder.items.forEach((d,p)=>{p!==o&&p!==o-1&&p!==o+1&&(h.includes(d.href)||h.push(d.href)),p===o&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const R=this.blobs.get(d);R&&(this.injector?.releaseBlobUrl?.(R),URL.revokeObjectURL(R),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const R=this.pool.get(d);if(!this.blobs.has(d))await R.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await R.load(n);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const U=await new si(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,U)}const _=new ui(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==a&&await _.hide(),this.container.appendChild(_.iframe),await _.load(n),this.pool.set(d,_)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=this.pool.get(a);f?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),f&&await f.load(n),f&&await f.show(t.locations.progression),this._currentFrame=f),l()});this.inprogress.set(a,s),await s,this.inprogress.delete(a)}setCSSProperties(e){if(!((n,i)=>{const o=Object.keys(n),a=Object.keys(i);if(o.length!==a.length)return!1;for(const s of o)if(n[s]!==i[s])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(n=>{n.setCSSProperties(e)});for(const n of this.blobs.keys())this.pendingUpdates.set(n,{inPool:this.pool.has(n)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}}var Yt,pi;function er(){if(pi)return Yt;pi=1;function r(i){if(typeof i!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function e(i,o){for(var a="",s=0,l=-1,c=0,h,u=0;u<=i.length;++u){if(u<i.length)h=i.charCodeAt(u);else{if(h===47)break;h=47}if(h===47){if(!(l===u-1||c===1))if(l!==u-1&&c===2){if(a.length<2||s!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var m=a.lastIndexOf("/");if(m!==a.length-1){m===-1?(a="",s=0):(a=a.slice(0,m),s=a.length-1-a.lastIndexOf("/")),l=u,c=0;continue}}else if(a.length===2||a.length===1){a="",s=0,l=u,c=0;continue}}o&&(a.length>0?a+="/..":a="..",s=2)}else a.length>0?a+="/"+i.slice(l+1,u):a=i.slice(l+1,u),s=u-l-1;l=u,c=0}else h===46&&c!==-1?++c:c=-1}return a}function t(i,o){var a=o.dir||o.root,s=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+s:a+i+s:s}var n={resolve:function(){for(var o="",a=!1,s,l=arguments.length-1;l>=-1&&!a;l--){var c;l>=0?c=arguments[l]:(s===void 0&&(s=process.cwd()),c=s),r(c),c.length!==0&&(o=c+"/"+o,a=c.charCodeAt(0)===47)}return o=e(o,!a),a?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(r(o),o.length===0)return".";var a=o.charCodeAt(0)===47,s=o.charCodeAt(o.length-1)===47;return o=e(o,!a),o.length===0&&!a&&(o="."),o.length>0&&s&&(o+="/"),a?"/"+o:o},isAbsolute:function(o){return r(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,a=0;a<arguments.length;++a){var s=arguments[a];r(s),s.length>0&&(o===void 0?o=s:o+="/"+s)}return o===void 0?".":n.normalize(o)},relative:function(o,a){if(r(o),r(a),o===a||(o=n.resolve(o),a=n.resolve(a),o===a))return"";for(var s=1;s<o.length&&o.charCodeAt(s)===47;++s);for(var l=o.length,c=l-s,h=1;h<a.length&&a.charCodeAt(h)===47;++h);for(var u=a.length,m=u-h,f=c<m?c:m,d=-1,p=0;p<=f;++p){if(p===f){if(m>f){if(a.charCodeAt(h+p)===47)return a.slice(h+p+1);if(p===0)return a.slice(h+p)}else c>f&&(o.charCodeAt(s+p)===47?d=p:p===0&&(d=0));break}var _=o.charCodeAt(s+p),R=a.charCodeAt(h+p);if(_!==R)break;_===47&&(d=p)}var U="";for(p=s+d+1;p<=l;++p)(p===l||o.charCodeAt(p)===47)&&(U.length===0?U+="..":U+="/..");return U.length>0?U+a.slice(h+d):(h+=d,a.charCodeAt(h)===47&&++h,a.slice(h))},_makeLong:function(o){return o},dirname:function(o){if(r(o),o.length===0)return".";for(var a=o.charCodeAt(0),s=a===47,l=-1,c=!0,h=o.length-1;h>=1;--h)if(a=o.charCodeAt(h),a===47){if(!c){l=h;break}}else c=!1;return l===-1?s?"/":".":s&&l===1?"//":o.slice(0,l)},basename:function(o,a){if(a!==void 0&&typeof a!="string")throw new TypeError('"ext" argument must be a string');r(o);var s=0,l=-1,c=!0,h;if(a!==void 0&&a.length>0&&a.length<=o.length){if(a.length===o.length&&a===o)return"";var u=a.length-1,m=-1;for(h=o.length-1;h>=0;--h){var f=o.charCodeAt(h);if(f===47){if(!c){s=h+1;break}}else m===-1&&(c=!1,m=h+1),u>=0&&(f===a.charCodeAt(u)?--u===-1&&(l=h):(u=-1,l=m))}return s===l?l=m:l===-1&&(l=o.length),o.slice(s,l)}else{for(h=o.length-1;h>=0;--h)if(o.charCodeAt(h)===47){if(!c){s=h+1;break}}else l===-1&&(c=!1,l=h+1);return l===-1?"":o.slice(s,l)}},extname:function(o){r(o);for(var a=-1,s=0,l=-1,c=!0,h=0,u=o.length-1;u>=0;--u){var m=o.charCodeAt(u);if(m===47){if(!c){s=u+1;break}continue}l===-1&&(c=!1,l=u+1),m===46?a===-1?a=u:h!==1&&(h=1):a!==-1&&(h=-1)}return a===-1||l===-1||h===0||h===1&&a===l-1&&a===s+1?"":o.slice(a,l)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return t("/",o)},parse:function(o){r(o);var a={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return a;var s=o.charCodeAt(0),l=s===47,c;l?(a.root="/",c=1):c=0;for(var h=-1,u=0,m=-1,f=!0,d=o.length-1,p=0;d>=c;--d){if(s=o.charCodeAt(d),s===47){if(!f){u=d+1;break}continue}m===-1&&(f=!1,m=d+1),s===46?h===-1?h=d:p!==1&&(p=1):h!==-1&&(p=-1)}return h===-1||m===-1||p===0||p===1&&h===m-1&&h===u+1?m!==-1&&(u===0&&l?a.base=a.name=o.slice(1,m):a.base=a.name=o.slice(u,m)):(u===0&&l?(a.name=o.slice(1,h),a.base=o.slice(1,m)):(a.name=o.slice(u,h),a.base=o.slice(u,m)),a.ext=o.slice(h,m)),u>0?a.dir=o.slice(0,u-1):l&&(a.dir="/"),a},sep:"/",delimiter:":",win32:null,posix:null};return n.posix=n,Yt=n,Yt}var dt=er();const ut={experimentalHeaderFiltering:{description:"Attempts to filter out paragraphs that are implicitly headings or part of headers",scope:"RS",value:"readium-experimentalHeaderFiltering-on"},experimentalZoom:{description:"Attemps to filter out elements that are sized using viewport units and should not be scaled directly e.g. tables, images, iframes, etc.",scope:"RS",value:"readium-experimentalZoom-on"}};var Z=(r=>(r.start="start",r.left="left",r.right="right",r.justify="justify",r))(Z||{});const le={range:[0,100],step:1},Te={range:[.7,4],step:.05},ee={range:[100,1e3],step:100},Me={range:[50,250],step:10},Fe={range:[0,1],step:.125},Ne={range:[1,2],step:.1},ce={range:[20,100],step:1},Ie={range:[0,3],step:.25},De={range:[0,3],step:.25},He={range:[0,2],step:.125},We={range:[.7,4],step:.05},Be={range:[0,1],step:.1},je={range:[.5,4],step:.1},te={range:[5,60],step:5};class Ge{constructor(){}toFlag(e){return`readium-${e}-on`}toUnitless(e){return e.toString()}toPercentage(e,t=!1){return t||e>0&&e<=1?`${Math.round(e*100)}%`:`${e}%`}toVw(e){const t=Math.round(e*100);return`${Math.min(t,100)}vw`}toVh(e){const t=Math.round(e*100);return`${Math.min(t,100)}vh`}toPx(e){return`${e}px`}toRem(e){return`${e}rem`}}class qt extends Ge{constructor(e){super(),this.a11yNormalize=e.a11yNormalize??null,this.bodyHyphens=e.bodyHyphens??null,this.fontFamily=e.fontFamily??null,this.fontWeight=e.fontWeight??null,this.iOSPatch=e.iOSPatch??null,this.iPadOSPatch=e.iPadOSPatch??null,this.letterSpacing=e.letterSpacing??null,this.ligatures=e.ligatures??null,this.lineHeight=e.lineHeight??null,this.noRuby=e.noRuby??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.textAlign=e.textAlign??null,this.wordSpacing=e.wordSpacing??null,this.zoom=e.zoom??null}toCSSProperties(){const e={};return this.a11yNormalize&&(e["--USER__a11yNormalize"]=this.toFlag("a11y")),this.bodyHyphens&&(e["--USER__bodyHyphens"]=this.bodyHyphens),this.fontFamily&&(e["--USER__fontFamily"]=this.fontFamily),this.fontWeight!=null&&(e["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.iOSPatch&&(e["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(e["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(e["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(e["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(e["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.noRuby&&(e["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(e["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.textAlign&&(e["--USER__textAlign"]=this.textAlign),this.wordSpacing!=null&&(e["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),this.zoom!==null&&(e["--USER__zoom"]=this.toPercentage(this.zoom,!0)),e}}class gi extends Ge{constructor(e){super(),this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=ut[t].value}),e}}class fi{constructor(e){this.rsProperties=e.rsProperties,this.userProperties=e.userProperties}update(e){e.experiments&&(this.rsProperties.experiments=e.experiments);const t={a11yNormalize:e.textNormalization,bodyHyphens:typeof e.hyphens!="boolean"?null:e.hyphens?"auto":"none",fontFamily:e.fontFamily,fontWeight:e.fontWeight,iOSPatch:e.iOSPatch,iPadOSPatch:e.iPadOSPatch,letterSpacing:e.letterSpacing,ligatures:typeof e.ligatures!="boolean"?null:e.ligatures?"common-ligatures":"none",lineHeight:e.lineHeight,noRuby:e.noRuby,paraIndent:e.paragraphIndent,paraSpacing:e.paragraphSpacing,textAlign:e.textAlign,wordSpacing:e.wordSpacing,zoom:e.zoom};this.userProperties=new qt(t)}}function yi(r,e){return r==null||e==null||r<=e?r:void 0}function Si(r,e){return r==null||e==null||r>=e?r:void 0}function I(r){return typeof r=="string"?r:r===null?null:void 0}function P(r){return typeof r=="boolean"||r==null?r:void 0}function Ve(r,e){if(r!==void 0)return r===null?null:e[r]!==void 0?r:void 0}function he(r){return typeof r=="boolean"||typeof r=="number"&&r>=0?r:r===null?null:void 0}function v(r){if(r!==void 0)return r===null?null:r<0?void 0:r}function M(r,e){if(r===void 0)return;if(r===null)return null;const t=Math.min(...e),n=Math.max(...e);return r>=t&&r<=n?r:void 0}function mt(r,e){return r===void 0?e:r}function Kt(r){if(r!==void 0)return r===null?null:r.filter(e=>e in ut)}class Pe{constructor(e={}){this.fontFamily=I(e.fontFamily),this.fontWeight=M(e.fontWeight,ee.range),this.hyphens=P(e.hyphens),this.iOSPatch=P(e.iOSPatch),this.iPadOSPatch=P(e.iPadOSPatch),this.letterSpacing=v(e.letterSpacing),this.ligatures=P(e.ligatures),this.lineHeight=v(e.lineHeight),this.noRuby=P(e.noRuby),this.paragraphIndent=v(e.paragraphIndent),this.paragraphSpacing=v(e.paragraphSpacing),this.textAlign=Ve(e.textAlign,Z),this.textNormalization=P(e.textNormalization),this.wordSpacing=v(e.wordSpacing),this.zoom=M(e.zoom,We.range)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Pe(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(t[n]=e[n]);return new Pe(t)}}class bi{constructor(e){this.fontFamily=I(e.fontFamily)||null,this.fontWeight=M(e.fontWeight,ee.range)||null,this.hyphens=P(e.hyphens)??null,this.iOSPatch=e.iOSPatch===!1?!1:(O.OS.iOS||O.OS.iPadOS)&&O.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:O.OS.iPadOS&&O.iOSRequest==="desktop",this.letterSpacing=v(e.letterSpacing)||null,this.ligatures=P(e.ligatures)??null,this.lineHeight=v(e.lineHeight)||null,this.noRuby=P(e.noRuby)??!1,this.paragraphIndent=v(e.paragraphIndent)??null,this.paragraphSpacing=v(e.paragraphSpacing)??null,this.textAlign=Ve(e.textAlign,Z)||null,this.textNormalization=P(e.textNormalization)??!1,this.wordSpacing=v(e.wordSpacing)||null,this.zoom=M(e.zoom,We.range)||1,this.experiments=Kt(e.experiments)??null}}class Zt{constructor(e,t,n){this.fontFamily=null,this.fontWeight=null,this.hyphens=null,this.iOSPatch=null,this.iPadOSPatch=null,this.letterSpacing=null,this.ligatures=null,this.lineHeight=null,this.noRuby=null,this.paragraphIndent=null,this.paragraphSpacing=null,this.textAlign=null,this.textNormalization=null,this.wordSpacing=null,n&&(this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.iOSPatch=e.iOSPatch===!1?!1:e.iOSPatch===!0?(O.OS.iOS||O.OS.iPadOS)&&O.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?O.OS.iPadOS&&O.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.textAlign=e.textAlign||t.textAlign||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null),this.zoom=e.zoom!==void 0?e.zoom:t.zoom!==void 0?t.zoom:null,this.experiments=t.experiments||null}}class T{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i}){this._value=e,this._effectiveValue=t,this._isEffective=n,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}}class A extends T{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}toggle(){this._value=!this._value,this._onChange(this._value)}}class Jt extends T{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i,supportedValues:o}){super({initialValue:e,effectiveValue:t,isEffective:n,onChange:i}),this._supportedValues=o}set value(e){if(e&&!this._supportedValues.includes(e))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 effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedValues(){return this._supportedValues}clear(){this._value=null}}class E extends T{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i,supportedRange:o,step:a}){super({initialValue:e,effectiveValue:t,isEffective:n,onChange:i}),this._supportedRange=o,this._step=a,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e&&(e<this._supportedRange[0]||e>this._supportedRange[1]))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 effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value&&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&&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()}clear(){this._value=null}}class Qt{constructor(e,t,n){this.preferences=e,this.settings=t,this.metadata=n}clear(){this.preferences=new Pe({})}updatePreference(e,t){this.preferences[e]=t}get isDisplayTransformable(){return this.metadata?.accessibility?.feature?.some(e=>e.value===Je.DISPLAY_TRANSFORMABILITY.value)??!1}get fontFamily(){return new T({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontFamily",e??null)}})}get fontWeight(){return new E({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:ee.range,step:ee.step})}get hyphens(){return new A({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("hyphens",e??null)}})}get iOSPatch(){return new A({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:!0,onChange:e=>{this.updatePreference("iOSPatch",e??null)}})}get iPadOSPatch(){return new A({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:!0,onChange:e=>{this.updatePreference("iPadOSPatch",e??null)}})}get letterSpacing(){return new E({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Fe.range,step:Fe.step})}get ligatures(){return new A({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("ligatures",e??null)}})}get lineHeight(){return new E({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:Ne.range,step:Ne.step})}get noRuby(){return new A({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("noRuby",e??null)}})}get paragraphIndent(){return new E({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Ie.range,step:Ie.step})}get paragraphSpacing(){return new E({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:De.range,step:De.step})}get textAlign(){return new Jt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||Z.start,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(Z)})}get textNormalization(){return new A({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textNormalization",e??null)}})}get wordSpacing(){return new E({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:He.range,step:He.step})}get zoom(){return new E({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:e=>{this.updatePreference("zoom",e??null)},supportedRange:We.range,step:We.step})}}const _i=r=>{if("blob"in r&&r.blob.type)return r.blob.type;if(r.as==="script")return"text/javascript";if(r.as==="link"&&"url"in r){const e=r.url.toLowerCase();if(e.endsWith(".css"))return"text/css";if([".js",".mjs",".cjs"].some(t=>e.endsWith(t)))return"text/javascript"}},vi=(r,e)=>{e.attributes&&Object.entries(e.attributes).forEach(([t,n])=>{t==="type"||t==="rel"||t==="href"||t==="src"||n!=null&&(typeof n=="boolean"?n&&r.setAttribute(t,""):r.setAttribute(t,n))})},tr=(r,e,t)=>{const n=r.createElement("script");n.dataset.readium="true",e.id&&(n.id=e.id);const i=e.type||_i(e);return i&&(n.type=i),vi(n,e),n.src=t,n},wi=(r,e,t)=>{const n=r.createElement("link");n.dataset.readium="true",e.id&&(n.id=e.id),e.rel&&(n.rel=e.rel);const i=e.type||_i(e);return i&&(n.type=i),vi(n,e),n.href=t,n};class en{constructor(e){this.blobStore=new Map,this.createdBlobUrls=new Set,this.allowedDomains=[],this.injectableIdCounter=0,this.allowedDomains=(e.allowedDomains||[]).map(t=>{try{return new URL(t),t}catch{throw new Error(`Invalid allowed domain: "${t}". Must be a valid URL (e.g., "https://fonts.googleapis.com").`)}}),this.rules=e.rules.map(t=>{const n={...t};return t.prepend&&(n.prepend=t.prepend.map(i=>({...i,id:i.id||`injectable-${this.injectableIdCounter++}`})).reverse()),t.append&&(n.append=t.append.map(i=>({...i,id:i.id||`injectable-${this.injectableIdCounter++}`}))),n})}dispose(){for(const e of this.createdBlobUrls)try{URL.revokeObjectURL(e)}catch(t){console.warn("Failed to revoke blob URL:",e,t)}this.createdBlobUrls.clear()}getAllowedDomains(){return[...this.allowedDomains]}async injectForDocument(e,t){for(const n of this.rules)this.matchesRule(n,t)&&await this.applyRule(e,n)}matchesRule(e,t){const n=t.href;return e.resources.some(i=>i instanceof RegExp?i.test(n):n===i)}async getOrCreateBlobUrl(e){const t=e.id;if(this.blobStore.has(t)){const n=this.blobStore.get(t);return n.refCount++,n.url}if("blob"in e){const n=URL.createObjectURL(e.blob);return this.blobStore.set(t,{url:n,refCount:1}),this.createdBlobUrls.add(n),n}throw new Error("Resource must have a blob property")}async releaseBlobUrl(e){if(!this.createdBlobUrls.has(e))return;const t=Array.from(this.blobStore.values()).find(n=>n.url===e);if(t&&(t.refCount--,t.refCount<=0)){URL.revokeObjectURL(e),this.createdBlobUrls.delete(e);for(const[n,i]of this.blobStore.entries())if(i.url===e){this.blobStore.delete(n);break}}}async getResourceUrl(e,t){if("url"in e){const n=new URL(e.url,t.baseURI).toString();if(!this.isValidUrl(n,t))throw new Error(`Invalid URL: Only HTTPS, data:, blob:, or localhost HTTP URLs are allowed. Got: ${e.url}`);return n}else return this.getOrCreateBlobUrl(e)}createPreloadLink(e,t,n){if(t.as!=="link"||t.rel!=="preload")return;const i={...t,rel:"preload",attributes:{...t.attributes,as:t.as}},o=wi(e,i,n);e.head.appendChild(o)}createElement(e,t,n){if(t.as==="script")return tr(e,t,n);if(t.as==="link")return wi(e,t,n);throw new Error(`Unsupported element type: ${t.as}`)}async applyRule(e,t){const n=[],i=t.prepend?t.prepend.filter(a=>!a.condition||a.condition(e)):[],o=t.append?t.append.filter(a=>!a.condition||a.condition(e)):[];try{for(const a of i)await this.processInjectable(a,e,n,"prepend");for(const a of o)await this.processInjectable(a,e,n,"append")}catch(a){for(const{element:s,url:l}of n)try{s.remove(),await this.releaseBlobUrl(l)}catch(c){console.error("Error during cleanup:",c)}throw a}}async processInjectable(e,t,n,i){const o=e.target==="body"?t.body:t.head;if(!o)return;let a=null;try{if(a=await this.getResourceUrl(e,t),e.rel==="preload"&&"url"in e)this.createPreloadLink(t,e,a);else{const s=this.createElement(t,e,a);n.push({element:s,url:a}),i==="prepend"?o.prepend(s):o.append(s)}}catch(s){throw console.error("Failed to process resource:",s),a&&"blob"in e&&await this.releaseBlobUrl(a),s}}isValidUrl(e,t){try{const n=new URL(e,t.baseURI);if(n.protocol==="data:"||n.protocol==="blob:"&&this.createdBlobUrls.has(e))return!0;if(this.allowedDomains.length>0){const i=n.origin;return this.allowedDomains.some(o=>{const a=new URL(o).origin;return i===a})}return!1}catch{return!1}}}const Re=r=>r.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),$e=r=>r.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," "),nr=`/*!
97
- * Readium CSS v.2.0.0
95
+ `,e.document.head.appendChild(n),this.resizeObserver=new ResizeObserver(()=>{this.resizeDebounce&&this.wnd.clearTimeout(this.resizeDebounce),this.isResizing=!0,this.resizeDebounce=this.wnd.setTimeout(()=>{this.isResizing=!1,this.resizeDebounce=null,this.reportProgress()},50)}),this.resizeObserver.observe(e.document.body),e.addEventListener("scroll",this.handleScroll,{passive:!0}),t.register("force_webkit_recalc",j.moduleName,()=>{At(this.wnd);const i=this.doc().scrollLeft;this.verticalLR?this.doc().scrollLeft=i>1?i-1:i+1:this.doc().scrollLeft=i<-1?i+1:i-1,this.doc().scrollLeft=i}),t.register("go_progression",j.moduleName,(i,o)=>{const a=i;if(a<0||a>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),o(!1);return}this.wnd.requestAnimationFrame(()=>{const s=this.scrollable()*a;this.doc().scrollLeft=this.verticalLR?s:-s,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_id",j.moduleName,(i,o)=>{const a=e.document.getElementById(i);if(!a){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft+=a.getBoundingClientRect().left-e.innerWidth/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_text",j.moduleName,(i,o)=>{let a;Array.isArray(i)&&(i.length>1&&(a=i[1]),i=i[0]);const s=oe.deserialize(i),l=Le(this.wnd.document,new N({href:e.location.href,type:"text/html",text:s,locations:a?new C({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!l){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft+=l.getBoundingClientRect().left-e.innerWidth/2,this.reportProgress(),z(this.wnd),o(!0)})}),t.register("go_start",j.moduleName,(i,o)=>{if(this.doc().scrollLeft===0)return o(!1);this.doc().scrollLeft=0,this.reportProgress(),o(!0)}),t.register("go_end",j.moduleName,(i,o)=>{if(Math.abs(this.doc().scrollLeft)===this.scrollable())return o(!1);this.doc().scrollLeft=this.verticalLR?this.scrollable():-this.scrollable(),this.reportProgress(),o(!0)}),t.register(["go_next","go_prev"],j.moduleName,(i,o)=>o(!1)),t.register("unfocus",j.moduleName,(i,o)=>{z(this.wnd),o(!0)}),t.register("scroll_protection",j.moduleName,(i,o)=>{this.enableScrollProtection(),o(!0)}),t.register("focus",j.moduleName,(i,o)=>{this.reportProgress(),o(!0)}),t.register("first_visible_locator",j.moduleName,(i,o)=>{const a=lt(e,!0);this.comms.send("first_visible_locator",a.serialize()),o(!0)}),t.log("CJKVerticalSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(j.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(ri)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("CJKVerticalSnapper Unmounted"),!0}};j.moduleName="cjk_vertical_snapper";let jt=j;const jo=["fixed_setup","decorator","peripherals","print_protection"],Go=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper","cjk_vertical_snapper","print_protection"],Vo=["webpub_setup","webpub_snapper","decorator","peripherals","print_protection"],Gt=new Map([Wt,Dt,Bt,It,Ht,Ot,Nt,Mt,jt,Bo].map(r=>[r.moduleName,r]));class be{constructor(e=window,t=[]){this.loadedModules=[],this.wnd=e,this.comms=new uo(e);const n=[...new Set(t)];if(n.length){if(typeof e>"u")throw Error("Loader is not in a web browser");e.parent!==e&&this.comms.log("Loader is probably in a frame"),this.loadedModules=n.map(i=>{const o=this.loadModule(i);if(o)return o.mount(this.wnd,this.comms),o}).filter(i=>i!==void 0)}}loadModule(e){const t=Gt.get(e);return t===void 0?(this.comms.log(`Module "${name}" does not exist in the library`),t):new t}addModule(e){const t=this.loadModule(e);return!t||!t.mount(this.wnd,this.comms)?!1:(this.loadedModules.push(t),!0)}removeModule(e){const t=Gt.get(e);if(t===void 0)return this.comms.log(`Module "${e}" does not exist in the library`),!1;const n=this.loadedModules.findIndex(i=>i instanceof t);return n<0?!1:(this.loadedModules[n].unmount(this.wnd,this.comms),this.loadedModules.splice(n,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(e=>e.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const $o={type:"developer_tools",keyCombos:[{keyCode:73,meta:!0,alt:!0},{keyCode:73,ctrl:!0,shift:!0},{keyCode:74,meta:!0,alt:!0},{keyCode:74,ctrl:!0,shift:!0},{keyCode:85,meta:!0,alt:!0},{keyCode:67,meta:!0,alt:!0},{keyCode:67,meta:!0,shift:!0},{keyCode:67,ctrl:!0,shift:!0},{keyCode:65,meta:!0,alt:!0},{keyCode:84,meta:!0,shift:!0,alt:!0},{keyCode:67,shift:!0,alt:!0},{keyCode:123},{keyCode:123,shift:!0},{keyCode:123,ctrl:!0,shift:!0},{keyCode:123,meta:!0,alt:!0}]},Ko={type:"select_all",keyCombos:[{keyCode:65,meta:!0},{keyCode:65,ctrl:!0}]},Xo={type:"print",keyCombos:[{keyCode:80,meta:!0},{keyCode:80,ctrl:!0},{keyCode:80,meta:!0,shift:!0},{keyCode:80,ctrl:!0,shift:!0},{keyCode:80,meta:!0,alt:!0},{keyCode:80,ctrl:!0,alt:!0}]},Yo={type:"save",keyCombos:[{keyCode:83,meta:!0},{keyCode:83,ctrl:!0}]};class Vt{mergeKeyboardPeripherals(e,t=[]){const n=[],i=t.filter(o=>!["developer_tools","select_all","print","save"].includes(o.type));e.disableSelectAll&&n.push(Ko),e.disableSave&&n.push(Yo),e.monitorDevTools&&n.push($o),e.protectPrinting?.disable&&n.push(Xo);for(const o of i){const a=o.keyCombos.filter(s=>!n.some(l=>l.keyCombos.some(c=>s.keyCode===c.keyCode&&s.ctrl===c.ctrl&&s.shift===c.shift&&s.alt===c.alt&&s.meta===c.meta)));a.length>0&&n.push({...o,keyCombos:a})}return n}}class $t extends Vt{goLeft(e=!1,t){this.readingProgression===M.ltr?this.goBackward(e,t):this.readingProgression===M.rtl&&this.goForward(e,t)}goRight(e=!1,t){this.readingProgression===M.ltr?this.goForward(e,t):this.readingProgression===M.rtl&&this.goBackward(e,t)}}class ai extends Vt{}class si{constructor(e,t,n,i){this.injector=null,this.pub=e,this.item=n,this.burl=n.toURL(t)||"",this.cssProperties=i.cssProperties,this.injector=i.injector??null}async build(){if(!this.item.mediaType.isHTML)throw new Error(`Unsupported media type for WebPub: ${this.item.mediaType.string}`);return await this.buildHtmlFrame()}async buildHtmlFrame(){const e=await this.pub.get(this.item).readAsString();if(!e)throw new Error(`Failed reading item ${this.item.href}`);const t=new DOMParser().parseFromString(e,this.item.mediaType.string),n=t.querySelector("parsererror");if(n){const i=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${i?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(t,this.item),this.finalizeDOM(t,this.burl,this.item.mediaType,e,this.cssProperties)}setProperties(e,t){for(const n in e){const i=e[n];i&&t.documentElement.style.setProperty(n,i)}}finalizeDOM(e,t,n,i,o){if(!e)return"";if(o&&this.setProperties(o,e),e.body.querySelectorAll("img").forEach(s=>{s.setAttribute("fetchpriority","high")}),t!==void 0){const s=e.createElement("base");s.href=t,s.dataset.readium="true",e.head.firstChild.before(s)}let a;return n.string==="application/xhtml+xml"?a=new XMLSerializer().serializeToString(e):a=this.serializeAsHTML(e,i||""),URL.createObjectURL(new Blob([a],{type:n.isHTML?n.string:"application/xhtml+xml"}))}serializeAsHTML(e,t){const n=t.match(/<!DOCTYPE[^>]*>/i),i=n?n[0]+`
96
+ `:"";let a=e.documentElement.outerHTML;return i+a}}const qo=1e4;class ve{constructor(e,t){this.registry=new Map,this._ready=!1,this.listenerBuffer=[],this.handler=this.handle.bind(this),this.wnd=e,this.origin=t;try{this.channelId=window.crypto.randomUUID()}catch{this.channelId=Rt()}this.gc=setInterval(()=>{this.registry.forEach((n,i)=>{performance.now()-n.time>qo&&(console.warn(i,"event for",n.key,"was never handled!"),this.registry.delete(i))})},5e3),window.addEventListener("message",this.handler),this.send("_ping",void 0)}set listener(e){this.listenerBuffer.length>0&&this.listenerBuffer.forEach(t=>e(t[0],t[1])),this.listenerBuffer=[],this._listener=e}clearListener(){typeof this._listener=="function"&&(this._listener=void 0)}halt(){this._ready=!1,window.removeEventListener("message",this.handler),clearInterval(this.gc),this._listener=void 0,this.registry.clear()}resume(){window.addEventListener("message",this.handler),this._ready=!0}handle(e){const t=e.data;if(!t._readium){console.warn("Ignoring",t);return}if(t._channel===this.channelId)switch(t.key){case"_ack":{if(!t.id)return;const n=this.registry.get(t.id);if(!n)return;this.registry.delete(t.id),n.cb(!!t.data);return}case"_pong":this._ready=!0;default:{if(!this.ready)return;typeof this._listener=="function"?this._listener(t.key,t.data):this.listenerBuffer.push([t.key,t.data])}}}get ready(){return this._ready}send(e,t,n,i=!1,o=[]){const a=Rt();return n&&this.registry.set(a,{cb:n,time:performance.now(),key:e}),this.wnd.postMessage({_readium:ge,_channel:this.channelId,id:a,data:t,key:e,strict:i},"/",o),a}}const Jo={oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif"},Zo=16,li=Jo.oldStyleTf;class we{constructor(e){this._optimalLineLength=null,this._canvas=document.createElement("canvas"),this._optimalChars=e.optimalChars,this._minChars=e.minChars,this._maxChars=e.maxChars,this._baseFontSize=e.baseFontSize||Zo,this._fontFace=e.fontFace||li,this._sample=e.sample||null,this._padding=e.padding??0,this._letterSpacing=e.letterSpacing?Math.round(e.letterSpacing*this._baseFontSize):0,this._wordSpacing=e.wordSpacing?Math.round(e.wordSpacing*this._baseFontSize):0,this._isCJK=e.isCJK||!1,this._getRelative=e.getRelative||!1,this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1,this._approximatedWordSpaces=we.approximateWordSpaces(this._optimalChars,this._sample)}updateMultipliers(){this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1}update(e){e.optimalChars&&(this._optimalChars=e.optimalChars),e.minChars!==void 0&&(this._minChars=e.minChars),e.maxChars!==void 0&&(this._maxChars=e.maxChars),e.baseFontSize&&(this._baseFontSize=e.baseFontSize),e.fontFace!==void 0&&(this._fontFace=e.fontFace||li),e.letterSpacing&&(this._letterSpacing=e.letterSpacing),e.wordSpacing&&(this._wordSpacing=e.wordSpacing),e.isCJK!=null&&(this._isCJK=e.isCJK),e.padding!==void 0&&(this._padding=e.padding??0),e.getRelative&&(this._getRelative=e.getRelative),e.sample&&(this._sample=e.sample,this._approximatedWordSpaces=we.approximateWordSpaces(this._optimalChars,this._sample)),this.updateMultipliers(),this._optimalLineLength=this.getOptimalLineLength()}get baseFontSize(){return this._baseFontSize}get minimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._minDivider!==null?Math.round(this._optimalLineLength/this._minDivider+this._padding)/(this._getRelative?this._baseFontSize:1):null}get maximalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._maxMultiplier!==null?Math.round(this._optimalLineLength*this._maxMultiplier+this._padding)/(this._getRelative?this._baseFontSize:1):null}get optimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),Math.round(this._optimalLineLength+this._padding)/(this._getRelative?this._baseFontSize:1)}get all(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),{min:this.minimalLineLength,max:this.maximalLineLength,optimal:this.optimalLineLength,baseFontSize:this._baseFontSize}}static approximateWordSpaces(e,t){let n=0;if(t&&t.length>=e){const i=t.match(/([\s]+)/gi);n=(i?i.length:0)*(e/t.length)}return n}getLineLengthFallback(){const e=this._letterSpacing*(this._optimalChars-1),t=this._wordSpacing*this._approximatedWordSpaces;return this._optimalChars*(this._baseFontSize*.5)+e+t}getOptimalLineLength(){if(this._fontFace){if(typeof this._fontFace=="string")return this.measureText(this._fontFace);{const e=new FontFace(this._fontFace.name,`url(${this._fontFace.url})`);e.load().then(()=>(document.fonts.add(e),this.measureText(e.family)),t=>{})}}return this.getLineLengthFallback()}measureText(e){const t=this._canvas.getContext("2d");if(t&&e){let n=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(t.font=`${this._baseFontSize}px ${e}`,this._sample&&this._sample.length>=this._optimalChars&&(n=this._sample.slice(0,this._optimalChars)),Object.hasOwn(t,"letterSpacing")&&Object.hasOwn(t,"wordSpacing"))return t.letterSpacing=this._letterSpacing.toString()+"px",t.wordSpacing=this._wordSpacing.toString()+"px",t.measureText(n).width;{const i=this._letterSpacing*(this._optimalChars-1),o=this._wordSpacing*we.approximateWordSpaces(this._optimalChars,this._sample);return t.measureText(n).width+i+o}}else return this.getLineLengthFallback()}}const ci=()=>typeof navigator>"u"?"":navigator.userAgent||"",hi=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class di{constructor(){const e=hi(),t=ci(),n=o=>(typeof o=="string"||typeof o=="number")&&o?String(o).replace(/_/g,".").split(".").map(a=>parseInt(a)||0):[],i=(o="")=>{if(!o)return[];const a=new RegExp("^.*"+o+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return a.test(t)?n(t.replace(a,"$1")):[]};this.OS=(o=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(o.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?o.iOS=o.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?o.iOS=o.iPadOS=i():o.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?o.Windows=(a=>a[0]!==6||!a[1]?a:a[1]===1?[7]:a[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(t)?o.Android=i("Android"):/CrOS/.test(t)?o.ChromeOS=i():/X11;/.test(t)&&(o.Linux=i()),o))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(o=>(a=>{const s=o.platform,l=o.platformVersion;if(!(!s||!l)){if(/^i(OS|P(hone|od touch))$/.test(s))a.iOS=n(l);else if(/^iPad(OS)?$/.test(s))a.iOS=a.iPadOS=n(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(s))document.ontouchend!==void 0?a.iOS=a.iPadOS=n():a.macOS=n(l);else if(/^(Microsoft )?Windows$/.test(s))a.Windows=n(l);else if(/^(Google )?Android$/.test(s))a.Android=n(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(s))a.ChromeOS=n(l);else if(/^(Linux|Ubuntu|X11)$/.test(s))a.Linux=n(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,a)}})({})),this.UA=(o=>{let a=!1;if(e&&Array.isArray(e.brands)){const s=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});s["Google Chrome"]?(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Chrome=s["Google Chrome"]):s["Microsoft Edge"]?(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Edge=s["Microsoft Edge"]):s.Opera&&(a=!0,o.Blink=o.Chromium=s.Chromium||[],o.Opera=s.Opera)}return a||(/ Gecko\/\d/.test(t)?(o.Gecko=i("rv"),/ Waterfox\/\d/.test(t)?o.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(t)&&(o.Firefox=i("Firefox"))):/ Edge\/\d/.test(t)?(o.EdgeHTML=i("Edge"),o.Edge=o.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(o.Blink=o.Chromium=(s=>s[0]?s:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(t)?o.Edge=(s=>s[0]?s:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(t)?o.Opera=i("OPR"):/ Vivaldi\/\d/.test(t)?o.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(t)?o.Silk=i("Silk"):/ UCBrowser\/\d/.test(t)?o.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(t)?o.Phoebe=i("Phoebe"):o.Chrome=(s=>s[0]?s:o.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(t)?(o.WebKit=i("AppleWebKit"),/ CriOS \d/.test(t)?o.Chrome=i("CriOS"):/ FxiOS \d/.test(t)?o.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(t)?o.Edge=i("EdgiOS"):/ Version\/\d/.test(t)&&(o.Safari=i("Version"))):/ Trident\/\d/.test(t)&&(o.Trident=i("Trident"),o.InternetExplorer=(s=>s[0]?s:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(o.Facebook=i("FBAV")),/ Line\/\d/.test(t)&&(o.LINE=i("Line")),o})({}),this.Env={get:()=>[this.OS,this.UA].reduce((o,a)=>{for(const s in a)a[s]&&o.push(s);return o},[])}}}class Qo extends di{get iOSRequest(){const e=hi(),t=ci();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 Y=new di,L=new Qo;function se(r){const e=r.languages?.[0]?.toLowerCase(),t=r.readingProgression;if(e){if(e.startsWith("zh")||e.startsWith("ja")||e.startsWith("ko"))return t===M.rtl?"cjk-vertical":"cjk-horizontal";if(e.startsWith("mn-mong"))return"mongolian-vertical";if(e.startsWith("ar")||e.startsWith("fa")||e.startsWith("he"))return"rtl"}return"ltr"}class Kt{constructor(e,t){this.config=e,this.onUpdate=t,this.unsubs=[],this.conditionValues=new Map}setup(){let e=!0;this.config.forEach(t=>t.keyCombos.forEach(n=>{if(n.condition){const i=n.condition.subscribe(o=>{this.conditionValues.set(n,o),e||this.onUpdate(this.buildSerializable())});this.unsubs.push(i)}})),e=!1,this.onUpdate(this.buildSerializable())}buildSerializable(){return this.config.map(e=>({...e,keyCombos:e.keyCombos.filter(t=>!t.condition||this.conditionValues.get(t)===!0).map(({condition:t,...n})=>n)})).filter(e=>e.keyCombos.length>0)}destroy(){this.unsubs.forEach(e=>e()),this.unsubs=[],this.conditionValues.clear()}}class ui{constructor(e,t={},n=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.frame.style.backgroundColor="#FFFFFF",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...n]}async load(e=[]){return new Promise((t,n)=>{if(this.loader){const i=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(i)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(i,e),this.currModules=e,this.comms=void 0;try{t(i)}catch{}return}this.frame.onload=()=>{const i=this.frame.contentWindow;this.loader=new be(i,e),this.currModules=e;try{t(i)}catch{}},this.frame.onerror=i=>{try{n(i)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Kt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){this.conditionBridge?.destroy(),await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),new Promise((t,n)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const i=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,Y.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,i):i()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new ve(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get msg(){return this.comms}get ldr(){return this.loader}}class mi{constructor(e,t,n,i={},o=[]){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.currentCssProperties=t,this.injector=n,this.contentProtectionConfig=i,this.keyboardPeripheralsConfig=[...o]}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>{this.injector?.releaseBlobUrl?.(a),URL.revokeObjectURL(a)}),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}async update(e,t,n){const i=e.readingOrder.items;let o=i.findIndex(l=>l.href===t.href);if(o<0)throw Error(`Locator not found in reading order: ${t.href}`);const a=i[o].href;this.inprogress.has(a)&&await this.inprogress.get(a);const s=new Promise(async(l,c)=>{const h=[],u=[];e.readingOrder.items.forEach((d,p)=>{p!==o&&p!==o-1&&p!==o+1&&(h.includes(d.href)||h.push(d.href)),p===o&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const P=this.blobs.get(d);P&&(this.injector?.releaseBlobUrl?.(P),URL.revokeObjectURL(P),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const P=this.pool.get(d);if(!this.blobs.has(d))await P.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await P.load(n);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const A=await new si(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,A)}const b=new ui(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==a&&await b.hide(),this.container.appendChild(b.iframe),await b.load(n),this.pool.set(d,b)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=this.pool.get(a);f?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),f&&await f.load(n),f&&await f.show(t.locations.progression),this._currentFrame=f),l()});this.inprogress.set(a,s),await s,this.inprogress.delete(a)}setCSSProperties(e){if(!((n,i)=>{const o=Object.keys(n),a=Object.keys(i);if(o.length!==a.length)return!1;for(const s of o)if(n[s]!==i[s])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(n=>{n.setCSSProperties(e)});for(const n of this.blobs.keys())this.pendingUpdates.set(n,{inPool:this.pool.has(n)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}}var Xt,pi;function er(){if(pi)return Xt;pi=1;function r(i){if(typeof i!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function e(i,o){for(var a="",s=0,l=-1,c=0,h,u=0;u<=i.length;++u){if(u<i.length)h=i.charCodeAt(u);else{if(h===47)break;h=47}if(h===47){if(!(l===u-1||c===1))if(l!==u-1&&c===2){if(a.length<2||s!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var m=a.lastIndexOf("/");if(m!==a.length-1){m===-1?(a="",s=0):(a=a.slice(0,m),s=a.length-1-a.lastIndexOf("/")),l=u,c=0;continue}}else if(a.length===2||a.length===1){a="",s=0,l=u,c=0;continue}}o&&(a.length>0?a+="/..":a="..",s=2)}else a.length>0?a+="/"+i.slice(l+1,u):a=i.slice(l+1,u),s=u-l-1;l=u,c=0}else h===46&&c!==-1?++c:c=-1}return a}function t(i,o){var a=o.dir||o.root,s=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+s:a+i+s:s}var n={resolve:function(){for(var o="",a=!1,s,l=arguments.length-1;l>=-1&&!a;l--){var c;l>=0?c=arguments[l]:(s===void 0&&(s=process.cwd()),c=s),r(c),c.length!==0&&(o=c+"/"+o,a=c.charCodeAt(0)===47)}return o=e(o,!a),a?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(r(o),o.length===0)return".";var a=o.charCodeAt(0)===47,s=o.charCodeAt(o.length-1)===47;return o=e(o,!a),o.length===0&&!a&&(o="."),o.length>0&&s&&(o+="/"),a?"/"+o:o},isAbsolute:function(o){return r(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,a=0;a<arguments.length;++a){var s=arguments[a];r(s),s.length>0&&(o===void 0?o=s:o+="/"+s)}return o===void 0?".":n.normalize(o)},relative:function(o,a){if(r(o),r(a),o===a||(o=n.resolve(o),a=n.resolve(a),o===a))return"";for(var s=1;s<o.length&&o.charCodeAt(s)===47;++s);for(var l=o.length,c=l-s,h=1;h<a.length&&a.charCodeAt(h)===47;++h);for(var u=a.length,m=u-h,f=c<m?c:m,d=-1,p=0;p<=f;++p){if(p===f){if(m>f){if(a.charCodeAt(h+p)===47)return a.slice(h+p+1);if(p===0)return a.slice(h+p)}else c>f&&(o.charCodeAt(s+p)===47?d=p:p===0&&(d=0));break}var b=o.charCodeAt(s+p),P=a.charCodeAt(h+p);if(b!==P)break;b===47&&(d=p)}var A="";for(p=s+d+1;p<=l;++p)(p===l||o.charCodeAt(p)===47)&&(A.length===0?A+="..":A+="/..");return A.length>0?A+a.slice(h+d):(h+=d,a.charCodeAt(h)===47&&++h,a.slice(h))},_makeLong:function(o){return o},dirname:function(o){if(r(o),o.length===0)return".";for(var a=o.charCodeAt(0),s=a===47,l=-1,c=!0,h=o.length-1;h>=1;--h)if(a=o.charCodeAt(h),a===47){if(!c){l=h;break}}else c=!1;return l===-1?s?"/":".":s&&l===1?"//":o.slice(0,l)},basename:function(o,a){if(a!==void 0&&typeof a!="string")throw new TypeError('"ext" argument must be a string');r(o);var s=0,l=-1,c=!0,h;if(a!==void 0&&a.length>0&&a.length<=o.length){if(a.length===o.length&&a===o)return"";var u=a.length-1,m=-1;for(h=o.length-1;h>=0;--h){var f=o.charCodeAt(h);if(f===47){if(!c){s=h+1;break}}else m===-1&&(c=!1,m=h+1),u>=0&&(f===a.charCodeAt(u)?--u===-1&&(l=h):(u=-1,l=m))}return s===l?l=m:l===-1&&(l=o.length),o.slice(s,l)}else{for(h=o.length-1;h>=0;--h)if(o.charCodeAt(h)===47){if(!c){s=h+1;break}}else l===-1&&(c=!1,l=h+1);return l===-1?"":o.slice(s,l)}},extname:function(o){r(o);for(var a=-1,s=0,l=-1,c=!0,h=0,u=o.length-1;u>=0;--u){var m=o.charCodeAt(u);if(m===47){if(!c){s=u+1;break}continue}l===-1&&(c=!1,l=u+1),m===46?a===-1?a=u:h!==1&&(h=1):a!==-1&&(h=-1)}return a===-1||l===-1||h===0||h===1&&a===l-1&&a===s+1?"":o.slice(a,l)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return t("/",o)},parse:function(o){r(o);var a={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return a;var s=o.charCodeAt(0),l=s===47,c;l?(a.root="/",c=1):c=0;for(var h=-1,u=0,m=-1,f=!0,d=o.length-1,p=0;d>=c;--d){if(s=o.charCodeAt(d),s===47){if(!f){u=d+1;break}continue}m===-1&&(f=!1,m=d+1),s===46?h===-1?h=d:p!==1&&(p=1):h!==-1&&(p=-1)}return h===-1||m===-1||p===0||p===1&&h===m-1&&h===u+1?m!==-1&&(u===0&&l?a.base=a.name=o.slice(1,m):a.base=a.name=o.slice(u,m)):(u===0&&l?(a.name=o.slice(1,h),a.base=o.slice(1,m)):(a.name=o.slice(u,h),a.base=o.slice(u,m)),a.ext=o.slice(h,m)),u>0?a.dir=o.slice(0,u-1):l&&(a.dir="/"),a},sep:"/",delimiter:":",win32:null,posix:null};return n.posix=n,Xt=n,Xt}var dt=er();const tr={experimentalHeaderFiltering:{description:"Attempts to filter out paragraphs that are implicitly headings or part of headers",scope:"RS",value:"readium-experimentalHeaderFiltering-on"},experimentalZoom:{description:"Attempts to filter out elements that are sized using viewport units and should not be scaled directly e.g. tables, images, iframes, etc.",scope:"RS",value:"readium-experimentalZoom-on"}},nr={default:{disabled:[],added:[]},rtl:{disabled:["bodyHyphens","a11yNormalize","letterSpacing"],added:[]},"cjk-horizontal":{disabled:["textAlign","bodyHyphens","a11yNormalize","ligatures","paraIndent","wordSpacing"],added:["noRuby"]},"cjk-vertical":{disabled:["colCount","textAlign","bodyHyphens","a11yNormalize","ligatures","paraIndent","wordSpacing"],added:["noRuby"]}},ir={default:{baseFontFamily:"var(--RS__oldStyleTf)",lineHeightCompensation:1},am:{baseFontFamily:"Kefa, Nyala, Roboto, Noto, 'Noto Sans Ethiopic', serif",lineHeightCompensation:1.167},ar:{baseFontFamily:"'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif"},bn:{baseFontFamily:"'Kohinoor Bangla', 'Bangla Sangam MN', Vrinda, Roboto, Noto, 'Noto Sans Bengali', sans-serif",lineHeightCompensation:1.067},bo:{baseFontFamily:"Kailasa, 'Microsoft Himalaya', Roboto, Noto, 'Noto Sans Tibetan', sans-serif"},chr:{baseFontFamily:"'Plantagenet Cherokee', Roboto, Noto, 'Noto Sans Cherokee'",lineHeightCompensation:1.167},fa:{baseFontFamily:"'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif"},gu:{baseFontFamily:"'Gujarati Sangam MN', 'Nirmala UI', Shruti, Roboto, Noto, 'Noto Sans Gujarati', sans-serif",lineHeightCompensation:1.167},he:{baseFontFamily:"'New Peninim MT', 'Arial Hebrew', Gisha, 'Times New Roman', Roboto, Noto, 'Noto Sans Hebrew', sans-serif",lineHeightCompensation:1.1},hi:{baseFontFamily:"'Kohinoor Devanagari', 'Devanagari Sangam MN', Kokila, 'Nirmala UI', Roboto, Noto, 'Noto Sans Devanagari', sans-serif",lineHeightCompensation:1.1},hy:{baseFontFamily:"Mshtakan, Sylfaen, Roboto, Noto, 'Noto Serif Armenian', serif"},iu:{baseFontFamily:"'Euphemia UCAS', Euphemia, Roboto, Noto, 'Noto Sans Canadian Aboriginal', sans-serif"},ja:{baseFontFamily:"YuGothic, 'Hiragino Maru Gothic ProN', 'Hiragino Sans', 'Yu Gothic UI', 'Meiryo UI', 'MS Gothic', Roboto, Noto, 'Noto Sans CJK JP', sans-serif",lineHeightCompensation:1.167},km:{baseFontFamily:"'Khmer Sangam MN', 'Leelawadee UI', 'Khmer UI', Roboto, Noto, 'Noto Sans Khmer', sans-serif",lineHeightCompensation:1.067},kn:{baseFontFamily:"'Kannada Sangam MN', 'Nirmala UI', Tunga, Roboto, Noto, 'Noto Sans Kannada', sans-serif",lineHeightCompensation:1.1},ko:{baseFontFamily:"'Nanum Gothic', 'Apple SD Gothic Neo', 'Malgun Gothic', Roboto, Noto, 'Noto Sans CJK KR', sans-serif",lineHeightCompensation:1.167},lo:{baseFontFamily:"'Lao Sangam MN', 'Leelawadee UI', 'Lao UI', Roboto, Noto, 'Noto Sans Lao', sans-serif"},ml:{baseFontFamily:"'Malayalam Sangam MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Malayalam', sans-serif",lineHeightCompensation:1.067},or:{baseFontFamily:"'Oriya Sangam MN', 'Nirmala UI', Kalinga, Roboto, Noto, 'Noto Sans Oriya', sans-serif",lineHeightCompensation:1.167},pa:{baseFontFamily:"'Gurmukhi MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Gurmukhi', sans-serif",lineHeightCompensation:1.1},si:{baseFontFamily:"'Sinhala Sangam MN', 'Nirmala UI', 'Iskoola Pota', Roboto, Noto, 'Noto Sans Sinhala', sans-serif",lineHeightCompensation:1.167},ta:{baseFontFamily:"'Tamil Sangam MN', 'Nirmala UI', Latha, Roboto, Noto, 'Noto Sans Tamil', sans-serif",lineHeightCompensation:1.067},te:{baseFontFamily:"'Kohinoor Telugu', 'Telugu Sangam MN', 'Nirmala UI', Gautami, Roboto, Noto, 'Noto Sans Telugu', sans-serif"},th:{baseFontFamily:"Thonburi, 'Leelawadee UI', 'Cordia New', Roboto, Noto, 'Noto Sans Thai', sans-serif",lineHeightCompensation:1.067},zh:{baseFontFamily:"'方体', 'PingFang SC', '黑体', 'Heiti SC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK SC', sans-serif",lineHeightCompensation:1.167},"zh-Hant":{baseFontFamily:"'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif",lineHeightCompensation:1.167},"zh-TW":{baseFontFamily:"'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif",lineHeightCompensation:1.167},"zh-HK":{baseFontFamily:"'方體', 'PingFang HK', '方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif",lineHeightCompensation:1.167}},ut=tr,or=nr,rr=ir;var J=(r=>(r.start="start",r.left="left",r.right="right",r.justify="justify",r))(J||{});const le={range:[0,100],step:1},Ue={range:[.7,4],step:.05},ee={range:[100,1e3],step:100},Te={range:[50,250],step:10},Ne={range:[0,1],step:.125},Me={range:[1,2.5],step:.1},ce={range:[20,100],step:1},Ie={range:[0,3],step:.25},He={range:[0,3],step:.25},De={range:[0,2],step:.125},We={range:[.7,4],step:.05},Be={range:[0,1],step:.1},je={range:[.5,4],step:.1},te={range:[5,60],step:5};class Ge{constructor(){}toFlag(e){return`readium-${e}-on`}toUnitless(e){return e.toString()}toPercentage(e,t=!1){return t||e>0&&e<=1?`${Math.round(e*100)}%`:`${e}%`}toVw(e){const t=Math.round(e*100);return`${Math.min(t,100)}vw`}toVh(e){const t=Math.round(e*100);return`${Math.min(t,100)}vh`}toPx(e){return`${e}px`}toRem(e){return`${e}rem`}}class Yt extends Ge{constructor(e){super(),this.a11yNormalize=e.a11yNormalize??null,this.bodyHyphens=e.bodyHyphens??null,this.fontFamily=e.fontFamily??null,this.fontWeight=e.fontWeight??null,this.iOSPatch=e.iOSPatch??null,this.iPadOSPatch=e.iPadOSPatch??null,this.letterSpacing=e.letterSpacing??null,this.ligatures=e.ligatures??null,this.lineHeight=e.lineHeight??null,this.noRuby=e.noRuby??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.textAlign=e.textAlign??null,this.wordSpacing=e.wordSpacing??null,this.zoom=e.zoom??null}toCSSProperties(){const e={};return this.a11yNormalize&&(e["--USER__a11yNormalize"]=this.toFlag("a11y")),this.bodyHyphens&&(e["--USER__bodyHyphens"]=this.bodyHyphens),this.fontFamily&&(e["--USER__fontFamily"]=this.fontFamily),this.fontWeight!=null&&(e["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.iOSPatch&&(e["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(e["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(e["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(e["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(e["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.noRuby&&(e["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(e["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.textAlign&&(e["--USER__textAlign"]=this.textAlign),this.wordSpacing!=null&&(e["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),this.zoom!==null&&(e["--USER__zoom"]=this.toPercentage(this.zoom,!0)),e}}class gi extends Ge{constructor(e){super(),this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=ut[t].value}),e}}class fi{constructor(e){this.rsProperties=e.rsProperties,this.userProperties=e.userProperties}update(e){e.experiments&&(this.rsProperties.experiments=e.experiments);const t={a11yNormalize:e.textNormalization,bodyHyphens:typeof e.hyphens!="boolean"?null:e.hyphens?"auto":"none",fontFamily:e.fontFamily,fontWeight:e.fontWeight,iOSPatch:e.iOSPatch,iPadOSPatch:e.iPadOSPatch,letterSpacing:e.letterSpacing,ligatures:typeof e.ligatures!="boolean"?null:e.ligatures?"common-ligatures":"none",lineHeight:e.lineHeight,noRuby:e.noRuby,paraIndent:e.paragraphIndent,paraSpacing:e.paragraphSpacing,textAlign:e.textAlign,wordSpacing:e.wordSpacing,zoom:e.zoom};this.userProperties=new Yt(t)}}function yi(r,e){return r==null||e==null||r<=e?r:void 0}function _i(r,e){return r==null||e==null||r>=e?r:void 0}function I(r){return typeof r=="string"?r:r===null?null:void 0}function R(r){return typeof r=="boolean"||r==null?r:void 0}function Ve(r,e){if(r!==void 0)return r===null?null:e[r]!==void 0?r:void 0}function he(r){return typeof r=="boolean"||typeof r=="number"&&r>=0?r:r===null?null:void 0}function v(r){if(r!==void 0)return r===null?null:r<0?void 0:r}function T(r,e){if(r===void 0)return;if(r===null)return null;const t=Math.min(...e),n=Math.max(...e);return r>=t&&r<=n?r:void 0}function mt(r,e){return r===void 0?e:r}function qt(r){if(r!==void 0)return r===null?null:r.filter(e=>e in ut)}class Re{constructor(e={}){this.fontFamily=I(e.fontFamily),this.fontWeight=T(e.fontWeight,ee.range),this.hyphens=R(e.hyphens),this.iOSPatch=R(e.iOSPatch),this.iPadOSPatch=R(e.iPadOSPatch),this.letterSpacing=v(e.letterSpacing),this.ligatures=R(e.ligatures),this.lineHeight=v(e.lineHeight),this.noRuby=R(e.noRuby),this.paragraphIndent=v(e.paragraphIndent),this.paragraphSpacing=v(e.paragraphSpacing),this.textAlign=Ve(e.textAlign,J),this.textNormalization=R(e.textNormalization),this.wordSpacing=v(e.wordSpacing),this.zoom=T(e.zoom,We.range)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Re(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(t[n]=e[n]);return new Re(t)}}class Si{constructor(e){this.fontFamily=I(e.fontFamily)||null,this.fontWeight=T(e.fontWeight,ee.range)||null,this.hyphens=R(e.hyphens)??null,this.iOSPatch=e.iOSPatch===!1?!1:(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:L.OS.iPadOS&&L.iOSRequest==="desktop",this.letterSpacing=v(e.letterSpacing)||null,this.ligatures=R(e.ligatures)??null,this.lineHeight=v(e.lineHeight)||null,this.noRuby=R(e.noRuby)??!1,this.paragraphIndent=v(e.paragraphIndent)??null,this.paragraphSpacing=v(e.paragraphSpacing)??null,this.textAlign=Ve(e.textAlign,J)||null,this.textNormalization=R(e.textNormalization)??!1,this.wordSpacing=v(e.wordSpacing)||null,this.zoom=T(e.zoom,We.range)||1,this.experiments=qt(e.experiments)??null}}class Jt{constructor(e,t,n){this.fontFamily=null,this.fontWeight=null,this.hyphens=null,this.iOSPatch=null,this.iPadOSPatch=null,this.letterSpacing=null,this.ligatures=null,this.lineHeight=null,this.noRuby=null,this.paragraphIndent=null,this.paragraphSpacing=null,this.textAlign=null,this.textNormalization=null,this.wordSpacing=null,n&&(this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.iOSPatch=e.iOSPatch===!1?!1:e.iOSPatch===!0?(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?L.OS.iPadOS&&L.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.textAlign=e.textAlign||t.textAlign||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null),this.zoom=e.zoom!==void 0?e.zoom:t.zoom!==void 0?t.zoom:null,this.experiments=t.experiments||null}}class U{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i}){this._value=e,this._effectiveValue=t,this._isEffective=n,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}}class O extends U{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}toggle(){this._value=!this._value,this._onChange(this._value)}}class Zt extends U{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i,supportedValues:o}){super({initialValue:e,effectiveValue:t,isEffective:n,onChange:i}),this._supportedValues=o}set value(e){if(e&&!this._supportedValues.includes(e))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 effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedValues(){return this._supportedValues}clear(){this._value=null}}class k extends U{constructor({initialValue:e=null,effectiveValue:t,isEffective:n,onChange:i,supportedRange:o,step:a}){super({initialValue:e,effectiveValue:t,isEffective:n,onChange:i}),this._supportedRange=o,this._step=a,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(e){if(e&&(e<this._supportedRange[0]||e>this._supportedRange[1]))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 effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value&&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&&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()}clear(){this._value=null}}class Qt{constructor(e,t,n){this.preferences=e,this.settings=t,this.metadata=n}clear(){this.preferences=new Re({})}updatePreference(e,t){this.preferences[e]=t}get isDisplayTransformable(){return this.metadata?.accessibility?.feature?.some(e=>e.value===Ze.DISPLAY_TRANSFORMABILITY.value)??!1}get fontFamily(){return new U({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontFamily",e??null)}})}get fontWeight(){return new k({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:ee.range,step:ee.step})}get hyphens(){return new O({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("hyphens",e??null)}})}get iOSPatch(){return new O({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:!0,onChange:e=>{this.updatePreference("iOSPatch",e??null)}})}get iPadOSPatch(){return new O({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:!0,onChange:e=>{this.updatePreference("iPadOSPatch",e??null)}})}get letterSpacing(){return new k({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Ne.range,step:Ne.step})}get ligatures(){return new O({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("ligatures",e??null)}})}get lineHeight(){return new k({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:Me.range,step:Me.step})}get noRuby(){return new O({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("noRuby",e??null)}})}get paragraphIndent(){return new k({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Ie.range,step:Ie.step})}get paragraphSpacing(){return new k({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:He.range,step:He.step})}get textAlign(){return new Zt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||J.start,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(J)})}get textNormalization(){return new O({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textNormalization",e??null)}})}get wordSpacing(){return new k({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:De.range,step:De.step})}get zoom(){return new k({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:e=>{this.updatePreference("zoom",e??null)},supportedRange:We.range,step:We.step})}}const bi=r=>{if("blob"in r&&r.blob.type)return r.blob.type;if(r.as==="script")return"text/javascript";if(r.as==="link"&&"url"in r){const e=r.url.toLowerCase();if(e.endsWith(".css"))return"text/css";if([".js",".mjs",".cjs"].some(t=>e.endsWith(t)))return"text/javascript"}},vi=(r,e)=>{e.attributes&&Object.entries(e.attributes).forEach(([t,n])=>{t==="type"||t==="rel"||t==="href"||t==="src"||n!=null&&(typeof n=="boolean"?n&&r.setAttribute(t,""):r.setAttribute(t,n))})},ar=(r,e,t)=>{const n=r.createElement("script");n.dataset.readium="true",e.id&&(n.id=e.id);const i=e.type||bi(e);return i&&(n.type=i),vi(n,e),n.src=t,n},wi=(r,e,t)=>{const n=r.createElement("link");n.dataset.readium="true",e.id&&(n.id=e.id),e.rel&&(n.rel=e.rel);const i=e.type||bi(e);return i&&(n.type=i),vi(n,e),n.href=t,n};class en{constructor(e){this.blobStore=new Map,this.createdBlobUrls=new Set,this.allowedDomains=[],this.injectableIdCounter=0,this.allowedDomains=(e.allowedDomains||[]).map(t=>{try{return new URL(t),t}catch{throw new Error(`Invalid allowed domain: "${t}". Must be a valid URL (e.g., "https://fonts.googleapis.com").`)}}),this.rules=e.rules.map(t=>{const n={...t};return t.prepend&&(n.prepend=t.prepend.map(i=>({...i,id:i.id||`injectable-${this.injectableIdCounter++}`})).reverse()),t.append&&(n.append=t.append.map(i=>({...i,id:i.id||`injectable-${this.injectableIdCounter++}`}))),n})}dispose(){for(const e of this.createdBlobUrls)try{URL.revokeObjectURL(e)}catch(t){console.warn("Failed to revoke blob URL:",e,t)}this.createdBlobUrls.clear()}getAllowedDomains(){return[...this.allowedDomains]}async injectForDocument(e,t){for(const n of this.rules)this.matchesRule(n,t)&&await this.applyRule(e,n)}matchesRule(e,t){const n=t.href;return e.resources.some(i=>i instanceof RegExp?i.test(n):n===i)}async getOrCreateBlobUrl(e){const t=e.id;if(this.blobStore.has(t)){const n=this.blobStore.get(t);return n.refCount++,n.url}if("blob"in e){const n=URL.createObjectURL(e.blob);return this.blobStore.set(t,{url:n,refCount:1}),this.createdBlobUrls.add(n),n}throw new Error("Resource must have a blob property")}async releaseBlobUrl(e){if(!this.createdBlobUrls.has(e))return;const t=Array.from(this.blobStore.values()).find(n=>n.url===e);if(t&&(t.refCount--,t.refCount<=0)){URL.revokeObjectURL(e),this.createdBlobUrls.delete(e);for(const[n,i]of this.blobStore.entries())if(i.url===e){this.blobStore.delete(n);break}}}async getResourceUrl(e,t){if("url"in e){const n=new URL(e.url,t.baseURI).toString();if(!this.isValidUrl(n,t))throw new Error(`Invalid URL: Only HTTPS, data:, blob:, or localhost HTTP URLs are allowed. Got: ${e.url}`);return n}else return this.getOrCreateBlobUrl(e)}createPreloadLink(e,t,n){if(t.as!=="link"||t.rel!=="preload")return;const i={...t,rel:"preload",attributes:{...t.attributes,as:t.as}},o=wi(e,i,n);e.head.appendChild(o)}createElement(e,t,n){if(t.as==="script")return ar(e,t,n);if(t.as==="link")return wi(e,t,n);throw new Error(`Unsupported element type: ${t.as}`)}async applyRule(e,t){const n=[],i=t.prepend?t.prepend.filter(a=>!a.condition||a.condition(e)):[],o=t.append?t.append.filter(a=>!a.condition||a.condition(e)):[];try{for(const a of i)await this.processInjectable(a,e,n,"prepend");for(const a of o)await this.processInjectable(a,e,n,"append")}catch(a){for(const{element:s,url:l}of n)try{s.remove(),await this.releaseBlobUrl(l)}catch(c){console.error("Error during cleanup:",c)}throw a}}async processInjectable(e,t,n,i){const o=e.target==="body"?t.body:t.head;if(!o)return;let a=null;try{if(a=await this.getResourceUrl(e,t),e.rel==="preload"&&"url"in e)this.createPreloadLink(t,e,a);else{const s=this.createElement(t,e,a);n.push({element:s,url:a}),i==="prepend"?o.prepend(s):o.append(s)}}catch(s){throw console.error("Failed to process resource:",s),a&&"blob"in e&&await this.releaseBlobUrl(a),s}}isValidUrl(e,t){try{const n=new URL(e,t.baseURI);if(n.protocol==="data:"||n.protocol==="blob:"&&this.createdBlobUrls.has(e))return!0;if(this.allowedDomains.length>0){const i=n.origin;return this.allowedDomains.some(o=>{const a=new URL(o).origin;return i===a})}return!1}catch{return!1}}}const Pe=r=>r.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),$e=r=>r.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," "),sr=`/*!
97
+ * Readium CSS v.2.0.4
98
98
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
99
99
  * Use of this source code is governed by a BSD-style license which is detailed in the
100
100
  * LICENSE file present in the project repository where this source code is maintained.
@@ -143,11 +143,11 @@
143
143
  :root[style*="--USER__bodyHyphens"] li,
144
144
  :root[style*="--USER__bodyHyphens"] div,
145
145
  :root[style*="--USER__bodyHyphens"] dd{
146
- -webkit-hyphens:inherit;
147
- -moz-hyphens:inherit;
148
- -ms-hyphens:inherit;
149
- -epub-hyphens:inherit;
150
- hyphens:inherit;
146
+ -webkit-hyphens:var(--USER__bodyHyphens) !important;
147
+ -moz-hyphens:var(--USER__bodyHyphens) !important;
148
+ -ms-hyphens:var(--USER__bodyHyphens) !important;
149
+ -epub-hyphens:var(--USER__bodyHyphens) !important;
150
+ hyphens:var(--USER__bodyHyphens) !important;
151
151
  }
152
152
 
153
153
  :root[style*="--USER__fontFamily"]{
@@ -227,7 +227,7 @@
227
227
  :root[style*="--USER__lineHeight"] p,
228
228
  :root[style*="--USER__lineHeight"] li,
229
229
  :root[style*="--USER__lineHeight"] div{
230
- line-height:inherit;
230
+ line-height:var(--USER__lineHeight) !important;
231
231
  }
232
232
 
233
233
  :root[style*="--USER__paraSpacing"] p{
@@ -247,8 +247,7 @@
247
247
  text-indent:var(--USER__paraIndent) !important;
248
248
  }
249
249
 
250
- :root[style*="--USER__paraIndent"] p *,
251
- :root[style*="--USER__paraIndent"] p:first-letter{
250
+ :root[style*="--USER__paraIndent"] p *{
252
251
  text-indent:0 !important;
253
252
  }
254
253
 
@@ -263,7 +262,7 @@
263
262
  :root[style*="--USER__wordSpacing"] div,
264
263
  :root[style*="--USER__wordSpacing"] dt,
265
264
  :root[style*="--USER__wordSpacing"] dd{
266
- word-spacing:var(--USER__wordSpacing);
265
+ word-spacing:var(--USER__wordSpacing) !important;
267
266
  }
268
267
 
269
268
  :root[style*="--USER__letterSpacing"] h1,
@@ -277,8 +276,8 @@
277
276
  :root[style*="--USER__letterSpacing"] div,
278
277
  :root[style*="--USER__letterSpacing"] dt,
279
278
  :root[style*="--USER__letterSpacing"] dd{
280
- letter-spacing:var(--USER__letterSpacing);
281
- font-variant:none;
279
+ letter-spacing:var(--USER__letterSpacing) !important;
280
+ font-variant:none !important;
282
281
  }
283
282
 
284
283
  :root[style*="--USER__fontWeight"] body{
@@ -367,11 +366,11 @@
367
366
 
368
367
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
369
368
  -webkit-text-zoom:normal;
370
- }`,Pi='!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{_readium_cssSelectorGenerator:()=>Z,default:()=>tt,getCssSelector:()=>X});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="_readium_cssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const s={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1};function u(t){return t instanceof RegExp}function l(t){return["string","function"].includes(typeof t)||u(t)}function a(t){return Array.isArray(t)?t.filter(l):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("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 f(n)?(n!==document&&c("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):S(e)}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function g(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("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((e=>e(t)))}function h(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:S(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function b(t,e){return p(t.map((t=>y(t,e))))}function S(t){return t.ownerDocument.querySelector(":root")}const N=", ",v=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),x=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],w=g(["class","id","ng-*"]);function I({name:t}){return`[${t}]`}function T({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:F(t),value:F(null!=e?e:void 0)}}function C(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t,nodeValue:e},n){const o=n.tagName.toLowerCase();return!(["input","option"].includes(o)&&"value"===t||"src"===t&&(null==e?void 0:e.startsWith("data:"))||w(t))}(e,t))).map(O);return[...e.map(I),...e.map(T)]}function j(t){var e;return(null!==(e=t.getAttribute("class"))&&void 0!==e?e:"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${F(t)}`))}function A(t){var e;const n=null!==(e=t.getAttribute("id"))&&void 0!==e?e:"",o=`#${F(n)}`,r=t.getRootNode({composed:!1});return!v.test(n)&&h([t],o,r)?[o]:[]}function R(t){var e;const n=null===(e=t.parentElement)||void 0===e?void 0:e.children;if(n)for(let e=0;e<n.length;e++)if(n[e]===t)return[`:nth-child(${String(e+1)})`];return[]}function $(t){return[F(t.tagName.toLowerCase())]}function D(t){const e=[...new Set((n=t.map($),[].concat(...n)))];var n;return 0===e.length||e.length>1?[]:[e[0]]}function k(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${String(r+1)})`]}return[]}function*P(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=_(o,t.length-1)}}function _(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),V=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function F(t=""){return CSS?CSS.escape(t):function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:V.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:D,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(C))},nthchild:function(t){return p(t.map(R))},nthoftype:function(t){return p(t.map(k))}},G={tag:$,id:A,class:j,attribute:C,nthchild:R,nthoftype:k};function W(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function*q(t,e){const n={};for(const o of t){const t=e[o];t&&t.length>0&&(n[o]=t)}for(const t of function*(t={}){const e=Object.entries(t);if(0===e.length)return;const n=[{index:e.length-1,partial:{}}];for(;n.length>0;){const t=n.pop();if(!t)break;const{index:o,partial:r}=t;if(o<0){yield r;continue}const[i,c]=e[o];for(let t=c.length-1;t>=0;t--)n.push({index:o-1,partial:Object.assign(Object.assign({},r),{[i]:c[t]})})}}(n))yield B(t)}function B(t={}){const e=[...x];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}function*U(t,e,n="",o){const r=function*(t,e){const n=new Set,o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),s=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[...e];return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){return(0,Y[e])(t)}(t,n),u=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,s),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(u,s);return e[n]=r?Array.from(P(l,{maxResults:i})):l.map((t=>[t])),e}),{})}(t,e);for(const t of function*(t,e){for(const n of function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?function(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(P(t,{maxResults:e}))}(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(W):i}(e))yield*q(n,t)}(o,e))n.has(t)||(n.add(t),yield t)}(t,o);for(const o of function*(t,e){if(""===e)yield*t;else for(const n of t)yield*H([n],e)}(r,n))h(t,o,e)&&(yield o)}function*z(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r)for(const r of U(t,e,n,o))yield{foundElements:t,selector:r}}function J(t){return{value:t,include:!1}}function K({selectors:t,operator:e}){let n=[...x];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{var n;(null!==(n=t[e])&&void 0!==n?n:[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function Q(t,e){return t.map((t=>function(t,e){return[e?":scope":":root",...y(t,e).reverse().map((t=>{var e;const n=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return G[e](t)}(t,e).map(J))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return(null!==(e=n.selectors.nthchild)&&void 0!==e?e:[]).forEach((t=>{t.include=!0})),n})).map(K)].join("")}(t,e))).join(N)}function X(t,e={}){return Z(t,Object.assign(Object.assign({},e),{maxResults:1})).next().value}function*Z(t,e={}){var o;const i=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),c=function(t,e={}){const n=Object.assign(Object.assign({},s),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:a(n.whitelist),blacklist:a(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates),useScope:!!n.useScope,maxResults:m(n.maxResults)};var o}(i[0],e),u=null!==(o=c.root)&&void 0!==o?o:S(i[0]);let l=0;for(const t of function*({elements:t,root:e,rootSelector:n="",options:o}){let r=e,i=n,c=!0;for(;c;){let n=!1;for(const c of z(t,r,i,o)){const{foundElements:o,selector:s}=c;if(n=!0,!h(t,s,e)){r=o[0],i=s;break}yield s}n||(c=!1)}}({elements:i,options:c,root:u,rootSelector:""}))if(yield t,l++,l>=c.maxResults)return;i.length>1&&(yield i.map((t=>X(t,c))).join(N),l++,l>=c.maxResults)||(yield Q(i,c.useScope?u:void 0))}const tt=X;return e})()));',ir=`// WebPub-specific setup - no execution blocking needed
369
+ }`,Ri='!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var o in n)t.o(n,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:n[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return"object"==typeof t&&null!==t&&t.nodeType===Node.ELEMENT_NODE}t.r(e),t.d(e,{_readium_cssSelectorGenerator:()=>Z,default:()=>tt,getCssSelector:()=>X});const o={NONE:"",DESCENDANT:" ",CHILD:" > "},r={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="_readium_cssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const s={selectors:[r.id,r.class,r.tag,r.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY,useScope:!1};function u(t){return t instanceof RegExp}function l(t){return["string","function"].includes(typeof t)||u(t)}function a(t){return Array.isArray(t)?t.filter(l):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("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 f(n)?(n!==document&&c("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):S(e)}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function g(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("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((e=>e(t)))}function h(t,e,n){const o=Array.from(d(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:S(t);const o=[];let r=t;for(;n(r)&&r!==e;)o.push(r),r=r.parentElement;return o}function b(t,e){return p(t.map((t=>y(t,e))))}function S(t){return t.ownerDocument.querySelector(":root")}const N=", ",v=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),x=[r.nthoftype,r.tag,r.id,r.class,r.attribute,r.nthchild],w=g(["class","id","ng-*"]);function I({name:t}){return`[${t}]`}function T({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:F(t),value:F(null!=e?e:void 0)}}function C(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t,nodeValue:e},n){const o=n.tagName.toLowerCase();return!(["input","option"].includes(o)&&"value"===t||"src"===t&&(null==e?void 0:e.startsWith("data:"))||w(t))}(e,t))).map(O);return[...e.map(I),...e.map(T)]}function j(t){var e;return(null!==(e=t.getAttribute("class"))&&void 0!==e?e:"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${F(t)}`))}function A(t){var e;const n=null!==(e=t.getAttribute("id"))&&void 0!==e?e:"",o=`#${F(n)}`,r=t.getRootNode({composed:!1});return!v.test(n)&&h([t],o,r)?[o]:[]}function R(t){var e;const n=null===(e=t.parentElement)||void 0===e?void 0:e.children;if(n)for(let e=0;e<n.length;e++)if(n[e]===t)return[`:nth-child(${String(e+1)})`];return[]}function $(t){return[F(t.tagName.toLowerCase())]}function D(t){const e=[...new Set((n=t.map($),[].concat(...n)))];var n;return 0===e.length||e.length>1?[]:[e[0]]}function k(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${String(r+1)})`]}return[]}function*P(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,o=L(1);for(;o.length<=t.length&&n<e;){n+=1;const e=o.map((e=>t[e]));yield e,o=_(o,t.length-1)}}function _(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return L(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?L(n+1):o}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),V=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function F(t=""){return CSS?CSS.escape(t):function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:V.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:D,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(C))},nthchild:function(t){return p(t.map(R))},nthoftype:function(t){return p(t.map(k))}},G={tag:$,id:A,class:j,attribute:C,nthchild:R,nthoftype:k};function W(t){return t.includes(r.tag)||t.includes(r.nthoftype)?[...t]:[...t,r.tag]}function*q(t,e){const n={};for(const o of t){const t=e[o];t&&t.length>0&&(n[o]=t)}for(const t of function*(t={}){const e=Object.entries(t);if(0===e.length)return;const n=[{index:e.length-1,partial:{}}];for(;n.length>0;){const t=n.pop();if(!t)break;const{index:o,partial:r}=t;if(o<0){yield r;continue}const[i,c]=e[o];for(let t=c.length-1;t>=0;t--)n.push({index:o-1,partial:Object.assign(Object.assign({},r),{[i]:c[t]})})}}(n))yield B(t)}function B(t={}){const e=[...x];return t[r.tag]&&t[r.nthoftype]&&e.splice(e.indexOf(r.tag),1),e.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function H(t,e){return[...t.map((t=>e+o.DESCENDANT+t)),...t.map((t=>e+o.CHILD+t))]}function*U(t,e,n="",o){const r=function*(t,e){const n=new Set,o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=g(n),s=g(o);return function(t){const{selectors:e,includeTag:n}=t,o=[...e];return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){return(0,Y[e])(t)}(t,n),u=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,s),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(u,s);return e[n]=r?Array.from(P(l,{maxResults:i})):l.map((t=>[t])),e}),{})}(t,e);for(const t of function*(t,e){for(const n of function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?function(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(P(t,{maxResults:e}))}(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(W):i}(e))yield*q(n,t)}(o,e))n.has(t)||(n.add(t),yield t)}(t,o);for(const o of function*(t,e){if(""===e)yield*t;else for(const n of t)yield*H([n],e)}(r,n))h(t,o,e)&&(yield o)}function*z(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r)for(const r of U(t,e,n,o))yield{foundElements:t,selector:r}}function J(t){return{value:t,include:!1}}function K({selectors:t,operator:e}){let n=[...x];t[r.tag]&&t[r.nthoftype]&&(n=n.filter((t=>t!==r.tag)));let o="";return n.forEach((e=>{var n;(null!==(n=t[e])&&void 0!==n?n:[]).forEach((({value:t,include:e})=>{e&&(o+=t)}))})),e+o}function Q(t,e){return t.map((t=>function(t,e){return[e?":scope":":root",...y(t,e).reverse().map((t=>{var e;const n=function(t,e,n=o.NONE){const r={};return e.forEach((e=>{Reflect.set(r,e,function(t,e){return G[e](t)}(t,e).map(J))})),{element:t,operator:n,selectors:r}}(t,[r.nthchild],o.CHILD);return(null!==(e=n.selectors.nthchild)&&void 0!==e?e:[]).forEach((t=>{t.include=!0})),n})).map(K)].join("")}(t,e))).join(N)}function X(t,e={}){return Z(t,Object.assign(Object.assign({},e),{maxResults:1})).next().value}function*Z(t,e={}){var o;const i=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),c=function(t,e={}){const n=Object.assign(Object.assign({},s),e);return{selectors:(o=n.selectors,Array.isArray(o)?o.filter((t=>{return e=r,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:a(n.whitelist),blacklist:a(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates),useScope:!!n.useScope,maxResults:m(n.maxResults)};var o}(i[0],e),u=null!==(o=c.root)&&void 0!==o?o:S(i[0]);let l=0;for(const t of function*({elements:t,root:e,rootSelector:n="",options:o}){let r=e,i=n,c=!0;for(;c;){let n=!1;for(const c of z(t,r,i,o)){const{foundElements:o,selector:s}=c;if(n=!0,!h(t,s,e)){r=o[0],i=s;break}yield s}n||(c=!1)}}({elements:i,options:c,root:u,rootSelector:""}))if(yield t,l++,l>=c.maxResults)return;i.length>1&&(yield i.map((t=>X(t,c))).join(N),l++,l>=c.maxResults)||(yield Q(i,c.useScope?u:void 0))}const tt=X;return e})()));',lr=`// WebPub-specific setup - no execution blocking needed
371
370
  window._readium_blockedEvents = [];
372
371
  window._readium_blockEvents = false; // WebPub doesn't need event blocking
373
372
  window._readium_eventBlocker = null;
374
- `,Ri=`(function() {
373
+ `,Pi=`(function() {
375
374
  if(window.onload) window.onload = new Proxy(window.onload, {
376
375
  apply: function(target, receiver, args) {
377
376
  if(!window._readium_blockEvents) {
@@ -384,7 +383,7 @@ window._readium_eventBlocker = null;
384
383
  }
385
384
  });
386
385
  })();
387
- `;function or(r){const e=r.filter(o=>o.mediaType.isHTML).map(o=>o.href),t=e.length>0?e:[/\.html$/,/\.xhtml$/,/\/$/],n=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([Re(Pi)],{type:"text/javascript"})},{id:"webpub-execution",as:"script",target:"head",blob:new Blob([Re(ir)],{type:"text/javascript"})}],i=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([Re(Ri)],{type:"text/javascript"}),condition:o=>!!(o.querySelector("script")||o.querySelector("body[onload]:not(body[onload=''])"))},{id:"readium-css-webpub",as:"link",target:"head",blob:new Blob([$e(nr)],{type:"text/css"}),rel:"stylesheet"}];return[{resources:t,prepend:n,append:i}]}class rr{constructor(e){if(this.detectedTools=new Set,!e.onDetected)throw new Error("onDetected callback is required");this.options=e,this.setupDetection()}isAutomationToolPresent(){const e=window;return e.domAutomation||e.domAutomationController?"Selenium":navigator.webdriver===!0?"Puppeteer/Playwright":e.__webdriver_evaluate||e.__selenium_evaluate?"Chrome Automation":e.callPhantom||e._phantom?"PhantomJS":e.__nightmare?"Nightmare":e.$testCafe?"TestCafe":null}setupDetection(){const e=this.isAutomationToolPresent();if(e){this.handleDetected(e);return}this.observer=new MutationObserver(()=>{const t=this.isAutomationToolPresent();t&&!this.detectedTools.has(t)&&this.handleDetected(t)}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("unload",()=>this.destroy())}handleDetected(e){this.detectedTools.add(e),this.options.onDetected?.(e)}destroy(){this.observer?.disconnect(),this.observer=void 0,this.detectedTools.clear()}}let ar=0;function sr(){return++ar}const lr=`
386
+ `;function cr(r){const e=r.filter(o=>o.mediaType.isHTML).map(o=>o.href),t=e.length>0?e:[/\.html$/,/\.xhtml$/,/\/$/],n=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([Pe(Ri)],{type:"text/javascript"})},{id:"webpub-execution",as:"script",target:"head",blob:new Blob([Pe(lr)],{type:"text/javascript"})}],i=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([Pe(Pi)],{type:"text/javascript"}),condition:o=>!!(o.querySelector("script")||o.querySelector("body[onload]:not(body[onload=''])"))},{id:"readium-css-webpub",as:"link",target:"head",blob:new Blob([$e(sr)],{type:"text/css"}),rel:"stylesheet"}];return[{resources:t,prepend:n,append:i}]}class hr{constructor(e){if(this.detectedTools=new Set,!e.onDetected)throw new Error("onDetected callback is required");this.options=e,this.setupDetection()}isAutomationToolPresent(){const e=window;return e.domAutomation||e.domAutomationController?"Selenium":navigator.webdriver===!0?"Puppeteer/Playwright":e.__webdriver_evaluate||e.__selenium_evaluate?"Chrome Automation":e.callPhantom||e._phantom?"PhantomJS":e.__nightmare?"Nightmare":e.$testCafe?"TestCafe":null}setupDetection(){const e=this.isAutomationToolPresent();if(e){this.handleDetected(e);return}this.observer=new MutationObserver(()=>{const t=this.isAutomationToolPresent();t&&!this.detectedTools.has(t)&&this.handleDetected(t)}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("unload",()=>this.destroy())}handleDetected(e){this.detectedTools.add(e),this.options.onDetected?.(e)}destroy(){this.observer?.disconnect(),this.observer=void 0,this.detectedTools.clear()}}let dr=0;function ur(){return++dr}const mr=`
388
387
  onmessage = function(event) {
389
388
  var action = event.data;
390
389
  var startTime = performance.now()
@@ -395,7 +394,7 @@ onmessage = function(event) {
395
394
  time: performance.now() - startTime
396
395
  })
397
396
  }
398
- `,pn=class pn{constructor(e,t){this.callbacks=new Map,this.worker=e,this.blobUrl=t,this.worker.onmessage=n=>{const i=n.data,o=i.id,a=this.callbacks.get(i.id);a&&(a({time:i.time}),this.callbacks.delete(o))},this.log=(...n)=>this.send("log",...n),this.table=(...n)=>this.send("table",...n),this.clear=(...n)=>this.send("clear",...n)}async send(e,...t){const n=sr();return new Promise((i,o)=>{this.callbacks.set(n,i),this.worker.postMessage({id:n,type:e,payload:t}),setTimeout(()=>{o(new Error("timeout")),this.callbacks.delete(n)},2e3)})}destroy(){this.worker.terminate(),URL.revokeObjectURL(this.blobUrl)}};pn.workerScript=lr;let pt=pn;function tn(r){return typeof window<"u"&&console?console[r]:(...e)=>{}}const cr=tn("log"),ki=tn("table"),hr=tn("clear");async function Ei(){if(typeof navigator<"u"&&navigator.brave&&navigator.brave.isBrave)try{return await Promise.race([navigator.brave.isBrave(),new Promise(r=>setTimeout(()=>r(!1),1e3))])}catch{return!0}return!1}function dr(r){return r.excludes.some(e=>e())?!1:r.includes.some(e=>e())}class ur{constructor(e={}){if(this.isOpen=!1,this.checkCount=0,this.maxChecks=10,this.maxPrintTime=0,this.largeObjectArray=null,this.options={onDetected:e.onDetected||(()=>{}),onClosed:e.onClosed||(()=>{}),interval:e.interval||1e3,enableDebuggerDetection:e.enableDebuggerDetection||!1},!q.UA.Firefox)try{const t=new Blob([pt.workerScript],{type:"application/javascript"}),n=URL.createObjectURL(t),i=new Worker(n);this.workerConsole=new pt(i,n)}catch(t){console.warn("Failed to create Web Worker for DevTools detection:",t)}this.startDetection()}createLargeObjectArray(){const e={};for(let n=0;n<500;n++)e[`${n}`]=`${n}`;const t=[];for(let n=0;n<50;n++)t.push(e);return t}getLargeObjectArray(){return this.largeObjectArray===null&&(this.largeObjectArray=this.createLargeObjectArray()),this.largeObjectArray}async calcTablePrintTime(){const e=this.getLargeObjectArray();if(this.workerConsole)try{return(await this.workerConsole.table(e)).time}catch{const n=performance.now();return ki(e),performance.now()-n}else{const t=performance.now();return ki(e),performance.now()-t}}async calcLogPrintTime(){const e=this.getLargeObjectArray();if(this.workerConsole)return(await this.workerConsole.log(e)).time;{const t=performance.now();return cr(e),performance.now()-t}}isPerformanceDetectionEnabled(){return dr({includes:[()=>!!q.UA.Chrome,()=>!!q.UA.Chromium,()=>!!q.UA.Safari,()=>!!q.UA.Firefox],excludes:[]})}isDebuggerDetectionEnabled(){return this.options.enableDebuggerDetection}async checkPerformanceBased(){if(!this.isPerformanceDetectionEnabled())return!1;const e=await this.calcTablePrintTime(),t=Math.max(await this.calcLogPrintTime(),await this.calcLogPrintTime());return this.maxPrintTime=Math.max(this.maxPrintTime,t),this.workerConsole?await this.workerConsole.clear():hr(),e===0?!1:this.maxPrintTime===0?!!await Ei():e>this.maxPrintTime*10}async checkDebuggerBased(){if(!this.isDebuggerDetectionEnabled()||await Ei())return!1;const e=performance.now();try{(()=>{}).constructor("debugger")()}catch{debugger}return performance.now()-e>100}async detectDevTools(){return await this.checkPerformanceBased()?!0:this.options.enableDebuggerDetection&&this.checkCount>=this.maxChecks?await this.checkDebuggerBased():!1}startDetection(){this.intervalId=window.setInterval(async()=>{this.checkCount++;const e=await this.detectDevTools();e!==this.isOpen&&(this.isOpen=e,e?this.options.onDetected():this.options.onClosed()),this.checkCount>this.maxChecks*2&&(this.checkCount=0)},this.options.interval),window.addEventListener("beforeunload",()=>this.destroy())}isDevToolsOpen(){return this.isOpen}async checkNow(){const e=this.isOpen;return this.isOpen=await this.detectDevTools(),this.isOpen!==e&&(this.isOpen?this.options.onDetected():this.options.onClosed()),this.isOpen}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.workerConsole&&(this.workerConsole.destroy(),this.workerConsole=void 0),this.isOpen=!1,this.checkCount=0}}class mr{constructor(e){if(this.detected=!1,!e.onDetected)throw new Error("onDetected callback is required");this.options=e,this.setupDetection()}isIframed(){try{return window.self!==window.top?{isEmbedded:!0,isCrossOrigin:!window.top.location.href}:{isEmbedded:!1,isCrossOrigin:!1}}catch{return{isEmbedded:!0,isCrossOrigin:!0}}}setupDetection(){const{isEmbedded:e,isCrossOrigin:t}=this.isIframed();if(e){this.handleDetected(t);return}this.observer=new MutationObserver(()=>{const{isEmbedded:n,isCrossOrigin:i}=this.isIframed();n&&!this.detected&&(this.handleDetected(i),this.observer?.disconnect())}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("unload",()=>this.destroy())}handleDetected(e){this.detected=!0,this.options.onDetected?.(e)}destroy(){this.observer?.disconnect(),this.observer=void 0,this.detected=!1}}class pr{constructor(e={}){this.styleElement=null,this.beforePrintHandler=null,this.onPrintAttempt=e.onPrintAttempt,e.disable&&this.setupPrintProtection(e.watermark)}setupPrintProtection(e){const t=document.createElement("style");t.textContent=`
397
+ `,pn=class pn{constructor(e,t){this.callbacks=new Map,this.worker=e,this.blobUrl=t,this.worker.onmessage=n=>{const i=n.data,o=i.id,a=this.callbacks.get(i.id);a&&(a({time:i.time}),this.callbacks.delete(o))},this.log=(...n)=>this.send("log",...n),this.table=(...n)=>this.send("table",...n),this.clear=(...n)=>this.send("clear",...n)}async send(e,...t){const n=ur();return new Promise((i,o)=>{this.callbacks.set(n,i),this.worker.postMessage({id:n,type:e,payload:t}),setTimeout(()=>{o(new Error("timeout")),this.callbacks.delete(n)},2e3)})}destroy(){this.worker.terminate(),URL.revokeObjectURL(this.blobUrl)}};pn.workerScript=mr;let pt=pn;function tn(r){return typeof window<"u"&&console?console[r]:(...e)=>{}}const pr=tn("log"),Ci=tn("table"),gr=tn("clear");async function ki(){if(typeof navigator<"u"&&navigator.brave&&navigator.brave.isBrave)try{return await Promise.race([navigator.brave.isBrave(),new Promise(r=>setTimeout(()=>r(!1),1e3))])}catch{return!0}return!1}function fr(r){return r.excludes.some(e=>e())?!1:r.includes.some(e=>e())}class yr{constructor(e={}){if(this.isOpen=!1,this.checkCount=0,this.maxChecks=10,this.maxPrintTime=0,this.largeObjectArray=null,this.options={onDetected:e.onDetected||(()=>{}),onClosed:e.onClosed||(()=>{}),interval:e.interval||1e3,enableDebuggerDetection:e.enableDebuggerDetection||!1},!Y.UA.Firefox)try{const t=new Blob([pt.workerScript],{type:"application/javascript"}),n=URL.createObjectURL(t),i=new Worker(n);this.workerConsole=new pt(i,n)}catch(t){console.warn("Failed to create Web Worker for DevTools detection:",t)}this.startDetection()}createLargeObjectArray(){const e={};for(let n=0;n<500;n++)e[`${n}`]=`${n}`;const t=[];for(let n=0;n<50;n++)t.push(e);return t}getLargeObjectArray(){return this.largeObjectArray===null&&(this.largeObjectArray=this.createLargeObjectArray()),this.largeObjectArray}async calcTablePrintTime(){const e=this.getLargeObjectArray();if(this.workerConsole)try{return(await this.workerConsole.table(e)).time}catch{const n=performance.now();return Ci(e),performance.now()-n}else{const t=performance.now();return Ci(e),performance.now()-t}}async calcLogPrintTime(){const e=this.getLargeObjectArray();if(this.workerConsole)return(await this.workerConsole.log(e)).time;{const t=performance.now();return pr(e),performance.now()-t}}isPerformanceDetectionEnabled(){return fr({includes:[()=>!!Y.UA.Chrome,()=>!!Y.UA.Chromium,()=>!!Y.UA.Safari,()=>!!Y.UA.Firefox],excludes:[]})}isDebuggerDetectionEnabled(){return this.options.enableDebuggerDetection}async checkPerformanceBased(){if(!this.isPerformanceDetectionEnabled())return!1;const e=await this.calcTablePrintTime(),t=Math.max(await this.calcLogPrintTime(),await this.calcLogPrintTime());return this.maxPrintTime=Math.max(this.maxPrintTime,t),this.workerConsole?await this.workerConsole.clear():gr(),e===0?!1:this.maxPrintTime===0?!!await ki():e>this.maxPrintTime*10}async checkDebuggerBased(){if(!this.isDebuggerDetectionEnabled()||await ki())return!1;const e=performance.now();try{(()=>{}).constructor("debugger")()}catch{debugger}return performance.now()-e>100}async detectDevTools(){return await this.checkPerformanceBased()?!0:this.options.enableDebuggerDetection&&this.checkCount>=this.maxChecks?await this.checkDebuggerBased():!1}startDetection(){this.intervalId=window.setInterval(async()=>{this.checkCount++;const e=await this.detectDevTools();e!==this.isOpen&&(this.isOpen=e,e?this.options.onDetected():this.options.onClosed()),this.checkCount>this.maxChecks*2&&(this.checkCount=0)},this.options.interval),window.addEventListener("beforeunload",()=>this.destroy())}isDevToolsOpen(){return this.isOpen}async checkNow(){const e=this.isOpen;return this.isOpen=await this.detectDevTools(),this.isOpen!==e&&(this.isOpen?this.options.onDetected():this.options.onClosed()),this.isOpen}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.workerConsole&&(this.workerConsole.destroy(),this.workerConsole=void 0),this.isOpen=!1,this.checkCount=0}}class _r{constructor(e){if(this.detected=!1,!e.onDetected)throw new Error("onDetected callback is required");this.options=e,this.setupDetection()}isIframed(){try{return window.self!==window.top?{isEmbedded:!0,isCrossOrigin:!window.top.location.href}:{isEmbedded:!1,isCrossOrigin:!1}}catch{return{isEmbedded:!0,isCrossOrigin:!0}}}setupDetection(){const{isEmbedded:e,isCrossOrigin:t}=this.isIframed();if(e){this.handleDetected(t);return}this.observer=new MutationObserver(()=>{const{isEmbedded:n,isCrossOrigin:i}=this.isIframed();n&&!this.detected&&(this.handleDetected(i),this.observer?.disconnect())}),this.observer.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("unload",()=>this.destroy())}handleDetected(e){this.detected=!0,this.options.onDetected?.(e)}destroy(){this.observer?.disconnect(),this.observer=void 0,this.detected=!1}}class Sr{constructor(e={}){this.styleElement=null,this.beforePrintHandler=null,this.onPrintAttempt=e.onPrintAttempt,e.disable&&this.setupPrintProtection(e.watermark)}setupPrintProtection(e){const t=document.createElement("style");t.textContent=`
399
398
  @media print {
400
399
  body * {
401
400
  display: none !important;
@@ -409,10 +408,10 @@ onmessage = function(event) {
409
408
  transform: translateY(-50%);
410
409
  }
411
410
  }
412
- `,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=n=>(n.preventDefault(),this.onPrintAttempt?.(),!1),window.addEventListener("beforeprint",this.beforePrintHandler)}destroy(){this.beforePrintHandler&&(window.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null)}}class gr{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const de="readium:navigator:suspiciousActivity";class nn{dispatchSuspiciousActivity(e,t){const n=new CustomEvent(de,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(n)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new ur({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new rr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new mr({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new pr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new gr({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const ue="readium:navigator:keyboardPeripheral";class on{constructor(e={}){this.keyManager=new ni,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=n=>{const i=new CustomEvent(ue,{detail:n});window.dispatchEvent(i)};this.keydownHandler=this.keyManager.createUnifiedHandler("",e,t),this.keydownHandler&&document.addEventListener("keydown",this.keydownHandler,!0)}window.addEventListener("unload",()=>this.destroy())}destroy(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler,!0),this.keydownHandler=void 0)}}const fr=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{}),contentProtection:r.contentProtection||(()=>{}),contextMenu:r.contextMenu||(()=>{}),peripheral:r.peripheral||(()=>{})});class Ci extends $t{constructor(e,t,n,i=void 0,o={preferences:{},defaults:{}}){super(),this.currentIndex=0,this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=fr(n),this._preferences=new Pe(o.preferences),this._defaults=new bi(o.defaults),this._settings=new Zt(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new fi({rsProperties:new gi({experiments:this._settings.experiments||null}),userProperties:new qt({zoom:this._settings.zoom})});const a=or(t.readingOrder.items),s=o.injectables||{rules:[],allowedDomains:[]};if(this._injector=new en({rules:[...a,...s.rules],allowedDomains:s.allowedDomains}),this._contentProtection=o.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,o.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new nn(this._contentProtection),this._suspiciousActivityListener=l=>{const{type:c,...h}=l.detail;c==="context_menu"?this.listeners.contextMenu(h):this.listeners.contentProtection(c,h)},window.addEventListener(de,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(ue,this._keyboardPeripheralListener)),i&&typeof i.copyWithLocations=="function"){this.currentLocation=i;const l=this.pub.readingOrder.findIndexWithHref(i.href);l>=0&&(this.currentIndex=l)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new mi(this.container,e,this._injector,this._contentProtection,this._keyboardPeripherals),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Qt(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){this._settings=new Zt(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Qt(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[n,i]of Object.entries(e.rsProperties.toCSSProperties()))t[n]=i;for(const[n,i]of Object.entries(e.userProperties.toCSSProperties()))t[n]=i;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t)}get _cframes(){return this.framePool.currentFrames}get hasDisplayTransformability(){return this.pub.metadata?.accessibility?.feature?.some(e=>e.value===Je.DISPLAY_TRANSFORMABILITY.value)??!1}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const n=F.deserialize(t);if(!n)break;this.currentLocation=new F({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:n?.locations,text:n?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const i=t;if(i.interactiveElement){const l=new DOMParser().parseFromString(i.interactiveElement,"text/html").body.children[0];if(l.nodeType===l.ELEMENT_NODE&&l.nodeName==="A"&&l.hasAttribute("href")){const c=l.attributes.getNamedItem("href")?.value;if(c.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[c.substring(1)]}),!1,()=>{});else if(c.startsWith("mailto:")||c.startsWith("tel:"))this.listeners.handleLocator(new V({href:c}).locator);else try{let h;if(c.startsWith("http://")||c.startsWith("https://"))h=c;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const m=new URL(this.currentLocation.href);h=new URL(c,m).href}else h=dt.join(dt.dirname(this.currentLocation.href),c);const u=this.pub.readingOrder.findWithHref(h);u?this.goLink(u,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${h}`),this.listeners.handleLocator(new V({href:c}).locator))}catch(h){console.warn(`Couldn't resolve internal link for ${c}: ${h}`),this.listeners.handleLocator(new V({href:c}).locator)}}else console.log("Clicked on",l)}else if(e==="click"?this.listeners.click(i):this.listeners.tap(i))break;break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const o=t;this.listeners.contentProtection(o.type,o);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":const a=t,s={...a,interactiveElement:void 0};a.interactiveElement&&(s.interactiveElement=new DOMParser().parseFromString(a.interactiveElement,"text/html").body.children[0]),this.listeners.peripheral(s);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){const e=Vo.slice(),t=se(this.pub.metadata);return t==="cjk-vertical"||t==="mongolian-vertical"?e.map(n=>n==="webpub_snapper"?"cjk_vertical_snapper":n):e}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(e,t)=>{this.eventListener(e,t)})}async apply(){if(await this.framePool.update(this.pub,this.currentLocation,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),n=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return n===t?!1:(this.currentIndex=n,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(e){this.webViewport.readingOrder=[],this.webViewport.progressions.clear(),this.webViewport.positions=null,this.currentLocation&&(this.webViewport.readingOrder.push(this.currentLocation.href),this.webViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(e){const t=e;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:t.start})),this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this.changeResource(-1).then(n=>{t(n)})}goForward(e,t){this.changeResource(1).then(n=>{t(n)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(e,t){let n=!1,i=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",i?[e.text?.serialize(),i]:e.text?.serialize(),h=>l(h))}):i&&(n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",i],h=>l(h))})),n){t(n);return}const o=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(o&&(n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",o,h=>l(h))})),n){t(n);return}const a=e?.locations?.progression;a&&a>0?n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",a,h=>l(h))}):n=!0,t(n)}go(e,t,n){const i=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(i))return n(this.listeners.handleLocator(e));const a=this.pub.readingOrder.findIndexWithHref(i);a>=0&&(this.currentIndex=a),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,s=>n(s))).then(()=>{this.attachListener()})}goLink(e,t,n){return this.go(e.locator,t,n)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const i=this.currentLocation&&this.currentLocation.href===t.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(t)||new F({href:t.href,type:t.type||"text/html",locations:new k({fragments:[],progression:i,position:this.currentIndex+1})})}}const yr=Ci,Sr=r=>{const e=r.join(" ");return["upgrade-insecure-requests",`default-src ${e} blob:`,"connect-src 'none'",`script-src ${e} blob: 'unsafe-inline'`,`style-src ${e} blob: 'unsafe-inline'`,`img-src ${e} blob: data:`,`font-src ${e} blob: data:`,`object-src ${e} blob:`,`child-src ${e}`,"form-action 'none'"].join("; ")};class xi{constructor(e,t,n,i){this.injector=null,this.pub=e,this.item=n,this.burl=n.toURL(t)||"",this.cssProperties=i.cssProperties,this.injector=i.injector??null}async build(e=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(e);if(this.item.mediaType.isBitmap||this.item.mediaType.equals(g.SVG))return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(e=!1){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const n=new DOMParser().parseFromString(t,this.item.mediaType.string),i=n.querySelector("parsererror");if(i){const o=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${o?.textContent||i.textContent}`)}return this.injector&&await this.injector.injectForDocument(n,this.item),this.finalizeDOM(n,this.pub.baseURL,this.burl,this.item.mediaType,e,this.cssProperties)}buildImageFrame(){const e=document.implementation.createHTMLDocument(this.item.title||this.item.href),t=document.createElement("img");return t.src=this.burl||"",t.alt=this.item.title||"",t.decoding="async",e.body.appendChild(t),this.finalizeDOM(e,this.pub.baseURL,this.burl,this.item.mediaType,!0)}setProperties(e,t){for(const n in e){const i=e[n];i&&t.documentElement.style.setProperty(n,i)}}finalizeDOM(e,t,n,i,o=!1,a){if(!e)return"";const s=this.injector?.getAllowedDomains?.()||[],l=[...new Set([...t?[t]:[],...s])].filter(Boolean);if(a&&!o&&this.setProperties(a,e),e.body.querySelectorAll("img").forEach(u=>{u.setAttribute("fetchpriority","high")}),i.isHTML&&this.pub.metadata.languages?.[0]){const u=this.pub.metadata.languages[0];if(i===g.XHTML){const m=e.documentElement.lang||e.documentElement.getAttribute("xml:lang"),f=e.body.lang||e.body.getAttribute("xml:lang");f&&!m?(e.documentElement.lang=f,e.documentElement.setAttribute("xml:lang",f),e.body.removeAttribute("xml:lang"),e.body.removeAttribute("lang")):m||(e.documentElement.lang=u,e.documentElement.setAttribute("xml:lang",u))}else i===g.HTML&&!e.documentElement.lang&&(e.documentElement.lang=u)}if(se(this.pub.metadata)==="rtl"&&!e.documentElement.dir&&!e.body.dir&&(e.documentElement.dir=N.rtl),n!==void 0){const u=e.createElement("base");u.href=n,u.dataset.readium="true",e.head.firstChild.before(u)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Sr(l),h.dataset.readium="true",e.head.firstChild.before(h),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:i.isHTML?i.string:"application/xhtml+xml"}))}}class rn{constructor(e,t={},n=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...n]}async load(e){return new Promise((t,n)=>{if(this.loader){const i=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(i)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new _e(i,e),this.currModules=e,this.comms=void 0;try{t(i)}catch{}return}this.frame.onload=()=>{const i=this.frame.contentWindow;this.loader=new _e(i,e),this.currModules=e;try{t(i)}catch{}},this.frame.onerror=i=>{try{n(i)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Xt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){this.conditionBridge?.destroy(),await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),new Promise((t,n)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const i=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,q.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,i):i()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new ve(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get isDestroyed(){return this.destroyed}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const Li=5,zi=3;class Oi{constructor(e,t,n,i,o,a){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.positions=t,this.currentCssProperties=n,this.injector=i??null,this.contentProtectionConfig=o||{},this.keyboardPeripheralsConfig=a||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>{this.injector?.releaseBlobUrl?.(a),URL.revokeObjectURL(a)}),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}async update(e,t,n,i=!1){let o=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(o<0)throw Error(`Locator not found in position list: ${t.locations.position} > ${this.positions.reduce((l,c)=>c.locations.position||0>l?c.locations.position||0:l,0)}`);const a=this.positions[o].href;this.inprogress.has(a)&&await this.inprogress.get(a);const s=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>o+Li||p<o-Li)&&(h.includes(d.href)||h.push(d.href)),p<o+zi&&p>o-zi&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d),this.pendingUpdates.has(d)&&this.pendingUpdates.set(d,{inPool:!1}))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(i&&(this.blobs.forEach(R=>{this.injector?.releaseBlobUrl?.(R),URL.revokeObjectURL(R)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const R=this.blobs.get(d);R&&(this.injector?.releaseBlobUrl?.(R),URL.revokeObjectURL(R),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const R=this.pool.get(d);if(!this.blobs.has(d))await R.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await R.load(n);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const U=await new xi(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,U)}const _=new rn(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==a&&await _.hide(),this.container.appendChild(_.iframe),await _.load(n),this.pool.set(d,_)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=this.pool.get(a);(f?.source!==this._currentFrame?.source||i)&&(await this._currentFrame?.hide(),f&&await f.load(n),f&&await f.show(t.locations.progression),this._currentFrame=f),l()});this.inprogress.set(a,s),await s,this.inprogress.delete(a)}setCSSProperties(e){if(!((n,i)=>{const o=Object.keys(n),a=Object.keys(i);if(o.length!==a.length)return!1;for(const s of o)if(n[s]!==i[s])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(n=>{n.setCSSProperties(e)});for(const n of this.blobs.keys())this.pendingUpdates.set(n,{inPool:this.pool.has(n)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}}class Ai{constructor(e,t,n,i={},o=[]){this.currModules=[],this.cachedPage=void 0,this.peripherals=e,this.debugHref=n,this.contentProtectionConfig={...i},this.keyboardPeripheralsConfig=[...o],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=n,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===N.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(e,t){return this.source===t&&this.loadPromise&&[...this.currModules].sort().join("|")===[...e].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==t&&this.window.stop(),this.source=t,this.loadPromise=new Promise((n,i)=>{if(this.loader&&this.loaded){const o=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{n(o),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new _e(o,e),this.currModules=e,this.comms=void 0;try{n(o),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const o=this.frame.contentWindow;this.loader=new _e(o,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(o);try{n(o)}catch{}},{once:!0}),this.frame.addEventListener("error",o=>{try{i(o.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const e=this.frame.contentWindow,t=e.document.head.querySelector("meta[name=viewport]");if(t){const n=/(\w+) *= *([^\s,]+)/g;let i,o=0,a=0;for(;i=n.exec(t.content);)i[1]==="width"?o=Number.parseFloat(i[2]):i[1]==="height"&&(a=Number.parseFloat(i[2]));if(o>0&&a>0)return{width:o,height:a}}return{width:e.document.body.scrollWidth,height:e.document.body.scrollHeight}}update(e){if(!this.loaded)return;const t=this.loadPageSize();this.frame.style.height=`${t.height}px`,this.frame.style.width=`${t.width}px`;const n=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${n})`;const i=this.frame.getBoundingClientRect(),o=this.wrapper.clientHeight-i.height;if(this.frame.style.top=`${o/2}px`,e===X.left){const a=this.wrapper.clientWidth-i.width;this.frame.style.left=`${a}px`}else if(e===X.center){const a=this.wrapper.clientWidth-i.width;this.frame.style.left=`${a/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){this.conditionBridge?.destroy(),await this.unfocus(),this.loader?.destroy(),this.wrapper.remove()}async unload(){if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),this.comms?.halt(),this.loader?.destroy(),this.comms=void 0,this.frame.blur(),new Promise((e,t)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,e()}catch{}},{once:!0}),this.frame.addEventListener("error",n=>{try{this.showPromise=void 0,t(n.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){this.frame.contentWindow?.getSelection()?.removeAllRanges()}async unfocus(){if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),this.showPromise=void 0,e()})});this.comms?.halt()}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Xt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async show(e){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==e&&(this.update(e),this.cachedPage=e),this.showPromise):(this.cachedPage=e,this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,n)=>{this.comms.send("focus",void 0,i=>{this.update(this.cachedPage),this.applyContentProtection(),t()})}),this.showPromise)}async activate(){return new Promise((e,t)=>{if(!this.comms)return e();this.comms?.send("activate",void 0,()=>{e()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(e){const t=`${e}%`;this.wrapper.style.width!==t&&(this.wrapper.style.width=t)}set height(e){const t=`${e}px`;this.wrapper.style.height!==t&&(this.wrapper.style.height=t)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}var Ui=(r=>(r[r.Left=0]="Left",r[r.Center=1]="Center",r[r.Right=2]="Right",r))(Ui||{}),Ti=(r=>(r[r.Top=0]="Top",r[r.Middle=1]="Middle",r[r.Bottom=2]="Bottom",r))(Ti||{});class Mi{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){q.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,q.OS.Android&&q.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(e,t=0){const n={X:0,Y:0};return/^touch/.test(e.type)?(n.X=e.touches[t].screenX,n.Y=e.touches[t].screenY):(n.X=e.screenX,n.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(n.X-=this.HTML.scrollLeft+this.Body.scrollLeft,n.Y-=this.HTML.scrollTop+this.Body.scrollTop),n.X-=this.outerWidth,n.Y-=this.outerHeight,n}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,n=e.touches[0].screenY-this.outerHeight,i=e.touches[1].screenX-this.outerWidth,o=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(i-t,2)+Math.pow(o-n,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,n=this.HTML.scrollTop+this.Body.scrollTop,i=e.touches[0].screenX-this.outerWidth-t,o=e.touches[0].screenY-this.outerHeight-n,a=e.touches[1].screenX-this.outerWidth-t,s=e.touches[1].screenY-this.outerHeight-n;return{X:(i+a)/2,Y:(o+s)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let n=.3;const i={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let o,a,s,l;s=o=n,l=a=1-n;const c={X:null,Y:null};return i.X<s?c.X=0:l<i.X?c.X=2:c.X=1,i.Y<o?c.Y=0:a<i.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:i,Division:c}}}class br{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const Fi=6,an=1.02,Ni=50;class Ii{constructor(e,t=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=e,this.coordinator=new Mi,this.attachEvents(),t&&(this.debugger=new br)}get scale(){return this._scale}set scale(e){isNaN(e)&&(e=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<an&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",e)},100),this._scale=e}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(e){e.addEventListener("touchstart",this.btouchstartHandler),e.addEventListener("touchend",this.btouchendHandler),e.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),e.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),e.addEventListener("mousedown",this.bmousedownHandler),e.addEventListener("mouseup",this.bmouseupHandler),e.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(e){}touchstartHandler(e){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(e.target.nodeName)!==-1)return;switch(e.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),e.touches.length){case 3:return;case 2:{e.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(e);const i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},this.debugger?.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=e.touches[0].identifier,this.debugger?.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.Y}startTouch(e){const t=this.coordinator.getTouchCenter(e)||this.coordinator.getBibiEventCoord(e);return{X:t.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:t.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(e){if(e.stopPropagation(),!e.touches||e.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>Ni&&Math.abs(this.pan.overscrollY)<Ni/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(e.touches.length===1){this.dragState=1,e.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=e.touches[0].identifier),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const t=this.startTouch(e);this.pan.startX=t.X,this.pan.startY=t.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<an&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(e){e.stopPropagation();const t=this.coordinator.getBibiEventCoord(e);Math.abs(this.pan.startY-t.Y)+Math.abs(this.pan.startX-t.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const n=this.coordinator?.getTouchDistance(e);let i=!1;const o=this.scale;if(this.dragState===2&&n){if(this.pinch.touchN++,this.pinch.touchN<4)return;let a=n/this.pinch.startDistance*this.scale;a>=Fi&&(a=Fi),a<=an&&(a=1),this.scale=a,this.pinch.startDistance=n,i=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-t.Y)<Math.abs(this.pan.startX-t.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${t.Y-10}px`,this.debugger.DOM.touch1.style.left=`${t.X-10}px`,this.debugger.DOM.touch1.innerText=`${t.X.toFixed(2)},${t.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const l={X:t.X-this.manager.width/2,Y:t.Y-this.manager.height/2};this.pan.translateX=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const l=this.coordinator.getTouchCenter(e);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${l.Y-5}px`,this.debugger.DOM.center.style.left=`${l.X-5}px`,this.debugger.DOM.center.innerText=`${l.X.toFixed(2)},${l.Y.toFixed(2)}`;const f=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${f.Y-10}px`,this.debugger.DOM.touch2.style.left=`${f.X-10}px`,this.debugger.DOM.touch2.innerText=`${f.X.toFixed(2)},${f.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/o;c+=l.X/this.scale,this.pinch.target.X+=c,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let h=-l.Y/o;h+=l.Y/this.scale,this.pinch.target.Y+=h,l.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let u=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,m=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=u,this.pan.translateY=m,this.debugger?.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const a=this.frameBounds.width/6,s=this.frameBounds.height/6;this.pan.translateX<-a&&(this.pan.overscrollX=-(a+this.pan.translateX),this.pan.translateX=-a),this.pan.translateY<-s&&(this.pan.overscrollY=-(s+this.pan.translateY),this.pan.translateY=-s),this.pan.translateX>a&&(this.pan.overscrollX=a-this.pan.translateX,this.pan.translateX=a),this.pan.translateY>s&&(this.pan.overscrollY=s-this.pan.translateY,this.pan.translateY=s),i=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
411
+ `,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=n=>(n.preventDefault(),this.onPrintAttempt?.(),!1),window.addEventListener("beforeprint",this.beforePrintHandler)}destroy(){this.beforePrintHandler&&(window.removeEventListener("beforeprint",this.beforePrintHandler),this.beforePrintHandler=null),this.styleElement?.parentNode&&(this.styleElement.parentNode.removeChild(this.styleElement),this.styleElement=null)}}class br{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const de="readium:navigator:suspiciousActivity";class nn{dispatchSuspiciousActivity(e,t){const n=new CustomEvent(de,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(n)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new yr({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new hr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new _r({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new Sr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new br({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const ue="readium:navigator:keyboardPeripheral";class on{constructor(e={}){this.keyManager=new ni,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=n=>{const i=new CustomEvent(ue,{detail:n});window.dispatchEvent(i)};this.keydownHandler=this.keyManager.createUnifiedHandler("",e,t),this.keydownHandler&&document.addEventListener("keydown",this.keydownHandler,!0)}window.addEventListener("unload",()=>this.destroy())}destroy(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler,!0),this.keydownHandler=void 0)}}const vr=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{}),contentProtection:r.contentProtection||(()=>{}),contextMenu:r.contextMenu||(()=>{}),peripheral:r.peripheral||(()=>{})});class Ei extends $t{constructor(e,t,n,i=void 0,o={preferences:{},defaults:{}}){super(),this.currentIndex=0,this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.webViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=vr(n),this._preferences=new Re(o.preferences),this._defaults=new Si(o.defaults),this._settings=new Jt(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new fi({rsProperties:new gi({experiments:this._settings.experiments||null}),userProperties:new Yt({zoom:this._settings.zoom})});const a=cr(t.readingOrder.items),s=o.injectables||{rules:[],allowedDomains:[]};if(this._injector=new en({rules:[...a,...s.rules],allowedDomains:s.allowedDomains}),this._contentProtection=o.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,o.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new nn(this._contentProtection),this._suspiciousActivityListener=l=>{const{type:c,...h}=l.detail;c==="context_menu"?this.listeners.contextMenu(h):this.listeners.contentProtection(c,h)},window.addEventListener(de,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(ue,this._keyboardPeripheralListener)),i&&typeof i.copyWithLocations=="function"){this.currentLocation=i;const l=this.pub.readingOrder.findIndexWithHref(i.href);l>=0&&(this.currentIndex=l)}else this.currentLocation=this.createCurrentLocator()}async load(){await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new mi(this.container,e,this._injector,this._contentProtection,this._keyboardPeripherals),await this.apply()}get settings(){return Object.freeze({...this._settings})}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new Qt(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){this._settings=new Jt(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Qt(this._preferences,this.settings,this.pub.metadata)),await this.updateCSS(!0)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[n,i]of Object.entries(e.rsProperties.toCSSProperties()))t[n]=i;for(const[n,i]of Object.entries(e.userProperties.toCSSProperties()))t[n]=i;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t)}get _cframes(){return this.framePool.currentFrames}get hasDisplayTransformability(){return this.pub.metadata?.accessibility?.feature?.some(e=>e.value===Ze.DISPLAY_TRANSFORMABILITY.value)??!1}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this.framePool.currentFrames[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const n=N.deserialize(t);if(!n)break;this.currentLocation=new N({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:n?.locations,text:n?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const i=t;if(i.interactiveElement){const l=new DOMParser().parseFromString(i.interactiveElement,"text/html").body.children[0];if(l.nodeType===l.ELEMENT_NODE&&l.nodeName==="A"&&l.hasAttribute("href")){const c=l.attributes.getNamedItem("href")?.value;if(c.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[c.substring(1)]}),!1,()=>{});else if(c.startsWith("mailto:")||c.startsWith("tel:"))this.listeners.handleLocator(new V({href:c}).locator);else try{let h;if(c.startsWith("http://")||c.startsWith("https://"))h=c;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const m=new URL(this.currentLocation.href);h=new URL(c,m).href}else h=dt.join(dt.dirname(this.currentLocation.href),c);const u=this.pub.readingOrder.findWithHref(h);u?this.goLink(u,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${h}`),this.listeners.handleLocator(new V({href:c}).locator))}catch(h){console.warn(`Couldn't resolve internal link for ${c}: ${h}`),this.listeners.handleLocator(new V({href:c}).locator)}}else console.log("Clicked on",l)}else if(e==="click"?this.listeners.click(i):this.listeners.tap(i))break;break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const o=t;this.listeners.contentProtection(o.type,o);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":const a=t,s={...a,interactiveElement:void 0};a.interactiveElement&&(s.interactiveElement=new DOMParser().parseFromString(a.interactiveElement,"text/html").body.children[0]),this.listeners.peripheral(s);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){const e=Vo.slice(),t=se(this.pub.metadata);return t==="cjk-vertical"||t==="mongolian-vertical"?e.map(n=>n==="webpub_snapper"?"cjk_vertical_snapper":n):e}attachListener(){this.framePool.currentFrames[0]?.msg&&(this.framePool.currentFrames[0].msg.listener=(e,t)=>{this.eventListener(e,t)})}async apply(){if(await this.framePool.update(this.pub,this.currentLocation,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),n=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return n===t?!1:(this.currentIndex=n,this.currentLocation=this.createCurrentLocator(),await this.apply(),!0)}updateViewport(e){this.webViewport.readingOrder=[],this.webViewport.progressions.clear(),this.webViewport.positions=null,this.currentLocation&&(this.webViewport.readingOrder.push(this.currentLocation.href),this.webViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.webViewport.positions=[this.currentLocation.locations.position]))}async syncLocation(e){const t=e;this.currentLocation&&(this.currentLocation=this.currentLocation.copyWithLocations({progression:t.start})),this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this.changeResource(-1).then(n=>{t(n)})}goForward(e,t){this.changeResource(1).then(n=>{t(n)})}get currentLocator(){return this.currentLocation}get viewport(){return this.webViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.pub.metadata.effectiveReadingProgression}get publication(){return this.pub}async loadLocator(e,t){let n=!1,i=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",i?[e.text?.serialize(),i]:e.text?.serialize(),h=>l(h))}):i&&(n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",i],h=>l(h))})),n){t(n);return}const o=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(o&&(n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",o,h=>l(h))})),n){t(n);return}const a=e?.locations?.progression;a&&a>0?n=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",a,h=>l(h))}):n=!0,t(n)}go(e,t,n){const i=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(i))return n(this.listeners.handleLocator(e));const a=this.pub.readingOrder.findIndexWithHref(i);a>=0&&(this.currentIndex=a),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,s=>n(s))).then(()=>{this.attachListener()})}goLink(e,t,n){return this.go(e.locator,t,n)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const i=this.currentLocation&&this.currentLocation.href===t.href&&this.currentLocation.locations.progression?this.currentLocation.locations.progression:0;return this.pub.manifest.locatorFromLink(t)||new N({href:t.href,type:t.type||"text/html",locations:new C({fragments:[],progression:i,position:this.currentIndex+1})})}}const wr=Ei,Rr=r=>{const e=r.join(" ");return["upgrade-insecure-requests",`default-src ${e} blob:`,"connect-src 'none'",`script-src ${e} blob: 'unsafe-inline'`,`style-src ${e} blob: 'unsafe-inline'`,`img-src ${e} blob: data:`,`font-src ${e} blob: data:`,`object-src ${e} blob:`,`child-src ${e}`,"form-action 'none'"].join("; ")};class xi{constructor(e,t,n,i){this.injector=null,this.pub=e,this.item=n,this.burl=n.toURL(t)||"",this.cssProperties=i.cssProperties,this.injector=i.injector??null}async build(e=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(e);if(this.item.mediaType.isBitmap||this.item.mediaType.equals(g.SVG))return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(e=!1){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const n=new DOMParser().parseFromString(t,this.item.mediaType.string),i=n.querySelector("parsererror");if(i){const o=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${o?.textContent||i.textContent}`)}return this.injector&&await this.injector.injectForDocument(n,this.item),this.finalizeDOM(n,this.pub.baseURL,this.burl,this.item.mediaType,e,this.cssProperties)}buildImageFrame(){const e=document.implementation.createHTMLDocument(this.item.title||this.item.href),t=document.createElement("img");return t.src=this.burl||"",t.alt=this.item.title||"",t.decoding="async",e.body.appendChild(t),this.finalizeDOM(e,this.pub.baseURL,this.burl,this.item.mediaType,!0)}setProperties(e,t){for(const n in e){const i=e[n];i&&t.documentElement.style.setProperty(n,i)}}finalizeDOM(e,t,n,i,o=!1,a){if(!e)return"";const s=this.injector?.getAllowedDomains?.()||[],l=[...new Set([...t?[t]:[],...s])].filter(Boolean);if(a&&!o&&this.setProperties(a,e),e.body.querySelectorAll("img").forEach(u=>{u.setAttribute("fetchpriority","high")}),i.isHTML&&this.pub.metadata.languages?.[0]){const u=this.pub.metadata.languages[0];if(i===g.XHTML){const m=e.documentElement.lang||e.documentElement.getAttribute("xml:lang"),f=e.body.lang||e.body.getAttribute("xml:lang");f&&!m?(e.documentElement.lang=f,e.documentElement.setAttribute("xml:lang",f),e.body.removeAttribute("xml:lang"),e.body.removeAttribute("lang")):m||(e.documentElement.lang=u,e.documentElement.setAttribute("xml:lang",u))}else i===g.HTML&&!e.documentElement.lang&&(e.documentElement.lang=u)}if(se(this.pub.metadata)==="rtl"&&!e.documentElement.dir&&!e.body.dir&&(e.documentElement.dir=M.rtl),n!==void 0){const u=e.createElement("base");u.href=n,u.dataset.readium="true",e.head.firstChild.before(u)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Rr(l),h.dataset.readium="true",e.head.firstChild.before(h),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:i.isHTML?i.string:"application/xhtml+xml"}))}}class rn{constructor(e,t={},n=[]){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=e,this.contentProtectionConfig={...t},this.keyboardPeripheralsConfig=[...n]}async load(e){return new Promise((t,n)=>{if(this.loader){const i=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(i)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(i,e),this.currModules=e,this.comms=void 0;try{t(i)}catch{}return}this.frame.onload=()=>{const i=this.frame.contentWindow;this.loader=new be(i,e),this.currModules=e;try{t(i)}catch{}},this.frame.onerror=i=>{try{n(i)}catch{}},this.frame.contentWindow.location.replace(this.source)})}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Kt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async destroy(){this.conditionBridge?.destroy(),await this.hide(),this.loader?.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),e()})});this.comms?.halt()}}async show(e){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),new Promise((t,n)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const i=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,Y.UA.WebKit&&this.comms?.send("force_webkit_recalc",void 0),t()};e!==void 0?this.comms?.send("go_progression",e,i):i()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new ve(this.frame.contentWindow,this.source)),this.comms?.send("update_properties",e),this.hidden&&this.comms?.halt())}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get isDestroyed(){return this.destroyed}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const Fi=5,zi=3;class Li{constructor(e,t,n,i,o,a){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.injector=null,this.container=e,this.positions=t,this.currentCssProperties=n,this.injector=i??null,this.contentProtectionConfig=o||{},this.keyboardPeripheralsConfig=a||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>{this.injector?.releaseBlobUrl?.(a),URL.revokeObjectURL(a)}),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}async update(e,t,n,i=!1){let o=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(o<0)throw Error(`Locator not found in position list: ${t.locations.position} > ${this.positions.reduce((l,c)=>c.locations.position||0>l?c.locations.position||0:l,0)}`);const a=this.positions[o].href;this.inprogress.has(a)&&await this.inprogress.get(a);const s=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>o+Fi||p<o-Fi)&&(h.includes(d.href)||h.push(d.href)),p<o+zi&&p>o-zi&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(await this.pool.get(d)?.destroy(),this.pool.delete(d),this.pendingUpdates.has(d)&&this.pendingUpdates.set(d,{inPool:!1}))}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>{this.injector?.releaseBlobUrl?.(d),URL.revokeObjectURL(d)}),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{if(i&&(this.blobs.forEach(P=>{this.injector?.releaseBlobUrl?.(P),URL.revokeObjectURL(P)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const P=this.blobs.get(d);P&&(this.injector?.releaseBlobUrl?.(P),URL.revokeObjectURL(P),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const P=this.pool.get(d);if(!this.blobs.has(d))await P.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await P.load(n);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const A=await new xi(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,A)}const b=new rn(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==a&&await b.hide(),this.container.appendChild(b.iframe),await b.load(n),this.pool.set(d,b)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=this.pool.get(a);(f?.source!==this._currentFrame?.source||i)&&(await this._currentFrame?.hide(),f&&await f.load(n),f&&await f.show(t.locations.progression),this._currentFrame=f),l()});this.inprogress.set(a,s),await s,this.inprogress.delete(a)}setCSSProperties(e){if(!((n,i)=>{const o=Object.keys(n),a=Object.keys(i);if(o.length!==a.length)return!1;for(const s of o)if(n[s]!==i[s])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(n=>{n.setCSSProperties(e)});for(const n of this.blobs.keys())this.pendingUpdates.set(n,{inPool:this.pool.has(n)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}}class Oi{constructor(e,t,n,i={},o=[]){this.currModules=[],this.cachedPage=void 0,this.peripherals=e,this.debugHref=n,this.contentProtectionConfig={...i},this.keyboardPeripheralsConfig=[...o],this.frame=document.createElement("iframe"),this.frame.sandbox.value="allow-same-origin allow-scripts",this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=n,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===M.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(e,t){return this.source===t&&this.loadPromise&&[...this.currModules].sort().join("|")===[...e].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==t&&this.window.stop(),this.source=t,this.loadPromise=new Promise((n,i)=>{if(this.loader&&this.loaded){const o=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{n(o),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(o,e),this.currModules=e,this.comms=void 0;try{n(o),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const o=this.frame.contentWindow;this.loader=new be(o,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(o);try{n(o)}catch{}},{once:!0}),this.frame.addEventListener("error",o=>{try{i(o.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const e=this.frame.contentWindow,t=e.document.head.querySelector("meta[name=viewport]");if(t){const n=/(\w+) *= *([^\s,]+)/g;let i,o=0,a=0;for(;i=n.exec(t.content);)i[1]==="width"?o=Number.parseFloat(i[2]):i[1]==="height"&&(a=Number.parseFloat(i[2]));if(o>0&&a>0)return{width:o,height:a}}return{width:e.document.body.scrollWidth,height:e.document.body.scrollHeight}}update(e){if(!this.loaded)return;const t=this.loadPageSize();this.frame.style.height=`${t.height}px`,this.frame.style.width=`${t.width}px`;const n=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${n})`;const i=this.frame.getBoundingClientRect(),o=this.wrapper.clientHeight-i.height;if(this.frame.style.top=`${o/2}px`,e===K.left){const a=this.wrapper.clientWidth-i.width;this.frame.style.left=`${a}px`}else if(e===K.center){const a=this.wrapper.clientWidth-i.width;this.frame.style.left=`${a/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){this.conditionBridge?.destroy(),await this.unfocus(),this.loader?.destroy(),this.wrapper.remove()}async unload(){if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),this.comms?.halt(),this.loader?.destroy(),this.comms=void 0,this.frame.blur(),new Promise((e,t)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,e()}catch{}},{once:!0}),this.frame.addEventListener("error",n=>{try{this.showPromise=void 0,t(n.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){this.frame.contentWindow?.getSelection()?.removeAllRanges()}async unfocus(){if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((e,t)=>{this.comms?.send("unfocus",void 0,n=>{this.comms?.halt(),this.showPromise=void 0,e()})});this.comms?.halt()}applyContentProtection(){this.comms||this.comms.resume(),this.comms.send("peripherals_protection",this.contentProtectionConfig),this.keyboardPeripheralsConfig&&this.keyboardPeripheralsConfig.length>0&&(this.conditionBridge?.destroy(),this.conditionBridge=new Kt(this.keyboardPeripheralsConfig,e=>{e.length>0&&this.comms.send("keyboard_peripherals",e)}),this.conditionBridge.setup()),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async show(e){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==e&&(this.update(e),this.cachedPage=e),this.showPromise):(this.cachedPage=e,this.comms?this.comms.resume():this.comms=new ve(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,n)=>{this.comms.send("focus",void 0,i=>{this.update(this.cachedPage),this.applyContentProtection(),t()})}),this.showPromise)}async activate(){return new Promise((e,t)=>{if(!this.comms)return e();this.comms?.send("activate",void 0,()=>{e()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(e){const t=`${e}%`;this.wrapper.style.width!==t&&(this.wrapper.style.width=t)}set height(e){const t=`${e}px`;this.wrapper.style.height!==t&&(this.wrapper.style.height=t)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}var Ai=(r=>(r[r.Left=0]="Left",r[r.Center=1]="Center",r[r.Right=2]="Right",r))(Ai||{}),Ui=(r=>(r[r.Top=0]="Top",r[r.Middle=1]="Middle",r[r.Bottom=2]="Bottom",r))(Ui||{});class Ti{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){Y.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,Y.OS.Android&&Y.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(e,t=0){const n={X:0,Y:0};return/^touch/.test(e.type)?(n.X=e.touches[t].screenX,n.Y=e.touches[t].screenY):(n.X=e.screenX,n.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(n.X-=this.HTML.scrollLeft+this.Body.scrollLeft,n.Y-=this.HTML.scrollTop+this.Body.scrollTop),n.X-=this.outerWidth,n.Y-=this.outerHeight,n}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,n=e.touches[0].screenY-this.outerHeight,i=e.touches[1].screenX-this.outerWidth,o=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(i-t,2)+Math.pow(o-n,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,n=this.HTML.scrollTop+this.Body.scrollTop,i=e.touches[0].screenX-this.outerWidth-t,o=e.touches[0].screenY-this.outerHeight-n,a=e.touches[1].screenX-this.outerWidth-t,s=e.touches[1].screenY-this.outerHeight-n;return{X:(i+a)/2,Y:(o+s)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let n=.3;const i={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let o,a,s,l;s=o=n,l=a=1-n;const c={X:null,Y:null};return i.X<s?c.X=0:l<i.X?c.X=2:c.X=1,i.Y<o?c.Y=0:a<i.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:i,Division:c}}}class Pr{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const Ni=6,an=1.02,Mi=50;class Ii{constructor(e,t=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=e,this.coordinator=new Ti,this.attachEvents(),t&&(this.debugger=new Pr)}get scale(){return this._scale}set scale(e){isNaN(e)&&(e=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<an&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",e)},100),this._scale=e}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(e){e.addEventListener("touchstart",this.btouchstartHandler),e.addEventListener("touchend",this.btouchendHandler),e.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),e.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),e.addEventListener("mousedown",this.bmousedownHandler),e.addEventListener("mouseup",this.bmouseupHandler),e.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(e){}touchstartHandler(e){if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(e.target.nodeName)!==-1)return;switch(e.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),e.touches.length){case 3:return;case 2:{e.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(e);const i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},this.debugger?.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=e.touches[0].identifier,this.debugger?.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.Y}startTouch(e){const t=this.coordinator.getTouchCenter(e)||this.coordinator.getBibiEventCoord(e);return{X:t.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:t.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(e){if(e.stopPropagation(),!e.touches||e.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>Mi&&Math.abs(this.pan.overscrollY)<Mi/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(e.touches.length===1){this.dragState=1,e.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=e.touches[0].identifier),this.debugger?.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const t=this.startTouch(e);this.pan.startX=t.X,this.pan.startY=t.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<an&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(e){e.stopPropagation();const t=this.coordinator.getBibiEventCoord(e);Math.abs(this.pan.startY-t.Y)+Math.abs(this.pan.startX-t.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const n=this.coordinator?.getTouchDistance(e);let i=!1;const o=this.scale;if(this.dragState===2&&n){if(this.pinch.touchN++,this.pinch.touchN<4)return;let a=n/this.pinch.startDistance*this.scale;a>=Ni&&(a=Ni),a<=an&&(a=1),this.scale=a,this.pinch.startDistance=n,i=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-t.Y)<Math.abs(this.pan.startX-t.X)),this.debugger?.show&&(this.debugger.DOM.touch1.style.top=`${t.Y-10}px`,this.debugger.DOM.touch1.style.left=`${t.X-10}px`,this.debugger.DOM.touch1.innerText=`${t.X.toFixed(2)},${t.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const l={X:t.X-this.manager.width/2,Y:t.Y-this.manager.height/2};this.pan.translateX=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const l=this.coordinator.getTouchCenter(e);if(this.debugger?.show){this.debugger.DOM.center.style.top=`${l.Y-5}px`,this.debugger.DOM.center.style.left=`${l.X-5}px`,this.debugger.DOM.center.innerText=`${l.X.toFixed(2)},${l.Y.toFixed(2)}`;const f=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${f.Y-10}px`,this.debugger.DOM.touch2.style.left=`${f.X-10}px`,this.debugger.DOM.touch2.innerText=`${f.X.toFixed(2)},${f.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/o;c+=l.X/this.scale,this.pinch.target.X+=c,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let h=-l.Y/o;h+=l.Y/this.scale,this.pinch.target.Y+=h,l.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let u=(l.X-(this.pan.startX-this.manager.width/2))*1/this.scale,m=(l.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=u,this.pan.translateY=m,this.debugger?.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const a=this.frameBounds.width/6,s=this.frameBounds.height/6;this.pan.translateX<-a&&(this.pan.overscrollX=-(a+this.pan.translateX),this.pan.translateX=-a),this.pan.translateY<-s&&(this.pan.overscrollY=-(s+this.pan.translateY),this.pan.translateY=-s),this.pan.translateX>a&&(this.pan.overscrollX=a-this.pan.translateX,this.pan.translateX=a),this.pan.translateY>s&&(this.pan.overscrollY=s-this.pan.translateY,this.pan.translateY=s),i=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
413
412
  TY: ${this.pan.translateY.toFixed(2)}
414
413
  Zoom: ${this.scale.toFixed(2)}
415
- Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(i){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const s=this.manager.currentSlide*(this.manager.width/this.manager.perPage),l=this.pan.endX-this.pan.startX,c=this.manager.rtl?s+l:s-l;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*c}px, 0, 0)`})})}}dblclickHandler(e){clearTimeout(this.dtimer),this.pdblclick=!0,this.dtimer=window.setTimeout(()=>this.pdblclick=!1,200),!this.disableDblClick&&this.isScaled&&(this.scale=1)}get isScaled(){return this.scale>1}addTouch(e){e.touches=[{pageX:e.pageX,pageY:e.pageY}]}mousedownHandler(e){this.isScaled&&(this.addTouch(e),this.touchstartHandler(e))}mouseupHandler(e){this.isScaled&&this.touchendHandler(e)}mousemoveHandler(e){this.isScaled&&e.buttons>0&&(e.preventDefault(),this.addTouch(e),this.touchmoveHandler(e))}updateAfterDrag(){const e=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),t=Math.abs(e);e>0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):e<0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}var gt=(r=>(r.auto="auto",r.landscape="landscape",r.portrait="portrait",r))(gt||{}),ft=(r=>(r.auto="auto",r.both="both",r.none="none",r.landscape="landscape",r))(ft||{});class Di{constructor(e){this.shift=!0,this.spreads=[],this.nLandscape=0,this.index(e),this.testShift(e),console.log(`Indexed ${this.spreads.length} spreads for ${e.readingOrder.items.length} items`)}index(e,t=!1){this.nLandscape=0,e.readingOrder.items.forEach((n,i)=>{t||(e.readingOrder.items[i]=n.addProperties({number:i+1,isImage:n.type?.indexOf("image/")===0}));const o=n.properties?.otherProperties.orientation==="landscape";(!n.properties?.page||t)&&(n.properties=n.properties?.add({page:o?"center":((this.shift?0:1)+i-this.nLandscape)%2?e.metadata.readingProgression===N.rtl?"right":"left":e.metadata.readingProgression===N.rtl?"left":"right"})),(o||n.properties?.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(e.readingOrder)}testShift(e){let t=!1;this.spreads.forEach((n,i)=>{if(n.length>1)return;const o=n[0],a=o.properties?.otherProperties.orientation;i===0&&(a==="landscape"||a!=="portrait"&&((o.width||0)>(o.height||0)||o.properties?.otherProperties.spread==="both"))&&(this.shift=!1),t&&o.properties?.page===X.center&&this.spreads[i-1][0].addProperties({addBlank:!0}),a==="portrait"&&o.properties?.page!=="center"&&o.properties?.otherProperties.number>1?t=!0:t=!1}),this.shift||this.index(e,!0)}buildSpreads(e){let t=[];e.items.forEach((n,i)=>{!i&&this.shift?this.spreads.push([n]):n.properties?.page===X.center?(t.length>0&&this.spreads.push(t),this.spreads.push([n]),t=[]):t.length>=2?(this.spreads.push(t),t=[n]):t.push(n)}),t.length>0&&this.spreads.push(t)}currentSpread(e,t){return this.spreads[Math.min(Math.floor(e/t),this.spreads.length-1)]}findByLink(e){return this.spreads.find(t=>t.includes(e))||void 0}}const Hi=8,Wi=5,_r=300,vr=15e3,wr=250,Pr=150,Rr=500;class Bi{constructor(e,t,n,i,o,a){if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],this.injector=null,this.width=0,this.height=0,this.transform="",this.currentSlide=0,this.spread=!0,this.orientationInternal=-1,this.container=e,this.positions=t,this.pub=n,this.injector=i??null,this.contentProtectionConfig=o||{},this.keyboardPeripheralsConfig=a||[],this.spreadPresentation=n.metadata.otherMetadata?.spread||ft.auto,this.pub.metadata.effectiveReadingProgression!==N.rtl&&this.pub.metadata.effectiveReadingProgression!==N.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Di(this.pub),this.containerHeightCached=e.clientHeight,this.bookElement=document.createElement("div"),this.bookElement.ariaLabel="Book",this.bookElement.tabIndex=-1,this.updateBookStyle(!0),this.spineElement=document.createElement("div"),this.spineElement.ariaLabel="Spine",this.bookElement.appendChild(this.spineElement),this.container.appendChild(this.bookElement),this.updateSpineStyle(!0),this.peripherals=new Ii(this),this.pub.readingOrder.items.forEach(s=>{const l=new Ai(this.peripherals,this.pub.metadata.effectiveReadingProgression,s.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.spineElement.appendChild(l.element),this.pool.set(s.href,l),l.width=100/this.length*(s.properties?.otherProperties.orientation===gt.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),l.height=this.height})}set listener(e){this._listener=e}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(e=!0,t=!0){this.currentSlide+this.perPage>this.length&&(this.currentSlide=this.length<=this.perPage?0:this.length-1),this.containerHeightCached=this.container.clientHeight,this.orientationInternal=-1,this.updateSpineStyle(!0),e&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!t,t)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((n,i)=>{let o=this.pub.readingOrder.items.findIndex(l=>l.href===i);const a=this.pub.readingOrder.items[o];if(n.width=100/this.length*(a.properties?.otherProperties.orientation===gt.landscape||a.properties?.otherProperties.addBlank?this.perPage:1),n.height=this.height,!n.loaded)return;const s=this.spreader.findByLink(a);n.update(this.spreadPosition(s,a))})},wr)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===N.rtl}get single(){return!this.spread||this.portrait}get perPage(){return this.spread&&!this.portrait?2:1}get threshold(){return 50}get portrait(){return this.spreadPresentation===ft.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(e,t=!0){let n="0";this.updateDimensions(),this.perPage>1&&(n=`${this.width/2}px`);const i={transition:e?`all ${t?Pr:Rr}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?n:"0",marginLeft:this.rtl?"0":n,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,i)}updateBookStyle(e=!1){if(e){const t={overflow:"hidden",direction:this.pub.metadata.effectiveReadingProgression,cursor:"",height:"100%",width:"100%",position:"relative",outline:"none",transition:this.peripherals?.dragState?"none":"transform .15s ease-in-out",touchAction:"none"};Object.assign(this.bookElement.style,t)}this.bookElement.style.transform=`scale(${this.peripherals?.scale||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(e){if(this.slength<=this.perPage)return;e=this.reAlign(e);const t=this.currentSlide;this.currentSlide=Math.min(Math.max(e,0),this.length-1),t!==this.currentSlide&&this.slideToCurrent(!1)}onChange(){this.peripherals.scale=1,this.updateBookStyle()}get offset(){return(this.rtl?1:-1)*this.currentSlide*(this.width/this.perPage)}get length(){if(this.single)return this.slength;const e=this.slength+this.nLandscape;return this.shift&&e%2===0?e+1:e}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(e){e===null?this.spread=!0:e===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(e,t=!0){if(this.updateDimensions(),e)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const n=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==n&&(this.transform=n,this.updateSpineStyle(!0,t),this.deselect())})});else{const n=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===n)return;this.transform=n,this.updateSpineStyle(!1),this.deselect()}}bounce(e=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(e?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+e,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===t&&(this.currentSlide+1,this.length),t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-e,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>URL.revokeObjectURL(a)),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}makeSpread(e){return this.perPage<2?[this.pub.readingOrder.items[e]]:this.spreader.currentSpread(e,this.perPage)}reAlign(e=this.currentSlide){return e%2&&!this.single&&e++,e}spreadPosition(e,t){return this.perPage<2||e.length<2?X.center:t.href===e[0].href?this.rtl?X.right:X.left:this.rtl?X.left:X.right}async waitForItem(e){if(this.inprogress.has(e)&&await this.inprogress.get(e),this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0?clearTimeout(t):await this.delayedShow.get(e),this.delayedTimeout.set(e,0),this.delayedShow.delete(e)}}async cancelShowing(e){if(this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0&&clearTimeout(t),this.delayedShow.delete(e)}}async update(e,t,n,i=!1){let o=this.pub.readingOrder.items.findIndex(l=>l.href===t.href);if(o<0)throw Error("Href not found in reading order");this.currentSlide!==o&&(this.currentSlide=this.reAlign(o),this.slideToCurrent(!0));const a=this.makeSpread(this.currentSlide);this.perPage>1&&o++;for(const l of a)await this.waitForItem(l.href);const s=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>o+Hi||p<o-Hi)&&(h.includes(d.href)||h.push(d.href)),p<o+Wi&&p>o-Wi&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(this.cancelShowing(d),await this.pool.get(d)?.unload())}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>URL.revokeObjectURL(d)),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{const p=e.readingOrder.findIndexWithHref(d),_=e.readingOrder.items[p];if(_){if(!this.blobs.has(d)){const U=await new xi(e,this.currentBaseURL||"",_,{injector:this.injector}).build(!0);this.blobs.set(d,U)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((R,U)=>{let Q=!1;const xe=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const Le=this.makeSpread(this.reAlign(p)),ta=this.spreadPosition(Le,_),no=this.pool.get(d);await no.load(n,this.blobs.get(d)),this.peripherals.isScaled||await no.show(ta),this.delayedShow.delete(d),Q=!0,R()},_r);setTimeout(()=>{!Q&&this.delayedShow.has(d)&&U(`Offscreen load timeout: ${d}`)},vr),this.delayedTimeout.set(d,xe)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=[];for(const d of a){const p=this.pool.get(d.href),_=this.blobs.get(d.href);_&&(this.cancelShowing(d.href),await p.load(n,_),await p.show(this.spreadPosition(a,d)),this.previousFrames.push(p),await p.activate(),f.push(p))}for(;this.previousFrames.length>0;){const d=this.previousFrames.shift();d&&!f.includes(d)&&await d.unfocus()}this.previousFrames=f,l()});for(const l of a)this.inprogress.set(l.href,s);await s;for(const l of a)this.inprogress.delete(l.href)}get currentFrames(){if(this.perPage<2){const t=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(t.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(t=>this.pool.get(t.href))}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}get viewport(){const e={readingOrder:[],progressions:new Map,positions:null};return(this.perPage<2?[this.pub.readingOrder.items[this.currentSlide]]:this.spreader.currentSpread(this.currentSlide,this.perPage)).forEach(n=>{e.readingOrder.push(n.href),e.progressions.set(n.href,{start:0,end:1})}),e.positions=this.getCurrentNumbers(),e}getCurrentNumbers(){if(this.perPage<2)return[this.pub.readingOrder.items[this.currentSlide].properties?.otherProperties.number];const e=this.spreader.currentSpread(this.currentSlide,this.perPage);return e.length>1?[e[0].properties?.otherProperties.number,e[e.length-1].properties?.otherProperties.number]:[e[0].properties?.otherProperties.number]}deselect(){this.currentFrames?.forEach(e=>e?.deselect())}}class ke{constructor(e={}){this.backgroundColor=I(e.backgroundColor),this.blendFilter=P(e.blendFilter),this.constraint=v(e.constraint),this.columnCount=v(e.columnCount),this.darkenFilter=he(e.darkenFilter),this.deprecatedFontSize=P(e.deprecatedFontSize),this.fontFamily=I(e.fontFamily),this.fontSize=M(e.fontSize,Te.range),this.fontSizeNormalize=P(e.fontSizeNormalize),this.fontOpticalSizing=P(e.fontOpticalSizing),this.fontWeight=M(e.fontWeight,ee.range),this.fontWidth=M(e.fontWidth,Me.range),this.hyphens=P(e.hyphens),this.invertFilter=he(e.invertFilter),this.invertGaijiFilter=he(e.invertGaijiFilter),this.iOSPatch=P(e.iOSPatch),this.iPadOSPatch=P(e.iPadOSPatch),this.letterSpacing=v(e.letterSpacing),this.ligatures=P(e.ligatures),this.lineHeight=v(e.lineHeight),this.linkColor=I(e.linkColor),this.noRuby=P(e.noRuby),this.pageGutter=v(e.pageGutter),this.paragraphIndent=v(e.paragraphIndent),this.paragraphSpacing=v(e.paragraphSpacing),this.scroll=P(e.scroll),this.scrollPaddingTop=v(e.scrollPaddingTop),this.scrollPaddingBottom=v(e.scrollPaddingBottom),this.scrollPaddingLeft=v(e.scrollPaddingLeft),this.scrollPaddingRight=v(e.scrollPaddingRight),this.selectionBackgroundColor=I(e.selectionBackgroundColor),this.selectionTextColor=I(e.selectionTextColor),this.textAlign=Ve(e.textAlign,Z),this.textColor=I(e.textColor),this.textNormalization=P(e.textNormalization),this.visitedColor=I(e.visitedColor),this.wordSpacing=v(e.wordSpacing),this.optimalLineLength=v(e.optimalLineLength),this.maximalLineLength=v(e.maximalLineLength),this.minimalLineLength=v(e.minimalLineLength)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new ke(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(n!=="maximalLineLength"||e[n]===null||e[n]>=(e.optimalLineLength??t.optimalLineLength??65))&&(n!=="minimalLineLength"||e[n]===null||e[n]<=(e.optimalLineLength??t.optimalLineLength??65))&&(t[n]=e[n]);return new ke(t)}}class ji{constructor(e){this.backgroundColor=I(e.backgroundColor)||null,this.blendFilter=P(e.blendFilter)??!1,this.constraint=v(e.constraint)||0,this.columnCount=v(e.columnCount)||null,this.darkenFilter=he(e.darkenFilter)??!1,this.deprecatedFontSize=P(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=I(e.fontFamily)||null,this.fontSize=M(e.fontSize,Te.range)||1,this.fontSizeNormalize=P(e.fontSizeNormalize)??!1,this.fontOpticalSizing=P(e.fontOpticalSizing)??null,this.fontWeight=M(e.fontWeight,ee.range)||null,this.fontWidth=M(e.fontWidth,Me.range)||null,this.hyphens=P(e.hyphens)??null,this.invertFilter=he(e.invertFilter)??!1,this.invertGaijiFilter=he(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(O.OS.iOS||O.OS.iPadOS)&&O.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:O.OS.iPadOS&&O.iOSRequest==="desktop",this.letterSpacing=v(e.letterSpacing)||null,this.ligatures=P(e.ligatures)??null,this.lineHeight=v(e.lineHeight)||null,this.linkColor=I(e.linkColor)||null,this.noRuby=P(e.noRuby)??!1,this.pageGutter=mt(v(e.pageGutter),20),this.paragraphIndent=v(e.paragraphIndent)??null,this.paragraphSpacing=v(e.paragraphSpacing)??null,this.scroll=P(e.scroll)??!1,this.scrollPaddingTop=v(e.scrollPaddingTop)??null,this.scrollPaddingBottom=v(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=v(e.scrollPaddingLeft)??null,this.scrollPaddingRight=v(e.scrollPaddingRight)??null,this.selectionBackgroundColor=I(e.selectionBackgroundColor)||null,this.selectionTextColor=I(e.selectionTextColor)||null,this.textAlign=Ve(e.textAlign,Z)||null,this.textColor=I(e.textColor)||null,this.textNormalization=P(e.textNormalization)??!1,this.visitedColor=I(e.visitedColor)||null,this.wordSpacing=v(e.wordSpacing)||null,this.optimalLineLength=v(e.optimalLineLength)||65,this.maximalLineLength=mt(Si(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=mt(yi(e.minimalLineLength,this.optimalLineLength),40),this.experiments=Kt(e.experiments)||null}}const Ee={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class sn{constructor(e,t,n){this.preferences=e,this.settings=t,this.metadata=n,this.layout=this.metadata?.effectiveLayout||b.reflowable}clear(){this.preferences=new ke({optimalLineLength:65})}updatePreference(e,t){this.preferences[e]=t}get backgroundColor(){return new T({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||Ee.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:e=>{this.updatePreference("backgroundColor",e??null)}})}get blendFilter(){return new A({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:e=>{this.updatePreference("blendFilter",e??null)}})}get columnCount(){return new T({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==b.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("columnCount",e??null)}})}get constraint(){return new T({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:e=>{this.updatePreference("constraint",e??null)}})}get darkenFilter(){return new E({initialValue:typeof this.preferences.darkenFilter=="boolean"?100:this.preferences.darkenFilter,effectiveValue:typeof this.settings.darkenFilter=="boolean"?100:this.settings.darkenFilter||0,isEffective:this.settings.darkenFilter!==null,onChange:e=>{this.updatePreference("darkenFilter",e??null)},supportedRange:le.range,step:le.step})}get deprecatedFontSize(){return new A({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("deprecatedFontSize",e??null)}})}get fontFamily(){return new T({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("fontFamily",e??null)}})}get fontSize(){return new E({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("fontSize",e??null)},supportedRange:Te.range,step:Te.step})}get fontSizeNormalize(){return new A({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==b.fixed&&this.preferences.fontSizeNormalize!==null,onChange:e=>{this.updatePreference("fontSizeNormalize",e??null)}})}get fontOpticalSizing(){return new A({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout!==b.fixed&&this.preferences.fontOpticalSizing!==null,onChange:e=>{this.updatePreference("fontOpticalSizing",e??null)}})}get fontWeight(){return new E({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==b.fixed&&this.preferences.fontWeight!==null,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:ee.range,step:ee.step})}get fontWidth(){return new E({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==b.fixed&&this.preferences.fontWidth!==null,onChange:e=>{this.updatePreference("fontWidth",e??null)},supportedRange:Me.range,step:Me.step})}get hyphens(){return new A({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==b.fixed&&this.metadata?.effectiveReadingProgression===N.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e??null)}})}get invertFilter(){return new E({initialValue:typeof this.preferences.invertFilter=="boolean"?100:this.preferences.invertFilter,effectiveValue:typeof this.settings.invertFilter=="boolean"?100:this.settings.invertFilter||0,isEffective:this.settings.invertFilter!==null,onChange:e=>{this.updatePreference("invertFilter",e??null)},supportedRange:le.range,step:le.step})}get invertGaijiFilter(){return new E({initialValue:typeof this.preferences.invertGaijiFilter=="boolean"?100:this.preferences.invertGaijiFilter,effectiveValue:typeof this.settings.invertGaijiFilter=="boolean"?100:this.settings.invertGaijiFilter||0,isEffective:this.preferences.invertGaijiFilter!==null,onChange:e=>{this.updatePreference("invertGaijiFilter",e??null)},supportedRange:le.range,step:le.step})}get iOSPatch(){return new A({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("iOSPatch",e??null)}})}get iPadOSPatch(){return new A({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("iPadOSPatch",e??null)}})}get letterSpacing(){return new E({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==b.fixed&&this.preferences.letterSpacing!==null,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Fe.range,step:Fe.step})}get ligatures(){return new A({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:(()=>{if(this.preferences.ligatures===null||this.layout===b.fixed)return!1;const e=this.metadata?.languages?.[0]?.toLowerCase();return!(e&&["zh","ja","ko","mn-mong"].some(t=>e.startsWith(t)))})(),onChange:e=>{this.updatePreference("ligatures",e??null)}})}get lineHeight(){return new E({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==b.fixed&&this.preferences.lineHeight!==null,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:Ne.range,step:Ne.step})}get linkColor(){return new T({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||Ee.RS__linkColor,isEffective:this.layout!==b.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e??null)}})}get maximalLineLength(){return new E({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:ce.range,step:ce.step})}get minimalLineLength(){return new E({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("minimalLineLength",e)},supportedRange:ce.range,step:ce.step})}get noRuby(){return new A({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==b.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:e=>{this.updatePreference("noRuby",e??null)}})}get optimalLineLength(){return new E({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("optimalLineLength",e)},supportedRange:ce.range,step:ce.step})}get pageGutter(){return new T({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==b.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("pageGutter",e??null)}})}get paragraphIndent(){return new E({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==b.fixed&&this.preferences.paragraphIndent!==null,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Ie.range,step:Ie.step})}get paragraphSpacing(){return new E({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==b.fixed&&this.preferences.paragraphSpacing!==null,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:De.range,step:De.step})}get scroll(){return new A({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("scroll",e??null)}})}get scrollPaddingTop(){return new T({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout!==b.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:e=>{this.updatePreference("scrollPaddingTop",e??null)}})}get scrollPaddingBottom(){return new T({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout!==b.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:e=>{this.updatePreference("scrollPaddingBottom",e??null)}})}get scrollPaddingLeft(){return new T({initialValue:this.preferences.scrollPaddingLeft,effectiveValue:this.settings.scrollPaddingLeft||0,isEffective:this.layout!==b.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingLeft!==null,onChange:e=>{this.updatePreference("scrollPaddingLeft",e??null)}})}get scrollPaddingRight(){return new T({initialValue:this.preferences.scrollPaddingRight,effectiveValue:this.settings.scrollPaddingRight||0,isEffective:this.layout!==b.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingRight!==null,onChange:e=>{this.updatePreference("scrollPaddingRight",e??null)}})}get selectionBackgroundColor(){return new T({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||Ee.RS__selectionBackgroundColor,isEffective:this.layout!==b.fixed&&this.preferences.selectionBackgroundColor!==null,onChange:e=>{this.updatePreference("selectionBackgroundColor",e??null)}})}get selectionTextColor(){return new T({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||Ee.RS__selectionTextColor,isEffective:this.layout!==b.fixed&&this.preferences.selectionTextColor!==null,onChange:e=>{this.updatePreference("selectionTextColor",e??null)}})}get textAlign(){return new Jt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||Z.start,isEffective:this.layout!==b.fixed&&this.preferences.textAlign!==null,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(Z)})}get textColor(){return new T({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||Ee.RS__textColor,isEffective:this.layout!==b.fixed&&this.preferences.textColor!==null,onChange:e=>{this.updatePreference("textColor",e??null)}})}get textNormalization(){return new A({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout!==b.fixed,onChange:e=>{this.updatePreference("textNormalization",e??null)}})}get visitedColor(){return new T({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||Ee.RS__visitedColor,isEffective:this.layout!==b.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e??null)}})}get wordSpacing(){return new E({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==b.fixed&&this.preferences.wordSpacing!==null,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:He.range,step:He.step})}}class ln{constructor(e,t){this.backgroundColor=e.backgroundColor||t.backgroundColor||null,this.blendFilter=typeof e.blendFilter=="boolean"?e.blendFilter:t.blendFilter??null,this.columnCount=e.columnCount!==void 0?e.columnCount:t.columnCount!==void 0?t.columnCount:null,this.constraint=e.constraint||t.constraint,this.darkenFilter=typeof e.darkenFilter=="boolean"?e.darkenFilter:t.darkenFilter??null,this.deprecatedFontSize=typeof e.deprecatedFontSize=="boolean"?e.deprecatedFontSize:t.deprecatedFontSize??null,this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontSize=e.fontSize!==void 0?e.fontSize:t.fontSize!==void 0?t.fontSize:null,this.fontSizeNormalize=typeof e.fontSizeNormalize=="boolean"?e.fontSizeNormalize:t.fontSizeNormalize??null,this.fontOpticalSizing=typeof e.fontOpticalSizing=="boolean"?e.fontOpticalSizing:t.fontOpticalSizing??null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.fontWidth=e.fontWidth!==void 0?e.fontWidth:t.fontWidth!==void 0?t.fontWidth:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.invertFilter=typeof e.invertFilter=="boolean"?e.invertFilter:t.invertFilter??null,this.invertGaijiFilter=typeof e.invertGaijiFilter=="boolean"?e.invertGaijiFilter:t.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||e.iOSPatch===!1?!1:e.iOSPatch===!0?(O.OS.iOS||O.OS.iPadOS)&&O.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?O.OS.iPadOS&&O.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.linkColor=e.linkColor||t.linkColor||null,this.maximalLineLength=e.maximalLineLength===null?null:e.maximalLineLength||t.maximalLineLength||null,this.minimalLineLength=e.minimalLineLength===null?null:e.minimalLineLength||t.minimalLineLength||null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.optimalLineLength=e.optimalLineLength||t.optimalLineLength,this.pageGutter=e.pageGutter!==void 0?e.pageGutter:t.pageGutter!==void 0?t.pageGutter:null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.scroll=typeof e.scroll=="boolean"?e.scroll:t.scroll??null,this.scrollPaddingTop=e.scrollPaddingTop!==void 0?e.scrollPaddingTop:t.scrollPaddingTop!==void 0?t.scrollPaddingTop:null,this.scrollPaddingBottom=e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:null,this.scrollPaddingLeft=e.scrollPaddingLeft!==void 0?e.scrollPaddingLeft:t.scrollPaddingLeft!==void 0?t.scrollPaddingLeft:null,this.scrollPaddingRight=e.scrollPaddingRight!==void 0?e.scrollPaddingRight:t.scrollPaddingRight!==void 0?t.scrollPaddingRight:null,this.selectionBackgroundColor=e.selectionBackgroundColor||t.selectionBackgroundColor||null,this.selectionTextColor=e.selectionTextColor||t.selectionTextColor||null,this.textAlign=e.textAlign||t.textAlign||null,this.textColor=e.textColor||t.textColor||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.visitedColor=e.visitedColor||t.visitedColor||null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null,this.experiments=t.experiments||null}}function Xe(r){const e=getComputedStyle(r),t=parseFloat(e.paddingLeft||"0"),n=parseFloat(e.paddingRight||"0");return r.clientWidth-t-n}function kr(r){const e=getComputedStyle(r),t=parseFloat(e.paddingTop||"0"),n=parseFloat(e.paddingBottom||"0");return r.clientHeight-t-n}class cn extends Ge{constructor(e){super(),this.a11yNormalize=e.a11yNormalize??null,this.backgroundColor=e.backgroundColor??null,this.blendFilter=e.blendFilter??null,this.bodyHyphens=e.bodyHyphens??null,this.colCount=e.colCount??null,this.darkenFilter=e.darkenFilter??null,this.deprecatedFontSize=e.deprecatedFontSize??null,this.fontFamily=e.fontFamily??null,this.fontOpticalSizing=e.fontOpticalSizing??null,this.fontSize=e.fontSize??null,this.fontSizeNormalize=e.fontSizeNormalize??null,this.fontWeight=e.fontWeight??null,this.fontWidth=e.fontWidth??null,this.invertFilter=e.invertFilter??null,this.invertGaijiFilter=e.invertGaijiFilter??null,this.iOSPatch=e.iOSPatch??null,this.iPadOSPatch=e.iPadOSPatch??null,this.letterSpacing=e.letterSpacing??null,this.ligatures=e.ligatures??null,this.lineHeight=e.lineHeight??null,this.lineLength=e.lineLength??null,this.linkColor=e.linkColor??null,this.noRuby=e.noRuby??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.textAlign=e.textAlign??null,this.textColor=e.textColor??null,this.view=e.view??null,this.visitedColor=e.visitedColor??null,this.wordSpacing=e.wordSpacing??null}toCSSProperties(){const e={};return this.a11yNormalize&&(e["--USER__a11yNormalize"]=this.toFlag("a11y")),this.backgroundColor&&(e["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(e["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(e["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(e["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?e["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(e["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(e["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(e["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(e["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(e["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(e["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(e["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(e["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?e["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(e["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?e["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(e["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(e["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(e["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(e["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(e["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(e["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(e["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(e["--USER__linkColor"]=this.linkColor),this.noRuby&&(e["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(e["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(e["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(e["--USER__textAlign"]=this.textAlign),this.textColor&&(e["--USER__textColor"]=this.textColor),this.view&&(e["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(e["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(e["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),e}}class Gi extends Ge{constructor(e){super(),this.backgroundColor=e.backgroundColor??null,this.baseFontFamily=e.baseFontFamily??null,this.baseFontSize=e.baseFontSize??null,this.baseLineHeight=e.baseLineHeight??null,this.boxSizingMedia=e.boxSizingMedia??null,this.boxSizingTable=e.boxSizingTable??null,this.colWidth=e.colWidth??null,this.colCount=e.colCount??null,this.colGap=e.colGap??null,this.codeFontFamily=e.codeFontFamily??null,this.compFontFamily=e.compFontFamily??null,this.defaultLineLength=e.defaultLineLength??null,this.flowSpacing=e.flowSpacing??null,this.humanistTf=e.humanistTf??null,this.linkColor=e.linkColor??null,this.maxMediaWidth=e.maxMediaWidth??null,this.maxMediaHeight=e.maxMediaHeight??null,this.modernTf=e.modernTf??null,this.monospaceTf=e.monospaceTf??null,this.noOverflow=e.noOverflow??null,this.noVerticalPagination=e.noVerticalPagination??null,this.oldStyleTf=e.oldStyleTf??null,this.pageGutter=e.pageGutter??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.primaryColor=e.primaryColor??null,this.scrollPaddingBottom=e.scrollPaddingBottom??null,this.scrollPaddingLeft=e.scrollPaddingLeft??null,this.scrollPaddingRight=e.scrollPaddingRight??null,this.scrollPaddingTop=e.scrollPaddingTop??null,this.sansSerifJa=e.sansSerifJa??null,this.sansSerifJaV=e.sansSerifJaV??null,this.sansTf=e.sansTf??null,this.secondaryColor=e.secondaryColor??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.serifJa=e.serifJa??null,this.serifJaV=e.serifJaV??null,this.textColor=e.textColor??null,this.typeScale=e.typeScale??null,this.visitedColor=e.visitedColor??null,this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.backgroundColor&&(e["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(e["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(e["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(e["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(e["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(e["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(e["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(e["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(e["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(e["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(e["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(e["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(e["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(e["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(e["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(e["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(e["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(e["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(e["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(e["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(e["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(e["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(e["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(e["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(e["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(e["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(e["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(e["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(e["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingLeft!=null&&(e["--RS__scrollPaddingLeft"]=this.toPx(this.scrollPaddingLeft)),this.scrollPaddingRight!=null&&(e["--RS__scrollPaddingRight"]=this.toPx(this.scrollPaddingRight)),this.scrollPaddingTop!=null&&(e["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(e["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(e["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(e["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(e["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(e["--RS__textColor"]=this.textColor),this.typeScale&&(e["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(e["--RS__visitedColor"]=this.visitedColor),this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=ut[t].value}),e}}class Vi{constructor(e){this.rsProperties=e.rsProperties,this.userProperties=e.userProperties,this.lineLengths=e.lineLengths,this.container=e.container,this.containerParent=e.container.parentElement||document.documentElement,this.constraint=e.constraint,this.isCJKVertical=e.isCJKVertical??!1,this.cachedColCount=e.userProperties.colCount,this.effectiveContainerWidth=Xe(this.containerParent)}update(e){this.cachedColCount=e.columnCount,e.constraint!==this.constraint&&(this.constraint=e.constraint),e.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=e.pageGutter),e.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=e.scrollPaddingBottom),e.scrollPaddingLeft!==this.rsProperties.scrollPaddingLeft&&(this.rsProperties.scrollPaddingLeft=e.scrollPaddingLeft),e.scrollPaddingRight!==this.rsProperties.scrollPaddingRight&&(this.rsProperties.scrollPaddingRight=e.scrollPaddingRight),e.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=e.scrollPaddingTop),e.experiments!==this.rsProperties.experiments&&(this.rsProperties.experiments=e.experiments),this.lineLengths.update({fontFace:e.fontFamily,letterSpacing:e.letterSpacing,padding:e.scroll?(e.scrollPaddingLeft||0)+(e.scrollPaddingRight||0):(e.pageGutter||0)*2,wordSpacing:e.wordSpacing,optimalChars:e.optimalLineLength,minChars:e.minimalLineLength,maxChars:e.maximalLineLength});const t=this.updateLayout(e.fontSize,e.deprecatedFontSize||e.iOSPatch,e.scroll,e.columnCount);t?.effectiveContainerWidth&&(this.effectiveContainerWidth=t?.effectiveContainerWidth);const n={a11yNormalize:e.textNormalization,backgroundColor:e.backgroundColor,blendFilter:e.blendFilter,bodyHyphens:typeof e.hyphens!="boolean"?null:e.hyphens?"auto":"none",colCount:t?.colCount,darkenFilter:e.darkenFilter,deprecatedFontSize:e.deprecatedFontSize,fontFamily:e.fontFamily,fontOpticalSizing:typeof e.fontOpticalSizing!="boolean"?null:e.fontOpticalSizing?"auto":"none",fontSize:e.fontSize,fontSizeNormalize:e.fontSizeNormalize,fontWeight:e.fontWeight,fontWidth:e.fontWidth,invertFilter:e.invertFilter,invertGaijiFilter:e.invertGaijiFilter,iOSPatch:e.iOSPatch,iPadOSPatch:e.iPadOSPatch,letterSpacing:e.letterSpacing,ligatures:typeof e.ligatures!="boolean"?null:e.ligatures?"common-ligatures":"none",lineHeight:e.lineHeight,lineLength:t?.effectiveLineLength,linkColor:e.linkColor,noRuby:e.noRuby,paraIndent:e.paragraphIndent,paraSpacing:e.paragraphSpacing,selectionBackgroundColor:e.selectionBackgroundColor,selectionTextColor:e.selectionTextColor,textAlign:e.textAlign,textColor:e.textColor,view:typeof e.scroll!="boolean"?null:e.scroll?"scroll":"paged",visitedColor:e.visitedColor,wordSpacing:e.wordSpacing};this.userProperties=new cn(n)}updateLayout(e,t,n,i){return this.isCJKVertical?this.computeCJKVerticalLength(e,t):n??this.userProperties.view==="scroll"?this.computeScrollLength(e,t):this.paginate(e,t,i)}getCompensatedMetrics(e,t){const n=e||this.userProperties.fontSize||1,i=n<1?1/n:t?n:1;return{zoomFactor:n,zoomCompensation:i,optimal:Math.round(this.lineLengths.optimalLineLength)*n,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*n):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*n):null}}paginate(e,t,n){const i=Math.round(Xe(this.containerParent)-this.constraint),o=this.getCompensatedMetrics(e,t),{zoomCompensation:a,optimal:s,minimal:l,maximal:c}=o,h=()=>i>=s&&c!==null?Math.min(Math.round(c*a),i):i;let u=1,m=i;if(n===void 0)return{colCount:void 0,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u*a)};if(n===null)if(i>=s&&c!==null){u=Math.floor(i/s);const f=Math.round(u*(c*a));m=Math.min(f,i)}else m=h();else if(n>1){const f=Math.round(n*(l!==null?l:s));if(i>=f)if(u=n,c===null)m=i;else{const d=Math.round(u*(c*a));m=Math.min(d,i)}else if(l!==null&&i<Math.round(n*l))if(u=Math.floor(i/l),u<=1)u=1,m=h();else{const d=Math.round(u*(s*a));m=Math.min(d,i)}else{u=n;const d=Math.round(u*(s*a));m=Math.min(d,i)}}else u=1,m=h();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*a)}}computeCJKVerticalLength(e,t){const n=Math.round(Xe(this.containerParent)-this.constraint),i=Math.round(kr(this.containerParent)),o=this.getCompensatedMetrics(e,t),a=o.maximal!==null?Math.min(Math.round(o.maximal*o.zoomCompensation),i):i;return{colCount:void 0,effectiveContainerWidth:n,effectiveLineLength:a}}computeScrollLength(e,t){const n=Math.round(Xe(this.containerParent)-this.constraint),i=this.getCompensatedMetrics(e&&(e<1||t)?e:1,t),o=i.zoomCompensation,a=i.optimal,s=i.maximal;let l,c=n,h=Math.round(a*o);if(s===null)h=n;else{const u=Math.min(Math.round(s*o),n);h=t?u:Math.round(u*o)}return{colCount:l,effectiveContainerWidth:c,effectiveLineLength:h}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const e=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=e.colCount,this.userProperties.lineLength=e.effectiveLineLength,this.effectiveContainerWidth=e.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const Er=`// Note: we aren't blocking some of the events right now to try and be as nonintrusive as possible.
414
+ Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(i){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const s=this.manager.currentSlide*(this.manager.width/this.manager.perPage),l=this.pan.endX-this.pan.startX,c=this.manager.rtl?s+l:s-l;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*c}px, 0, 0)`})})}}dblclickHandler(e){clearTimeout(this.dtimer),this.pdblclick=!0,this.dtimer=window.setTimeout(()=>this.pdblclick=!1,200),!this.disableDblClick&&this.isScaled&&(this.scale=1)}get isScaled(){return this.scale>1}addTouch(e){e.touches=[{pageX:e.pageX,pageY:e.pageY}]}mousedownHandler(e){this.isScaled&&(this.addTouch(e),this.touchstartHandler(e))}mouseupHandler(e){this.isScaled&&this.touchendHandler(e)}mousemoveHandler(e){this.isScaled&&e.buttons>0&&(e.preventDefault(),this.addTouch(e),this.touchmoveHandler(e))}updateAfterDrag(){const e=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),t=Math.abs(e);e>0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):e<0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}var gt=(r=>(r.auto="auto",r.landscape="landscape",r.portrait="portrait",r))(gt||{}),ft=(r=>(r.auto="auto",r.both="both",r.none="none",r.landscape="landscape",r))(ft||{});class Hi{constructor(e){this.shift=!0,this.spreads=[],this.nLandscape=0,this.index(e),this.testShift(e),console.log(`Indexed ${this.spreads.length} spreads for ${e.readingOrder.items.length} items`)}index(e,t=!1){this.nLandscape=0,e.readingOrder.items.forEach((n,i)=>{t||(e.readingOrder.items[i]=n.addProperties({number:i+1,isImage:n.type?.indexOf("image/")===0}));const o=n.properties?.otherProperties.orientation==="landscape";(!n.properties?.page||t)&&(n.properties=n.properties?.add({page:o?"center":((this.shift?0:1)+i-this.nLandscape)%2?e.metadata.readingProgression===M.rtl?"right":"left":e.metadata.readingProgression===M.rtl?"left":"right"})),(o||n.properties?.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(e.readingOrder)}testShift(e){let t=!1;this.spreads.forEach((n,i)=>{if(n.length>1)return;const o=n[0],a=o.properties?.otherProperties.orientation;i===0&&(a==="landscape"||a!=="portrait"&&((o.width||0)>(o.height||0)||o.properties?.otherProperties.spread==="both"))&&(this.shift=!1),t&&o.properties?.page===K.center&&this.spreads[i-1][0].addProperties({addBlank:!0}),a==="portrait"&&o.properties?.page!=="center"&&o.properties?.otherProperties.number>1?t=!0:t=!1}),this.shift||this.index(e,!0)}buildSpreads(e){let t=[];e.items.forEach((n,i)=>{!i&&this.shift?this.spreads.push([n]):n.properties?.page===K.center?(t.length>0&&this.spreads.push(t),this.spreads.push([n]),t=[]):t.length>=2?(this.spreads.push(t),t=[n]):t.push(n)}),t.length>0&&this.spreads.push(t)}currentSpread(e,t){return this.spreads[Math.min(Math.floor(e/t),this.spreads.length-1)]}findByLink(e){return this.spreads.find(t=>t.includes(e))||void 0}}const Di=8,Wi=5,Cr=300,kr=15e3,Er=250,xr=150,Fr=500;class Bi{constructor(e,t,n,i,o,a){if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],this.injector=null,this.width=0,this.height=0,this.transform="",this.currentSlide=0,this.spread=!0,this.orientationInternal=-1,this.container=e,this.positions=t,this.pub=n,this.injector=i??null,this.contentProtectionConfig=o||{},this.keyboardPeripheralsConfig=a||[],this.spreadPresentation=n.metadata.otherMetadata?.spread||ft.auto,this.pub.metadata.effectiveReadingProgression!==M.rtl&&this.pub.metadata.effectiveReadingProgression!==M.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Hi(this.pub),this.containerHeightCached=e.clientHeight,this.bookElement=document.createElement("div"),this.bookElement.ariaLabel="Book",this.bookElement.tabIndex=-1,this.updateBookStyle(!0),this.spineElement=document.createElement("div"),this.spineElement.ariaLabel="Spine",this.bookElement.appendChild(this.spineElement),this.container.appendChild(this.bookElement),this.updateSpineStyle(!0),this.peripherals=new Ii(this),this.pub.readingOrder.items.forEach(s=>{const l=new Oi(this.peripherals,this.pub.metadata.effectiveReadingProgression,s.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.spineElement.appendChild(l.element),this.pool.set(s.href,l),l.width=100/this.length*(s.properties?.otherProperties.orientation===gt.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),l.height=this.height})}set listener(e){this._listener=e}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(e=!0,t=!0){this.currentSlide+this.perPage>this.length&&(this.currentSlide=this.length<=this.perPage?0:this.length-1),this.containerHeightCached=this.container.clientHeight,this.orientationInternal=-1,this.updateSpineStyle(!0),e&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!t,t)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((n,i)=>{let o=this.pub.readingOrder.items.findIndex(l=>l.href===i);const a=this.pub.readingOrder.items[o];if(n.width=100/this.length*(a.properties?.otherProperties.orientation===gt.landscape||a.properties?.otherProperties.addBlank?this.perPage:1),n.height=this.height,!n.loaded)return;const s=this.spreader.findByLink(a);n.update(this.spreadPosition(s,a))})},Er)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===M.rtl}get single(){return!this.spread||this.portrait}get perPage(){return this.spread&&!this.portrait?2:1}get threshold(){return 50}get portrait(){return this.spreadPresentation===ft.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(e,t=!0){let n="0";this.updateDimensions(),this.perPage>1&&(n=`${this.width/2}px`);const i={transition:e?`all ${t?xr:Fr}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?n:"0",marginLeft:this.rtl?"0":n,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,i)}updateBookStyle(e=!1){if(e){const t={overflow:"hidden",direction:this.pub.metadata.effectiveReadingProgression,cursor:"",height:"100%",width:"100%",position:"relative",outline:"none",transition:this.peripherals?.dragState?"none":"transform .15s ease-in-out",touchAction:"none"};Object.assign(this.bookElement.style,t)}this.bookElement.style.transform=`scale(${this.peripherals?.scale||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(e){if(this.slength<=this.perPage)return;e=this.reAlign(e);const t=this.currentSlide;this.currentSlide=Math.min(Math.max(e,0),this.length-1),t!==this.currentSlide&&this.slideToCurrent(!1)}onChange(){this.peripherals.scale=1,this.updateBookStyle()}get offset(){return(this.rtl?1:-1)*this.currentSlide*(this.width/this.perPage)}get length(){if(this.single)return this.slength;const e=this.slength+this.nLandscape;return this.shift&&e%2===0?e+1:e}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(e){e===null?this.spread=!0:e===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(e,t=!0){if(this.updateDimensions(),e)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const n=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==n&&(this.transform=n,this.updateSpineStyle(!0,t),this.deselect())})});else{const n=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===n)return;this.transform=n,this.updateSpineStyle(!1),this.deselect()}}bounce(e=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(e?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+e,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===t&&(this.currentSlide+1,this.length),t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(e=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-e,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let e=this.inprogress.values(),t=e.next();const n=[];for(;t.value;)n.push(t.value),t=e.next();n.length>0&&await Promise.allSettled(n),this.inprogress.clear();let i=this.pool.values(),o=i.next();for(;o.value;)await o.value.destroy(),o=i.next();this.pool.clear(),this.blobs.forEach(a=>URL.revokeObjectURL(a)),this.injector?.dispose(),this.container.childNodes.forEach(a=>{(a.nodeType===Node.ELEMENT_NODE||a.nodeType===Node.TEXT_NODE)&&a.remove()})}makeSpread(e){return this.perPage<2?[this.pub.readingOrder.items[e]]:this.spreader.currentSpread(e,this.perPage)}reAlign(e=this.currentSlide){return e%2&&!this.single&&e++,e}spreadPosition(e,t){return this.perPage<2||e.length<2?K.center:t.href===e[0].href?this.rtl?K.right:K.left:this.rtl?K.left:K.right}async waitForItem(e){if(this.inprogress.has(e)&&await this.inprogress.get(e),this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0?clearTimeout(t):await this.delayedShow.get(e),this.delayedTimeout.set(e,0),this.delayedShow.delete(e)}}async cancelShowing(e){if(this.delayedShow.has(e)){const t=this.delayedTimeout.get(e);t>0&&clearTimeout(t),this.delayedShow.delete(e)}}async update(e,t,n,i=!1){let o=this.pub.readingOrder.items.findIndex(l=>l.href===t.href);if(o<0)throw Error("Href not found in reading order");this.currentSlide!==o&&(this.currentSlide=this.reAlign(o),this.slideToCurrent(!0));const a=this.makeSpread(this.currentSlide);this.perPage>1&&o++;for(const l of a)await this.waitForItem(l.href);const s=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>o+Di||p<o-Di)&&(h.includes(d.href)||h.push(d.href)),p<o+Wi&&p>o-Wi&&(u.includes(d.href)||u.push(d.href))}),h.forEach(async d=>{u.includes(d)||this.pool.has(d)&&(this.cancelShowing(d),await this.pool.get(d)?.unload())}),this.currentBaseURL!==void 0&&e.baseURL!==this.currentBaseURL&&(this.blobs.forEach(d=>URL.revokeObjectURL(d)),this.blobs.clear()),this.currentBaseURL=e.baseURL;const m=async d=>{const p=e.readingOrder.findIndexWithHref(d),b=e.readingOrder.items[p];if(b){if(!this.blobs.has(d)){const A=await new xi(e,this.currentBaseURL||"",b,{injector:this.injector}).build(!0);this.blobs.set(d,A)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((P,A)=>{let Q=!1;const xe=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const Fe=this.makeSpread(this.reAlign(p)),aa=this.spreadPosition(Fe,b),no=this.pool.get(d);await no.load(n,this.blobs.get(d)),this.peripherals.isScaled||await no.show(aa),this.delayedShow.delete(d),Q=!0,P()},Cr);setTimeout(()=>{!Q&&this.delayedShow.has(d)&&A(`Offscreen load timeout: ${d}`)},kr),this.delayedTimeout.set(d,xe)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const f=[];for(const d of a){const p=this.pool.get(d.href),b=this.blobs.get(d.href);b&&(this.cancelShowing(d.href),await p.load(n,b),await p.show(this.spreadPosition(a,d)),this.previousFrames.push(p),await p.activate(),f.push(p))}for(;this.previousFrames.length>0;){const d=this.previousFrames.shift();d&&!f.includes(d)&&await d.unfocus()}this.previousFrames=f,l()});for(const l of a)this.inprogress.set(l.href,s);await s;for(const l of a)this.inprogress.delete(l.href)}get currentFrames(){if(this.perPage<2){const t=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(t.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(t=>this.pool.get(t.href))}get currentBounds(){const e={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const n=t.realSize;e.x=Math.min(e.x,n.x),e.y=Math.min(e.y,n.y),e.width+=n.width,e.height=Math.max(e.height,n.height),e.top=Math.min(e.top,n.top),e.right=Math.min(e.right,n.right),e.bottom=Math.min(e.bottom,n.bottom),e.left=Math.min(e.left,n.left)}),e}get viewport(){const e={readingOrder:[],progressions:new Map,positions:null};return(this.perPage<2?[this.pub.readingOrder.items[this.currentSlide]]:this.spreader.currentSpread(this.currentSlide,this.perPage)).forEach(n=>{e.readingOrder.push(n.href),e.progressions.set(n.href,{start:0,end:1})}),e.positions=this.getCurrentNumbers(),e}getCurrentNumbers(){if(this.perPage<2)return[this.pub.readingOrder.items[this.currentSlide].properties?.otherProperties.number];const e=this.spreader.currentSpread(this.currentSlide,this.perPage);return e.length>1?[e[0].properties?.otherProperties.number,e[e.length-1].properties?.otherProperties.number]:[e[0].properties?.otherProperties.number]}deselect(){this.currentFrames?.forEach(e=>e?.deselect())}}class Ce{constructor(e={}){this.backgroundColor=I(e.backgroundColor),this.blendFilter=R(e.blendFilter),this.constraint=v(e.constraint),this.columnCount=v(e.columnCount),this.darkenFilter=he(e.darkenFilter),this.deprecatedFontSize=R(e.deprecatedFontSize),this.fontFamily=I(e.fontFamily),this.fontSize=T(e.fontSize,Ue.range),this.fontSizeNormalize=R(e.fontSizeNormalize),this.fontOpticalSizing=R(e.fontOpticalSizing),this.fontWeight=T(e.fontWeight,ee.range),this.fontWidth=T(e.fontWidth,Te.range),this.hyphens=R(e.hyphens),this.invertFilter=he(e.invertFilter),this.invertGaijiFilter=he(e.invertGaijiFilter),this.iOSPatch=R(e.iOSPatch),this.iPadOSPatch=R(e.iPadOSPatch),this.letterSpacing=v(e.letterSpacing),this.ligatures=R(e.ligatures),this.lineHeight=v(e.lineHeight),this.linkColor=I(e.linkColor),this.noRuby=R(e.noRuby),this.pageGutter=v(e.pageGutter),this.paragraphIndent=v(e.paragraphIndent),this.paragraphSpacing=v(e.paragraphSpacing),this.scroll=R(e.scroll),this.scrollPaddingTop=v(e.scrollPaddingTop),this.scrollPaddingBottom=v(e.scrollPaddingBottom),this.scrollPaddingLeft=v(e.scrollPaddingLeft),this.scrollPaddingRight=v(e.scrollPaddingRight),this.selectionBackgroundColor=I(e.selectionBackgroundColor),this.selectionTextColor=I(e.selectionTextColor),this.textAlign=Ve(e.textAlign,J),this.textColor=I(e.textColor),this.textNormalization=R(e.textNormalization),this.visitedColor=I(e.visitedColor),this.wordSpacing=v(e.wordSpacing),this.optimalLineLength=v(e.optimalLineLength),this.maximalLineLength=v(e.maximalLineLength),this.minimalLineLength=v(e.minimalLineLength)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Ce(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(n!=="maximalLineLength"||e[n]===null||e[n]>=(e.optimalLineLength??t.optimalLineLength??65))&&(n!=="minimalLineLength"||e[n]===null||e[n]<=(e.optimalLineLength??t.optimalLineLength??65))&&(t[n]=e[n]);return new Ce(t)}}class ji{constructor(e){this.backgroundColor=I(e.backgroundColor)||null,this.blendFilter=R(e.blendFilter)??!1,this.constraint=v(e.constraint)||0,this.columnCount=v(e.columnCount)||null,this.darkenFilter=he(e.darkenFilter)??!1,this.deprecatedFontSize=R(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=I(e.fontFamily)||null,this.fontSize=T(e.fontSize,Ue.range)||1,this.fontSizeNormalize=R(e.fontSizeNormalize)??!1,this.fontOpticalSizing=R(e.fontOpticalSizing)??null,this.fontWeight=T(e.fontWeight,ee.range)||null,this.fontWidth=T(e.fontWidth,Te.range)||null,this.hyphens=R(e.hyphens)??null,this.invertFilter=he(e.invertFilter)??!1,this.invertGaijiFilter=he(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:L.OS.iPadOS&&L.iOSRequest==="desktop",this.letterSpacing=v(e.letterSpacing)||null,this.ligatures=R(e.ligatures)??null,this.lineHeight=v(e.lineHeight)||null,this.linkColor=I(e.linkColor)||null,this.noRuby=R(e.noRuby)??!1,this.pageGutter=mt(v(e.pageGutter),20),this.paragraphIndent=v(e.paragraphIndent)??null,this.paragraphSpacing=v(e.paragraphSpacing)??null,this.scroll=R(e.scroll)??!1,this.scrollPaddingTop=v(e.scrollPaddingTop)??null,this.scrollPaddingBottom=v(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=v(e.scrollPaddingLeft)??null,this.scrollPaddingRight=v(e.scrollPaddingRight)??null,this.selectionBackgroundColor=I(e.selectionBackgroundColor)||null,this.selectionTextColor=I(e.selectionTextColor)||null,this.textAlign=Ve(e.textAlign,J)||null,this.textColor=I(e.textColor)||null,this.textNormalization=R(e.textNormalization)??!1,this.visitedColor=I(e.visitedColor)||null,this.wordSpacing=v(e.wordSpacing)||null,this.optimalLineLength=v(e.optimalLineLength)||65,this.maximalLineLength=mt(_i(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=mt(yi(e.minimalLineLength,this.optimalLineLength),40),this.experiments=qt(e.experiments)||null}}const ke={backgroundColor:"#FFFFFF",textColor:"#121212",linkColor:"#0000EE",visitedColor:"#551A8B",selectionBackgroundColor:"#b4d8fe",selectionTextColor:"inherit"};class sn{constructor(e,t,n){this.preferences=e,this.settings=t,this.metadata=n,this.layout=this.metadata?.effectiveLayout||S.reflowable}clear(){this.preferences=new Ce({optimalLineLength:65})}updatePreference(e,t){this.preferences[e]=t}get backgroundColor(){return new U({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||ke.backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:e=>{this.updatePreference("backgroundColor",e??null)}})}get blendFilter(){return new O({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:e=>{this.updatePreference("blendFilter",e??null)}})}get columnCount(){return new U({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==S.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("columnCount",e??null)}})}get constraint(){return new U({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:e=>{this.updatePreference("constraint",e??null)}})}get darkenFilter(){return new k({initialValue:typeof this.preferences.darkenFilter=="boolean"?100:this.preferences.darkenFilter,effectiveValue:typeof this.settings.darkenFilter=="boolean"?100:this.settings.darkenFilter||0,isEffective:this.settings.darkenFilter!==null,onChange:e=>{this.updatePreference("darkenFilter",e??null)},supportedRange:le.range,step:le.step})}get deprecatedFontSize(){return new O({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("deprecatedFontSize",e??null)}})}get fontFamily(){return new U({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("fontFamily",e??null)}})}get fontSize(){return new k({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("fontSize",e??null)},supportedRange:Ue.range,step:Ue.step})}get fontSizeNormalize(){return new O({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==S.fixed&&this.preferences.fontSizeNormalize!==null,onChange:e=>{this.updatePreference("fontSizeNormalize",e??null)}})}get fontOpticalSizing(){return new O({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout!==S.fixed&&this.preferences.fontOpticalSizing!==null,onChange:e=>{this.updatePreference("fontOpticalSizing",e??null)}})}get fontWeight(){return new k({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==S.fixed&&this.preferences.fontWeight!==null,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:ee.range,step:ee.step})}get fontWidth(){return new k({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==S.fixed&&this.preferences.fontWidth!==null,onChange:e=>{this.updatePreference("fontWidth",e??null)},supportedRange:Te.range,step:Te.step})}get hyphens(){return new O({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==S.fixed&&this.metadata?.effectiveReadingProgression===M.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e??null)}})}get invertFilter(){return new k({initialValue:typeof this.preferences.invertFilter=="boolean"?100:this.preferences.invertFilter,effectiveValue:typeof this.settings.invertFilter=="boolean"?100:this.settings.invertFilter||0,isEffective:this.settings.invertFilter!==null,onChange:e=>{this.updatePreference("invertFilter",e??null)},supportedRange:le.range,step:le.step})}get invertGaijiFilter(){return new k({initialValue:typeof this.preferences.invertGaijiFilter=="boolean"?100:this.preferences.invertGaijiFilter,effectiveValue:typeof this.settings.invertGaijiFilter=="boolean"?100:this.settings.invertGaijiFilter||0,isEffective:this.preferences.invertGaijiFilter!==null,onChange:e=>{this.updatePreference("invertGaijiFilter",e??null)},supportedRange:le.range,step:le.step})}get iOSPatch(){return new O({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("iOSPatch",e??null)}})}get iPadOSPatch(){return new O({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("iPadOSPatch",e??null)}})}get letterSpacing(){return new k({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==S.fixed&&this.preferences.letterSpacing!==null,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Ne.range,step:Ne.step})}get ligatures(){return new O({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:(()=>{if(this.preferences.ligatures===null||this.layout===S.fixed)return!1;const e=this.metadata?.languages?.[0]?.toLowerCase();return!(e&&["zh","ja","ko","mn-mong"].some(t=>e.startsWith(t)))})(),onChange:e=>{this.updatePreference("ligatures",e??null)}})}get lineHeight(){return new k({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==S.fixed&&this.preferences.lineHeight!==null,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:Me.range,step:Me.step})}get linkColor(){return new U({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||ke.linkColor,isEffective:this.layout!==S.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e??null)}})}get maximalLineLength(){return new k({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:ce.range,step:ce.step})}get minimalLineLength(){return new k({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("minimalLineLength",e)},supportedRange:ce.range,step:ce.step})}get noRuby(){return new O({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==S.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:e=>{this.updatePreference("noRuby",e??null)}})}get optimalLineLength(){return new k({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("optimalLineLength",e)},supportedRange:ce.range,step:ce.step})}get pageGutter(){return new U({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==S.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("pageGutter",e??null)}})}get paragraphIndent(){return new k({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==S.fixed&&this.preferences.paragraphIndent!==null,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Ie.range,step:Ie.step})}get paragraphSpacing(){return new k({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==S.fixed&&this.preferences.paragraphSpacing!==null,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:He.range,step:He.step})}get scroll(){return new O({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("scroll",e??null)}})}get scrollPaddingTop(){return new U({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout!==S.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:e=>{this.updatePreference("scrollPaddingTop",e??null)}})}get scrollPaddingBottom(){return new U({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout!==S.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:e=>{this.updatePreference("scrollPaddingBottom",e??null)}})}get scrollPaddingLeft(){return new U({initialValue:this.preferences.scrollPaddingLeft,effectiveValue:this.settings.scrollPaddingLeft||0,isEffective:this.layout!==S.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingLeft!==null,onChange:e=>{this.updatePreference("scrollPaddingLeft",e??null)}})}get scrollPaddingRight(){return new U({initialValue:this.preferences.scrollPaddingRight,effectiveValue:this.settings.scrollPaddingRight||0,isEffective:this.layout!==S.fixed&&!!this.settings.scroll&&this.preferences.scrollPaddingRight!==null,onChange:e=>{this.updatePreference("scrollPaddingRight",e??null)}})}get selectionBackgroundColor(){return new U({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||ke.selectionBackgroundColor,isEffective:this.layout!==S.fixed&&this.preferences.selectionBackgroundColor!==null,onChange:e=>{this.updatePreference("selectionBackgroundColor",e??null)}})}get selectionTextColor(){return new U({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||ke.selectionTextColor,isEffective:this.layout!==S.fixed&&this.preferences.selectionTextColor!==null,onChange:e=>{this.updatePreference("selectionTextColor",e??null)}})}get textAlign(){return new Zt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||J.start,isEffective:this.layout!==S.fixed&&this.preferences.textAlign!==null,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(J)})}get textColor(){return new U({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||ke.textColor,isEffective:this.layout!==S.fixed&&this.preferences.textColor!==null,onChange:e=>{this.updatePreference("textColor",e??null)}})}get textNormalization(){return new O({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout!==S.fixed,onChange:e=>{this.updatePreference("textNormalization",e??null)}})}get visitedColor(){return new U({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||ke.visitedColor,isEffective:this.layout!==S.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e??null)}})}get wordSpacing(){return new k({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==S.fixed&&this.preferences.wordSpacing!==null,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:De.range,step:De.step})}}class ln{constructor(e,t){this.backgroundColor=e.backgroundColor||t.backgroundColor||null,this.blendFilter=typeof e.blendFilter=="boolean"?e.blendFilter:t.blendFilter??null,this.columnCount=e.columnCount!==void 0?e.columnCount:t.columnCount!==void 0?t.columnCount:null,this.constraint=e.constraint||t.constraint,this.darkenFilter=typeof e.darkenFilter=="boolean"?e.darkenFilter:t.darkenFilter??null,this.deprecatedFontSize=typeof e.deprecatedFontSize=="boolean"?e.deprecatedFontSize:t.deprecatedFontSize??null,this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontSize=e.fontSize!==void 0?e.fontSize:t.fontSize!==void 0?t.fontSize:null,this.fontSizeNormalize=typeof e.fontSizeNormalize=="boolean"?e.fontSizeNormalize:t.fontSizeNormalize??null,this.fontOpticalSizing=typeof e.fontOpticalSizing=="boolean"?e.fontOpticalSizing:t.fontOpticalSizing??null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.fontWidth=e.fontWidth!==void 0?e.fontWidth:t.fontWidth!==void 0?t.fontWidth:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.invertFilter=typeof e.invertFilter=="boolean"?e.invertFilter:t.invertFilter??null,this.invertGaijiFilter=typeof e.invertGaijiFilter=="boolean"?e.invertGaijiFilter:t.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||e.iOSPatch===!1?!1:e.iOSPatch===!0?(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?L.OS.iPadOS&&L.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.linkColor=e.linkColor||t.linkColor||null,this.maximalLineLength=e.maximalLineLength===null?null:e.maximalLineLength||t.maximalLineLength||null,this.minimalLineLength=e.minimalLineLength===null?null:e.minimalLineLength||t.minimalLineLength||null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.optimalLineLength=e.optimalLineLength||t.optimalLineLength,this.pageGutter=e.pageGutter!==void 0?e.pageGutter:t.pageGutter!==void 0?t.pageGutter:null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.scroll=typeof e.scroll=="boolean"?e.scroll:t.scroll??null,this.scrollPaddingTop=e.scrollPaddingTop!==void 0?e.scrollPaddingTop:t.scrollPaddingTop!==void 0?t.scrollPaddingTop:null,this.scrollPaddingBottom=e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:null,this.scrollPaddingLeft=e.scrollPaddingLeft!==void 0?e.scrollPaddingLeft:t.scrollPaddingLeft!==void 0?t.scrollPaddingLeft:null,this.scrollPaddingRight=e.scrollPaddingRight!==void 0?e.scrollPaddingRight:t.scrollPaddingRight!==void 0?t.scrollPaddingRight:null,this.selectionBackgroundColor=e.selectionBackgroundColor||t.selectionBackgroundColor||null,this.selectionTextColor=e.selectionTextColor||t.selectionTextColor||null,this.textAlign=e.textAlign||t.textAlign||null,this.textColor=e.textColor||t.textColor||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.visitedColor=e.visitedColor||t.visitedColor||null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null,this.experiments=t.experiments||null}}function Ke(r){const e=getComputedStyle(r),t=parseFloat(e.paddingLeft||"0"),n=parseFloat(e.paddingRight||"0");return r.clientWidth-t-n}function zr(r){const e=getComputedStyle(r),t=parseFloat(e.paddingTop||"0"),n=parseFloat(e.paddingBottom||"0");return r.clientHeight-t-n}class cn extends Ge{constructor(e){super(),this.a11yNormalize=e.a11yNormalize??null,this.backgroundColor=e.backgroundColor??null,this.blendFilter=e.blendFilter??null,this.bodyHyphens=e.bodyHyphens??null,this.colCount=e.colCount??null,this.darkenFilter=e.darkenFilter??null,this.deprecatedFontSize=e.deprecatedFontSize??null,this.fontFamily=e.fontFamily??null,this.fontOpticalSizing=e.fontOpticalSizing??null,this.fontSize=e.fontSize??null,this.fontSizeNormalize=e.fontSizeNormalize??null,this.fontWeight=e.fontWeight??null,this.fontWidth=e.fontWidth??null,this.invertFilter=e.invertFilter??null,this.invertGaijiFilter=e.invertGaijiFilter??null,this.iOSPatch=e.iOSPatch??null,this.iPadOSPatch=e.iPadOSPatch??null,this.letterSpacing=e.letterSpacing??null,this.ligatures=e.ligatures??null,this.lineHeight=e.lineHeight??null,this.lineLength=e.lineLength??null,this.linkColor=e.linkColor??null,this.noRuby=e.noRuby??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.textAlign=e.textAlign??null,this.textColor=e.textColor??null,this.view=e.view??null,this.visitedColor=e.visitedColor??null,this.wordSpacing=e.wordSpacing??null}toCSSProperties(){const e={};return this.a11yNormalize&&(e["--USER__a11yNormalize"]=this.toFlag("a11y")),this.backgroundColor&&(e["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(e["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(e["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(e["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?e["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(e["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(e["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(e["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(e["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(e["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(e["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(e["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(e["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?e["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(e["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?e["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(e["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(e["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(e["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(e["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(e["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(e["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(e["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(e["--USER__linkColor"]=this.linkColor),this.noRuby&&(e["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(e["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(e["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(e["--USER__textAlign"]=this.textAlign),this.textColor&&(e["--USER__textColor"]=this.textColor),this.view&&(e["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(e["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(e["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),e}}class Gi extends Ge{constructor(e){super(),this.backgroundColor=e.backgroundColor??null,this.baseFontFamily=e.baseFontFamily??null,this.baseFontSize=e.baseFontSize??null,this.baseLineHeight=e.baseLineHeight??null,this.boxSizingMedia=e.boxSizingMedia??null,this.boxSizingTable=e.boxSizingTable??null,this.colWidth=e.colWidth??null,this.colCount=e.colCount??null,this.colGap=e.colGap??null,this.codeFontFamily=e.codeFontFamily??null,this.compFontFamily=e.compFontFamily??null,this.defaultLineLength=e.defaultLineLength??null,this.flowSpacing=e.flowSpacing??null,this.humanistTf=e.humanistTf??null,this.linkColor=e.linkColor??null,this.maxMediaWidth=e.maxMediaWidth??null,this.maxMediaHeight=e.maxMediaHeight??null,this.modernTf=e.modernTf??null,this.monospaceTf=e.monospaceTf??null,this.noOverflow=e.noOverflow??null,this.noVerticalPagination=e.noVerticalPagination??null,this.oldStyleTf=e.oldStyleTf??null,this.pageGutter=e.pageGutter??null,this.paraIndent=e.paraIndent??null,this.paraSpacing=e.paraSpacing??null,this.primaryColor=e.primaryColor??null,this.scrollPaddingBottom=e.scrollPaddingBottom??null,this.scrollPaddingLeft=e.scrollPaddingLeft??null,this.scrollPaddingRight=e.scrollPaddingRight??null,this.scrollPaddingTop=e.scrollPaddingTop??null,this.sansSerifJa=e.sansSerifJa??null,this.sansSerifJaV=e.sansSerifJaV??null,this.sansTf=e.sansTf??null,this.secondaryColor=e.secondaryColor??null,this.selectionBackgroundColor=e.selectionBackgroundColor??null,this.selectionTextColor=e.selectionTextColor??null,this.serifJa=e.serifJa??null,this.serifJaV=e.serifJaV??null,this.textColor=e.textColor??null,this.typeScale=e.typeScale??null,this.visitedColor=e.visitedColor??null,this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.backgroundColor&&(e["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(e["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(e["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(e["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(e["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(e["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(e["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(e["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(e["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(e["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(e["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(e["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(e["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(e["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(e["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(e["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(e["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(e["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(e["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(e["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(e["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(e["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(e["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(e["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(e["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(e["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(e["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(e["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(e["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(e["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingLeft!=null&&(e["--RS__scrollPaddingLeft"]=this.toPx(this.scrollPaddingLeft)),this.scrollPaddingRight!=null&&(e["--RS__scrollPaddingRight"]=this.toPx(this.scrollPaddingRight)),this.scrollPaddingTop!=null&&(e["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(e["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(e["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(e["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(e["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(e["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(e["--RS__textColor"]=this.textColor),this.typeScale&&(e["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(e["--RS__visitedColor"]=this.visitedColor),this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=ut[t].value}),e}}class Vi{constructor(e){this.rsProperties=e.rsProperties,this.userProperties=e.userProperties,this.lineLengths=e.lineLengths,this.container=e.container,this.containerParent=e.container.parentElement||document.documentElement,this.constraint=e.constraint,this.isCJKVertical=e.isCJKVertical??!1,this.cachedColCount=e.userProperties.colCount,this.effectiveContainerWidth=Ke(this.containerParent)}update(e){this.cachedColCount=e.columnCount,e.constraint!==this.constraint&&(this.constraint=e.constraint),e.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=e.pageGutter),e.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=e.scrollPaddingBottom),e.scrollPaddingLeft!==this.rsProperties.scrollPaddingLeft&&(this.rsProperties.scrollPaddingLeft=e.scrollPaddingLeft),e.scrollPaddingRight!==this.rsProperties.scrollPaddingRight&&(this.rsProperties.scrollPaddingRight=e.scrollPaddingRight),e.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=e.scrollPaddingTop),e.experiments!==this.rsProperties.experiments&&(this.rsProperties.experiments=e.experiments),this.lineLengths.update({fontFace:e.fontFamily,letterSpacing:e.letterSpacing,padding:e.scroll?(e.scrollPaddingLeft||0)+(e.scrollPaddingRight||0):(e.pageGutter||0)*2,wordSpacing:e.wordSpacing,optimalChars:e.optimalLineLength,minChars:e.minimalLineLength,maxChars:e.maximalLineLength});const t=this.updateLayout(e.fontSize,e.deprecatedFontSize||e.iOSPatch,e.scroll,e.columnCount);t?.effectiveContainerWidth&&(this.effectiveContainerWidth=t?.effectiveContainerWidth);const n={a11yNormalize:e.textNormalization,backgroundColor:e.backgroundColor,blendFilter:e.blendFilter,bodyHyphens:typeof e.hyphens!="boolean"?null:e.hyphens?"auto":"none",colCount:t?.colCount,darkenFilter:e.darkenFilter,deprecatedFontSize:e.deprecatedFontSize,fontFamily:e.fontFamily,fontOpticalSizing:typeof e.fontOpticalSizing!="boolean"?null:e.fontOpticalSizing?"auto":"none",fontSize:e.fontSize,fontSizeNormalize:e.fontSizeNormalize,fontWeight:e.fontWeight,fontWidth:e.fontWidth,invertFilter:e.invertFilter,invertGaijiFilter:e.invertGaijiFilter,iOSPatch:e.iOSPatch,iPadOSPatch:e.iPadOSPatch,letterSpacing:e.letterSpacing,ligatures:typeof e.ligatures!="boolean"?null:e.ligatures?"common-ligatures":"none",lineHeight:e.lineHeight,lineLength:t?.effectiveLineLength,linkColor:e.linkColor,noRuby:e.noRuby,paraIndent:e.paragraphIndent,paraSpacing:e.paragraphSpacing,selectionBackgroundColor:e.selectionBackgroundColor,selectionTextColor:e.selectionTextColor,textAlign:e.textAlign,textColor:e.textColor,view:typeof e.scroll!="boolean"?null:e.scroll?"scroll":"paged",visitedColor:e.visitedColor,wordSpacing:e.wordSpacing};this.userProperties=new cn(n)}updateLayout(e,t,n,i){return this.isCJKVertical?this.computeCJKVerticalLength(e,t):n??this.userProperties.view==="scroll"?this.computeScrollLength(e,t):this.paginate(e,t,i)}getCompensatedMetrics(e,t){const n=e||this.userProperties.fontSize||1,i=n<1?1/n:t?n:1;return{zoomFactor:n,zoomCompensation:i,optimal:Math.round(this.lineLengths.optimalLineLength)*n,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*n):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*n):null}}paginate(e,t,n){const i=Math.round(Ke(this.containerParent)-this.constraint),o=this.getCompensatedMetrics(e,t),{zoomCompensation:a,optimal:s,minimal:l,maximal:c}=o,h=()=>i>=s&&c!==null?Math.min(Math.round(c*a),i):i;let u=1,m=i;if(n===void 0)return{colCount:void 0,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u*a)};if(n===null)if(i>=s&&c!==null){u=Math.floor(i/s);const f=Math.round(u*(c*a));m=Math.min(f,i)}else m=h();else if(n>1){const f=Math.round(n*(l!==null?l:s));if(i>=f)if(u=n,c===null)m=i;else{const d=Math.round(u*(c*a));m=Math.min(d,i)}else if(l!==null&&i<Math.round(n*l))if(u=Math.floor(i/l),u<=1)u=1,m=h();else{const d=Math.round(u*(s*a));m=Math.min(d,i)}else{u=n;const d=Math.round(u*(s*a));m=Math.min(d,i)}}else u=1,m=h();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*a)}}computeCJKVerticalLength(e,t){const n=Math.round(Ke(this.containerParent)-this.constraint),i=Math.round(zr(this.containerParent)),o=this.getCompensatedMetrics(e,t),a=o.maximal!==null?Math.min(Math.round(o.maximal*o.zoomCompensation),i):i;return{colCount:void 0,effectiveContainerWidth:n,effectiveLineLength:a}}computeScrollLength(e,t){const n=Math.round(Ke(this.containerParent)-this.constraint),i=this.getCompensatedMetrics(e&&(e<1||t)?e:1,t),o=i.zoomCompensation,a=i.optimal,s=i.maximal;let l,c=n,h=Math.round(a*o);if(s===null)h=n;else{const u=Math.min(Math.round(s*o),n);h=t?u:Math.round(u*o)}return{colCount:l,effectiveContainerWidth:c,effectiveLineLength:h}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const e=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=e.colCount,this.userProperties.lineLength=e.effectiveLineLength,this.effectiveContainerWidth=e.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const Lr=`// Note: we aren't blocking some of the events right now to try and be as nonintrusive as possible.
416
415
  // For a more comprehensive implementation, see https://github.com/hackademix/noscript/blob/3a83c0e4a506f175e38b0342dad50cdca3eae836/src/content/syncFetchPolicy.js#L142
417
416
  // The snippet of code at the beginning of this source is an attempt at defence against JS using persistent storage
418
417
  (function() {
@@ -477,7 +476,7 @@ Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)
477
476
  window.addEventListener("DOMContentLoaded", window._readium_eventBlocker, true);
478
477
  window.addEventListener("load", window._readium_eventBlocker, true);
479
478
  })();
480
- `;async function Cr(r,e){const t=r.effectiveLayout===b.fixed,n=e.filter(s=>s.mediaType.isHTML).map(s=>s.href),i=n.length>0?n:[/\.xhtml$/,/\.html$/],o=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([Re(Pi)],{type:"text/javascript"})},{id:"execution-prevention",as:"script",target:"head",blob:new Blob([Re(Er)],{type:"text/javascript"}),condition:s=>!!(s.querySelector("script")||s.querySelector("body[onload]:not(body[onload=''])"))}],a=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([Re(Ri)],{type:"text/javascript"}),condition:s=>!!(s.querySelector("script")||s.querySelector("body[onload]:not(body[onload=''])"))}];if(!t){const s=se(r);let l,c,h;switch(s){case"rtl":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Br),Promise.resolve().then(()=>jr),Promise.resolve().then(()=>Gr)]);l=u.default,c=m.default,h=f.default;break}case"cjk-horizontal":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Vr),Promise.resolve().then(()=>$r),Promise.resolve().then(()=>Xr)]);l=u.default,c=m.default,h=f.default;break}case"cjk-vertical":case"mongolian-vertical":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Yr),Promise.resolve().then(()=>qr),Promise.resolve().then(()=>Kr)]);l=u.default,c=m.default,h=f.default;break}default:{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Zr),Promise.resolve().then(()=>Jr),Promise.resolve().then(()=>Qr)]);l=u.default,c=m.default,h=f.default;break}}if(o.unshift({id:"readium-css-before",as:"link",target:"head",blob:new Blob([$e(l)],{type:"text/css"}),rel:"stylesheet"}),a.unshift({id:"readium-css-default",as:"link",target:"head",blob:new Blob([$e(c)],{type:"text/css"}),rel:"stylesheet",condition:u=>!(u.querySelector("link[rel='stylesheet']")||u.querySelector("style")||u.querySelector("[style]:not([style=''])"))},{id:"readium-css-after",as:"link",target:"head",blob:new Blob([$e(h)],{type:"text/css"}),rel:"stylesheet"}),(s==="cjk-horizontal"||s==="cjk-vertical")&&(r.description==="ebpaj-guide-1.0"||r.otherMetadata?.["ebpaj:guide-version"]!==void 0)){const{default:m}=await Promise.resolve().then(()=>ea);a.push({id:"readium-css-ebpaj",as:"link",target:"head",blob:new Blob([$e(m)],{type:"text/css"}),rel:"stylesheet"})}}return[{resources:i,prepend:o,append:a}]}const xr=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),miscPointer:r.miscPointer||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{}),contentProtection:r.contentProtection||(()=>{}),contextMenu:r.contextMenu||(()=>{}),peripheral:r.peripheral||(()=>{})});class hn extends $t{constructor(e,t,n,i=[],o=void 0,a={preferences:{},defaults:{}}){super(),this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.reflowViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=xr(n),this.currentLocation=o,i.length&&(this.positions=i),this._preferences=new ke(a.preferences),this._defaults=new ji(a.defaults),this._settings=new ln(this._preferences,this._defaults);const s=se(t.metadata),l=s==="cjk-horizontal",c=s==="cjk-vertical",u=c||s==="mongolian-vertical",m=l||c;this._css=new Vi({rsProperties:new Gi({noVerticalPagination:u||void 0}),userProperties:new cn({}),lineLengths:new we({optimalChars:this._settings.optimalLineLength,minChars:this._settings.minimalLineLength,maxChars:this._settings.maximalLineLength,padding:this._settings.scroll?(this._settings.scrollPaddingLeft||0)+(this._settings.scrollPaddingRight||0):(this._settings.pageGutter||0)*2,fontFace:this._settings.fontFamily,letterSpacing:this._settings.letterSpacing,wordSpacing:this._settings.wordSpacing,isCJK:m}),container:e,constraint:this._settings.constraint,isCJKVertical:u}),this._layout=hn.determineLayout(t,!!this._settings.scroll),this.currentProgression=t.metadata.effectiveReadingProgression,this._injectablesConfig=a.injectables||{rules:[],allowedDomains:[]},this._readiumRulesPromise=Cr(t.metadata,t.readingOrder.items),this._contentProtection=a.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,a.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new nn(this._contentProtection),this._suspiciousActivityListener=f=>{const{type:d,...p}=f.detail;d==="context_menu"?this.listeners.contextMenu(p):this.listeners.contentProtection(d,p)},window.addEventListener(de,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=f=>{const d=f.detail;this.listeners.peripheral(d)},window.addEventListener(ue,this._keyboardPeripheralListener)),this.resizeObserver=new ResizeObserver(()=>this.ownerWindow.requestAnimationFrame(async()=>await this.resizeHandler())),this.resizeObserver.observe(this.container.parentElement||document.documentElement)}static determineLayout(e,t){const n=e.metadata.effectiveLayout;if(n===b.fixed||e.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in e.metadata.otherMetadata||e.metadata?.conformsTo?.includes(En.DIVINA))return b.fixed;if(n===b.scrolled)return b.scrolled;const i=se(e.metadata);return i==="cjk-vertical"||i==="mongolian-vertical"||n===b.reflowable&&t?b.scrolled:b.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),!this._injector){const e=await this._readiumRulesPromise;this._injector=new en({rules:[...e,...this._injectablesConfig.rules],allowedDomains:this._injectablesConfig.allowedDomains})}if(this._layout===b.fixed)this.framePool=new Bi(this.container,this.positions,this.pub,this._injector,this._contentProtection,this._keyboardPeripherals),this.framePool.listener=(e,t)=>{this.eventListener(e,t)};else{await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new Oi(this.container,this.positions,e,this._injector,this._contentProtection,this._keyboardPeripherals)}this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.resizeHandler(),await this.apply()}get settings(){if(this._layout===b.fixed)return Object.freeze({...this._settings});{const e=this._css.userProperties.colCount||this._css.rsProperties.colCount||this._settings.columnCount;return Object.freeze({...this._settings,columnCount:e})}}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new sn(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new ln(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new sn(this._preferences,this.settings,this.pub.metadata)),this._layout===b.fixed?this.handleFXLPrefs(e,this._settings):await this.updateCSS(!0)}handleFXLPrefs(e,t){e.columnCount!==t.columnCount&&this.framePool.setPerPage(t.columnCount)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[n,i]of Object.entries(e.rsProperties.toCSSProperties()))t[n]=i;for(const[n,i]of Object.entries(e.userProperties.toCSSProperties()))t[n]=i;return t}async commitCSS(e){if(!this.framePool)return;const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t),this._css.userProperties.view==="paged"&&this._layout===b.scrolled?await this.setLayout(b.reflowable):this._css.userProperties.view==="scroll"&&this._layout===b.reflowable&&await this.setLayout(b.scrolled),this._css.setContainerWidth()}async resizeHandler(){const e=this.container.parentElement||document.documentElement;if(this._layout===b.fixed){if(this.container.style.width=`${Xe(e)-this._settings.constraint}px`,!this.framePool)return;this.framePool.resizeHandler()}else{const t=this._css.userProperties.colCount,n=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&t!==this._css.userProperties.colCount||n!==this._css.userProperties.lineLength)&&await this.commitCSS(this._css)}}get layout(){return this._layout}get ownerWindow(){return this.container.ownerDocument.defaultView||window}get _cframes(){return(this.framePool?.currentFrames??[]).filter(e=>!(e instanceof rn&&e.isDestroyed))}get pool(){return this.framePool}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const n=F.deserialize(t);if(!n)break;this.currentLocation=new F({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:n?.locations,text:n?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const i=t;if(i.interactiveElement){const l=new DOMParser().parseFromString(i.interactiveElement,"text/html").body.children[0];if(l.nodeType===l.ELEMENT_NODE&&l.nodeName==="A"&&l.hasAttribute("href")){const c=l.attributes.getNamedItem("href")?.value;if(c.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[c.substring(1)]}),!1,()=>{});else if(c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")||c.startsWith("tel:"))this.listeners.handleLocator(new V({href:c}).locator);else try{this.goLink(new V({href:dt.join(dt.dirname(this.currentLocation.href),c)}),!1,()=>{})}catch(h){console.warn(`Couldn't go to link for ${c}: ${h}`),this.listeners.handleLocator(new V({href:c}).locator)}}else console.log("Clicked on",l)}else{if(this._layout===b.fixed&&this.framePool.doNotDisturb&&(i.doNotDisturb=!0),this._layout===b.fixed&&(this.currentProgression===N.rtl||this.currentProgression===N.ltr)&&this.framePool.currentFrames.length>1){const h=this.framePool.currentFrames;i.targetFrameSrc===h[this.currentProgression===N.rtl?0:1]?.source&&(i.x+=(h[this.currentProgression===N.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(e==="click"?this.listeners.click(i):this.listeners.tap(i))break;const c=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;i.x>=c&&i.x<=c*3&&this.listeners.miscPointer(1),i.x<c?this.goLeft(!1,()=>{}):i.x>c*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(t);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const o=t;this.listeners.contentProtection(o.type,o);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":const a=t,s={...a,interactiveElement:void 0};a.interactiveElement&&(s.interactiveElement=new DOMParser().parseFromString(a.interactiveElement,"text/html").body.children[0]),this.listeners.peripheral(s);break;case"log":console.log(this._cframes[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){let e=Array.from(Gt.keys());if(this._layout===b.fixed)return e.filter(i=>jo.includes(i));e=e.filter(i=>Go.includes(i));const t=se(this.pub.metadata);if(t==="cjk-vertical"||t==="mongolian-vertical")return e.filter(i=>i!=="column_snapper"&&i!=="scroll_snapper");const n=e;return this._layout===b.scrolled?e=n.filter(i=>i!=="column_snapper"&&i!=="cjk_vertical_snapper"):e=n.filter(i=>i!=="scroll_snapper"&&i!=="cjk_vertical_snapper"),e}attachListener(){const e=this._cframes.filter(t=>!!t);if(e.length===0)throw Error("no cframe to attach listener to");e.forEach(t=>{t.msg&&(t.msg.listener=(n,i)=>{this.eventListener(n,i)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;if(this._layout===b.fixed){const i=this.framePool,o=i.viewport.positions[0];if(e===1){if(!i.next(i.perPage))return!1}else if(e===-1){if(!i.prev(i.perPage))return!1}else throw Error("Invalid relative value for FXL");const a=i.viewport.positions[0];if(o>a){for(let s=this.positions.length-1;s>=0;s--)if(this.positions[s].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[s].copyWithLocations({progression:.999999999999});break}}else if(o<a){for(let s=0;s<this.positions.length;s++)if(this.positions[s].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[s];break}}return await this.apply(),!0}const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),n=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));if(n===t)return this._cframes[0]?.msg?.send("shake",void 0,async i=>{}),!1;if(t>n){for(let i=this.positions.length-1;i>=0;i--)if(this.positions[i].href===this.pub.readingOrder.items[n].href){this.currentLocation=this.positions[i].copyWithLocations({progression:.999999999999});break}}else for(let i=0;i<this.positions.length;i++)if(this.positions[i].href===this.pub.readingOrder.items[n].href){this.currentLocation=this.positions[i];break}return await this.apply(),!0}findLastPositionInProgressionRange(e,t){const n=e.findLastIndex(i=>{const o=i.locations.progression;return!!(o&&o>t.start&&o<=t.end)});return n!==-1?e[n]:void 0}findNearestPositions(e){const t=this.positions.filter(a=>a.href===this.currentLocation.href);let n=this.currentLocation,i;const o=t.findLastIndex(a=>(a.locations.progression??0)<=e.start);if(o!==-1){n=t[o];const a=t.slice(o+1);i=this.findLastPositionInProgressionRange(a,e)}return{first:n,last:i}}updateViewport(e){this.reflowViewport.readingOrder=[],this.reflowViewport.progressions.clear(),this.reflowViewport.positions=null,this.currentLocation&&(this.reflowViewport.readingOrder.push(this.currentLocation.href),this.reflowViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.reflowViewport.positions=[this.currentLocation.locations.position],this.lastLocationInView?.locations?.position!==void 0&&this.reflowViewport.positions.push(this.lastLocationInView.locations.position)))}async syncLocation(e){const t=e,n=this.findNearestPositions(t);this.currentLocation=n.first.copyWithLocations({progression:t.start}),this.lastLocationInView=n.last,this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this._layout===b.fixed?(this.changeResource(-1),t(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async n=>{t(n?!0:await this.changeResource(-1))})}goForward(e,t){this._layout===b.fixed?(this.changeResource(1),t(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async n=>{t(n?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===b.fixed?this.framePool?this.framePool.viewport:{readingOrder:[],progressions:new Map,positions:null}:this.reflowViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.currentProgression}async setLayout(e){this._layout!==e&&(this._layout=e,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(e,t){let n=!1,i=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",i?[e.text?.serialize(),i]:e.text?.serialize(),h=>l(h))}):i&&(n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",["",i],h=>l(h))})),n){t(n);return}const o=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(o&&(n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_id",o,h=>l(h))})),n){t(n);return}const a=e?.locations?.progression;a&&a>0?n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_progression",a,h=>l(h))}):n=!0,t(n)}go(e,t,n){const i=e.href.split("#")[0];let o=this.pub.readingOrder.findWithHref(i);if(!o)return n(this.listeners.handleLocator(e));this.currentLocation=this.positions.find(a=>a.href===o.href),this.apply().then(()=>this.loadLocator(e,a=>n(a))).then(()=>{this.attachListener()})}goLink(e,t,n){return this.go(e.locator,t,n)}}const Lr=`// PreservePitchProcessor.js
479
+ `;async function Or(r,e){const t=r.effectiveLayout===S.fixed,n=e.filter(s=>s.mediaType.isHTML).map(s=>s.href),i=n.length>0?n:[/\.xhtml$/,/\.html$/],o=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([Pe(Ri)],{type:"text/javascript"})},{id:"execution-prevention",as:"script",target:"head",blob:new Blob([Pe(Lr)],{type:"text/javascript"}),condition:s=>!!(s.querySelector("script")||s.querySelector("body[onload]:not(body[onload=''])"))}],a=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([Pe(Pi)],{type:"text/javascript"}),condition:s=>!!(s.querySelector("script")||s.querySelector("body[onload]:not(body[onload=''])"))}];if(!t){const s=se(r);let l,c,h;switch(s){case"rtl":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Kr),Promise.resolve().then(()=>Xr),Promise.resolve().then(()=>Yr)]);l=u.default,c=m.default,h=f.default;break}case"cjk-horizontal":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>qr),Promise.resolve().then(()=>Jr),Promise.resolve().then(()=>Zr)]);l=u.default,c=m.default,h=f.default;break}case"cjk-vertical":case"mongolian-vertical":{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>Qr),Promise.resolve().then(()=>ea),Promise.resolve().then(()=>ta)]);l=u.default,c=m.default,h=f.default;break}default:{const[u,m,f]=await Promise.all([Promise.resolve().then(()=>na),Promise.resolve().then(()=>ia),Promise.resolve().then(()=>oa)]);l=u.default,c=m.default,h=f.default;break}}if(o.unshift({id:"readium-css-before",as:"link",target:"head",blob:new Blob([$e(l)],{type:"text/css"}),rel:"stylesheet"}),a.unshift({id:"readium-css-default",as:"link",target:"head",blob:new Blob([$e(c)],{type:"text/css"}),rel:"stylesheet",condition:u=>!(u.querySelector("link[rel='stylesheet']")||u.querySelector("style")||u.querySelector("[style]:not([style=''])"))},{id:"readium-css-after",as:"link",target:"head",blob:new Blob([$e(h)],{type:"text/css"}),rel:"stylesheet"}),(s==="cjk-horizontal"||s==="cjk-vertical")&&(r.description==="ebpaj-guide-1.0"||r.otherMetadata?.["ebpaj:guide-version"]!==void 0)){const{default:m}=await Promise.resolve().then(()=>ra);a.push({id:"readium-css-ebpaj",as:"link",target:"head",blob:new Blob([$e(m)],{type:"text/css"}),rel:"stylesheet"})}}return[{resources:i,prepend:o,append:a}]}const Ar=r=>({frameLoaded:r.frameLoaded||(()=>{}),positionChanged:r.positionChanged||(()=>{}),tap:r.tap||(()=>!1),click:r.click||(()=>!1),zoom:r.zoom||(()=>{}),miscPointer:r.miscPointer||(()=>{}),scroll:r.scroll||(()=>{}),customEvent:r.customEvent||(()=>{}),handleLocator:r.handleLocator||(()=>!1),textSelected:r.textSelected||(()=>{}),contentProtection:r.contentProtection||(()=>{}),contextMenu:r.contextMenu||(()=>{}),peripheral:r.peripheral||(()=>{})});class hn extends $t{constructor(e,t,n,i=[],o=void 0,a={preferences:{},defaults:{}}){super(),this._preferencesEditor=null,this._injector=null,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this.reflowViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=t,this.container=e,this.listeners=Ar(n),this.currentLocation=o,i.length&&(this.positions=i),this._preferences=new Ce(a.preferences),this._defaults=new ji(a.defaults),this._settings=new ln(this._preferences,this._defaults);const s=se(t.metadata),l=s==="cjk-horizontal",c=s==="cjk-vertical",u=c||s==="mongolian-vertical",m=l||c;this._css=new Vi({rsProperties:new Gi({noVerticalPagination:u||void 0}),userProperties:new cn({}),lineLengths:new we({optimalChars:this._settings.optimalLineLength,minChars:this._settings.minimalLineLength,maxChars:this._settings.maximalLineLength,padding:this._settings.scroll?(this._settings.scrollPaddingLeft||0)+(this._settings.scrollPaddingRight||0):(this._settings.pageGutter||0)*2,fontFace:this._settings.fontFamily,letterSpacing:this._settings.letterSpacing,wordSpacing:this._settings.wordSpacing,isCJK:m}),container:e,constraint:this._settings.constraint,isCJKVertical:u}),this._layout=hn.determineLayout(t,!!this._settings.scroll),this.currentProgression=t.metadata.effectiveReadingProgression,this._injectablesConfig=a.injectables||{rules:[],allowedDomains:[]},this._readiumRulesPromise=Or(t.metadata,t.readingOrder.items),this._contentProtection=a.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,a.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new nn(this._contentProtection),this._suspiciousActivityListener=f=>{const{type:d,...p}=f.detail;d==="context_menu"?this.listeners.contextMenu(p):this.listeners.contentProtection(d,p)},window.addEventListener(de,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=f=>{const d=f.detail;this.listeners.peripheral(d)},window.addEventListener(ue,this._keyboardPeripheralListener)),this.resizeObserver=new ResizeObserver(()=>this.ownerWindow.requestAnimationFrame(async()=>await this.resizeHandler())),this.resizeObserver.observe(this.container.parentElement||document.documentElement)}static determineLayout(e,t){const n=e.metadata.effectiveLayout;if(n===S.fixed||e.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in e.metadata.otherMetadata||e.metadata?.conformsTo?.includes(kn.DIVINA))return S.fixed;if(n===S.scrolled)return S.scrolled;const i=se(e.metadata);return i==="cjk-vertical"||i==="mongolian-vertical"||n===S.reflowable&&t?S.scrolled:S.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),!this._injector){const e=await this._readiumRulesPromise;this._injector=new en({rules:[...e,...this._injectablesConfig.rules],allowedDomains:this._injectablesConfig.allowedDomains})}if(this._layout===S.fixed)this.framePool=new Bi(this.container,this.positions,this.pub,this._injector,this._contentProtection,this._keyboardPeripherals),this.framePool.listener=(e,t)=>{this.eventListener(e,t)};else{await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new Li(this.container,this.positions,e,this._injector,this._contentProtection,this._keyboardPeripherals)}this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.resizeHandler(),await this.apply()}get settings(){if(this._layout===S.fixed)return Object.freeze({...this._settings});{const e=this._css.userProperties.colCount||this._css.rsProperties.colCount||this._settings.columnCount;return Object.freeze({...this._settings,columnCount:e})}}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new sn(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),await this.applyPreferences()}async applyPreferences(){const e=this._settings;this._settings=new ln(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new sn(this._preferences,this.settings,this.pub.metadata)),this._layout===S.fixed?this.handleFXLPrefs(e,this._settings):await this.updateCSS(!0)}handleFXLPrefs(e,t){e.columnCount!==t.columnCount&&this.framePool.setPerPage(t.columnCount)}async updateCSS(e){this._css.update(this._settings),e&&await this.commitCSS(this._css)}compileCSSProperties(e){const t={};for(const[n,i]of Object.entries(e.rsProperties.toCSSProperties()))t[n]=i;for(const[n,i]of Object.entries(e.userProperties.toCSSProperties()))t[n]=i;return t}async commitCSS(e){if(!this.framePool)return;const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t),this._css.userProperties.view==="paged"&&this._layout===S.scrolled?await this.setLayout(S.reflowable):this._css.userProperties.view==="scroll"&&this._layout===S.reflowable&&await this.setLayout(S.scrolled),this._css.setContainerWidth()}async resizeHandler(){const e=this.container.parentElement||document.documentElement;if(this._layout===S.fixed){if(this.container.style.width=`${Ke(e)-this._settings.constraint}px`,!this.framePool)return;this.framePool.resizeHandler()}else{const t=this._css.userProperties.colCount,n=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&t!==this._css.userProperties.colCount||n!==this._css.userProperties.lineLength)&&await this.commitCSS(this._css)}}get layout(){return this._layout}get ownerWindow(){return this.container.ownerDocument.defaultView||window}get _cframes(){return(this.framePool?.currentFrames??[]).filter(e=>!(e instanceof rn&&e.isDestroyed))}get pool(){return this.framePool}eventListener(e,t){switch(e){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const n=N.deserialize(t);if(!n)break;this.currentLocation=new N({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:n?.locations,text:n?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const i=t;if(i.interactiveElement){const l=new DOMParser().parseFromString(i.interactiveElement,"text/html").body.children[0];if(l.nodeType===l.ELEMENT_NODE&&l.nodeName==="A"&&l.hasAttribute("href")){const c=l.attributes.getNamedItem("href")?.value;if(c.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[c.substring(1)]}),!1,()=>{});else if(c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")||c.startsWith("tel:"))this.listeners.handleLocator(new V({href:c}).locator);else try{this.goLink(new V({href:dt.join(dt.dirname(this.currentLocation.href),c)}),!1,()=>{})}catch(h){console.warn(`Couldn't go to link for ${c}: ${h}`),this.listeners.handleLocator(new V({href:c}).locator)}}else console.log("Clicked on",l)}else{if(this._layout===S.fixed&&this.framePool.doNotDisturb&&(i.doNotDisturb=!0),this._layout===S.fixed&&(this.currentProgression===M.rtl||this.currentProgression===M.ltr)&&this.framePool.currentFrames.length>1){const h=this.framePool.currentFrames;i.targetFrameSrc===h[this.currentProgression===M.rtl?0:1]?.source&&(i.x+=(h[this.currentProgression===M.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(e==="click"?this.listeners.click(i):this.listeners.tap(i))break;const c=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;i.x>=c&&i.x<=c*3&&this.listeners.miscPointer(1),i.x<c?this.goLeft(!1,()=>{}):i.x>c*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(t);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"scroll":this.listeners.scroll(t);break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"content_protection":const o=t;this.listeners.contentProtection(o.type,o);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":const a=t,s={...a,interactiveElement:void 0};a.interactiveElement&&(s.interactiveElement=new DOMParser().parseFromString(a.interactiveElement,"text/html").body.children[0]),this.listeners.peripheral(s);break;case"log":console.log(this._cframes[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){let e=Array.from(Gt.keys());if(this._layout===S.fixed)return e.filter(i=>jo.includes(i));e=e.filter(i=>Go.includes(i));const t=se(this.pub.metadata);if(t==="cjk-vertical"||t==="mongolian-vertical")return e.filter(i=>i!=="column_snapper"&&i!=="scroll_snapper");const n=e;return this._layout===S.scrolled?e=n.filter(i=>i!=="column_snapper"&&i!=="cjk_vertical_snapper"):e=n.filter(i=>i!=="scroll_snapper"&&i!=="cjk_vertical_snapper"),e}attachListener(){const e=this._cframes.filter(t=>!!t);if(e.length===0)throw Error("no cframe to attach listener to");e.forEach(t=>{t.msg&&(t.msg.listener=(n,i)=>{this.eventListener(n,i)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;if(this._layout===S.fixed){const i=this.framePool,o=i.viewport.positions[0];if(e===1){if(!i.next(i.perPage))return!1}else if(e===-1){if(!i.prev(i.perPage))return!1}else throw Error("Invalid relative value for FXL");const a=i.viewport.positions[0];if(o>a){for(let s=this.positions.length-1;s>=0;s--)if(this.positions[s].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[s].copyWithLocations({progression:.999999999999});break}}else if(o<a){for(let s=0;s<this.positions.length;s++)if(this.positions[s].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[s];break}}return await this.apply(),!0}const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),n=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));if(n===t)return this._cframes[0]?.msg?.send("shake",void 0,async i=>{}),!1;if(t>n){for(let i=this.positions.length-1;i>=0;i--)if(this.positions[i].href===this.pub.readingOrder.items[n].href){this.currentLocation=this.positions[i].copyWithLocations({progression:.999999999999});break}}else for(let i=0;i<this.positions.length;i++)if(this.positions[i].href===this.pub.readingOrder.items[n].href){this.currentLocation=this.positions[i];break}return await this.apply(),!0}findLastPositionInProgressionRange(e,t){const n=e.findLastIndex(i=>{const o=i.locations.progression;return!!(o&&o>t.start&&o<=t.end)});return n!==-1?e[n]:void 0}findNearestPositions(e){const t=this.positions.filter(a=>a.href===this.currentLocation.href);let n=this.currentLocation,i;const o=t.findLastIndex(a=>(a.locations.progression??0)<=e.start);if(o!==-1){n=t[o];const a=t.slice(o+1);i=this.findLastPositionInProgressionRange(a,e)}return{first:n,last:i}}updateViewport(e){this.reflowViewport.readingOrder=[],this.reflowViewport.progressions.clear(),this.reflowViewport.positions=null,this.currentLocation&&(this.reflowViewport.readingOrder.push(this.currentLocation.href),this.reflowViewport.progressions.set(this.currentLocation.href,e),this.currentLocation.locations?.position!==void 0&&(this.reflowViewport.positions=[this.currentLocation.locations.position],this.lastLocationInView?.locations?.position!==void 0&&this.reflowViewport.positions.push(this.lastLocationInView.locations.position)))}async syncLocation(e){const t=e,n=this.findNearestPositions(t);this.currentLocation=n.first.copyWithLocations({progression:t.start}),this.lastLocationInView=n.last,this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this._layout===S.fixed?(this.changeResource(-1),t(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async n=>{t(n?!0:await this.changeResource(-1))})}goForward(e,t){this._layout===S.fixed?(this.changeResource(1),t(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async n=>{t(n?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===S.fixed?this.framePool?this.framePool.viewport:{readingOrder:[],progressions:new Map,positions:null}:this.reflowViewport}get isScrollStart(){const e=this.viewport.readingOrder[0];return this.viewport.progressions.get(e)?.start===0}get isScrollEnd(){const e=this.viewport.readingOrder[this.viewport.readingOrder.length-1];return this.viewport.progressions.get(e)?.end===1}get canGoBackward(){const e=this.pub.readingOrder.items[0]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.start===0)}get canGoForward(){const e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1]?.href;return!(this.viewport.progressions.has(e)&&this.viewport.progressions.get(e)?.end===1)}get readingProgression(){return this.currentProgression}async setLayout(e){this._layout!==e&&(this._layout=e,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(e,t){let n=!1,i=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",i?[e.text?.serialize(),i]:e.text?.serialize(),h=>l(h))}):i&&(n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",["",i],h=>l(h))})),n){t(n);return}const o=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(o&&(n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_id",o,h=>l(h))})),n){t(n);return}const a=e?.locations?.progression;a&&a>0?n=await new Promise((l,c)=>{this._cframes[0].msg.send("go_progression",a,h=>l(h))}):n=!0,t(n)}go(e,t,n){const i=e.href.split("#")[0];let o=this.pub.readingOrder.findWithHref(i);if(!o)return n(this.listeners.handleLocator(e));this.currentLocation=this.positions.find(a=>a.href===o.href),this.apply().then(()=>this.loadLocator(e,a=>n(a))).then(()=>{this.attachListener()})}goLink(e,t,n){return this.go(e.locator,t,n)}}const Ur=`// PreservePitchProcessor.js
481
480
  // AudioWorklet processor for pitch preservation via pitch shifting.
482
481
  //
483
482
  // Architecture:
@@ -691,8 +690,8 @@ class PreservePitchProcessor extends AudioWorkletProcessor {
691
690
  }
692
691
 
693
692
  registerProcessor('preserve-pitch-processor', PreservePitchProcessor);
694
- `;class dn{constructor(e){this.workletNode=null,this.url=null,this.ctx=e}static async createWorklet(e){const{ctx:t,pitchFactor:n,modulePath:i}=e,o=new dn(t);try{if(i)await t.audioWorklet.addModule(i);else{const a=new Blob([Lr],{type:"text/javascript"});o.url=URL.createObjectURL(a),await t.audioWorklet.addModule(o.url)}}catch(a){throw o.destroy(),new Error(`Error adding module: ${a}`)}try{o.workletNode=new AudioWorkletNode(t,"preserve-pitch-processor"),n&&o.updatePitchFactor(n)}catch(a){throw o.destroy(),new Error(`Error creating worklet node: ${a}`)}return o}updatePitchFactor(e){this.workletNode&&this.workletNode.port.postMessage({type:"setPitchFactor",factor:e})}destroy(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.url&&(URL.revokeObjectURL(this.url),this.url=null)}}class $i{constructor(e){this.audioContext=null,this.sourceNode=null,this.gainNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.isStoppedValue=!1,this.worklet=null,this.webAudioActive=!1,this.boundOnCanPlayThrough=this.onCanPlayThrough.bind(this),this.boundOnTimeUpdate=this.onTimeUpdate.bind(this),this.boundOnError=this.onError.bind(this),this.boundOnEnded=this.onEnded.bind(this),this.boundOnStalled=this.onStalled.bind(this),this.boundOnEmptied=this.onEmptied.bind(this),this.boundOnSuspend=this.onSuspend.bind(this),this.boundOnWaiting=this.onWaiting.bind(this),this.boundOnLoadedMetadata=this.onLoadedMetadata.bind(this),this.boundOnSeeking=this.onSeeking.bind(this),this.boundOnSeeked=this.onSeeked.bind(this),this.boundOnPlay=this.onPlay.bind(this),this.boundOnPlaying=this.onPlaying.bind(this),this.boundOnPause=this.onPause.bind(this),this.boundOnProgress=this.onProgress.bind(this),this.playback=e.playback,this.mediaElement=document.createElement("audio"),this.mediaElement.addEventListener("canplaythrough",this.boundOnCanPlayThrough),this.mediaElement.addEventListener("timeupdate",this.boundOnTimeUpdate),this.mediaElement.addEventListener("error",this.boundOnError),this.mediaElement.addEventListener("ended",this.boundOnEnded),this.mediaElement.addEventListener("stalled",this.boundOnStalled),this.mediaElement.addEventListener("emptied",this.boundOnEmptied),this.mediaElement.addEventListener("suspend",this.boundOnSuspend),this.mediaElement.addEventListener("waiting",this.boundOnWaiting),this.mediaElement.addEventListener("loadedmetadata",this.boundOnLoadedMetadata),this.mediaElement.addEventListener("seeking",this.boundOnSeeking),this.mediaElement.addEventListener("seeked",this.boundOnSeeked),this.mediaElement.addEventListener("play",this.boundOnPlay),this.mediaElement.addEventListener("playing",this.boundOnPlaying),this.mediaElement.addEventListener("pause",this.boundOnPause),this.mediaElement.addEventListener("progress",this.boundOnProgress),this.mediaElement.currentTime=this.playback.state.currentTime}on(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==t))}async ensureAudioContextRunning(){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume()}getOrCreateAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}onStalled(e){this.emit("stalled",e)}onEmptied(e){this.emit("emptied",e)}onSuspend(e){this.emit("suspend",e)}onWaiting(e){this.emit("waiting",e)}onLoadedMetadata(e){this.emit("loadedmetadata",e)}onSeeking(e){this.emit("seeking",e)}onSeeked(e){this.emit("seeked",e)}onPlay(){this.emit("play",null)}onPlaying(){this.emit("playing",null)}onPause(){this.emit("pause",null)}onProgress(){this.emit("progress",this.mediaElement.seekable)}emit(e,t){this.listeners[e]&&this.listeners[e].forEach(n=>n(t))}async play(){if(!this.isPlayingValue)try{this.audioContext&&await this.ensureAudioContextRunning(),await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1,this.isStoppedValue=!1}catch(e){if(e?.name==="AbortError")return;console.error("error trying to play media element",e),this.emit("error",e)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1,this.isStoppedValue=!0}setVolume(e){const t=Math.max(0,Math.min(1,e));this.gainNode?(this.mediaElement.volume=1,this.gainNode.gain.value=t):this.mediaElement.volume=t,this.isMutedValue=t===0}skip(e){const t=this.mediaElement.duration;if(!isFinite(t))return;const n=this.mediaElement.currentTime+e;n<0?this.mediaElement.currentTime=0:n>t?this.mediaElement.currentTime=t:this.mediaElement.currentTime=n}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return this.isStoppedValue}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}setPlaybackRate(e,t){this.mediaElement.playbackRate=e,t?"preservesPitch"in this.mediaElement?this.mediaElement.preservesPitch=!0:this.activateWebAudio().then(()=>{this.worklet?this.worklet.updatePitchFactor(1/e):dn.createWorklet({ctx:this.getOrCreateAudioContext(),pitchFactor:1}).then(n=>{this.sourceNode&&this.sourceNode.disconnect(),this.worklet=n,this.sourceNode?.connect(this.worklet.workletNode),this.worklet.workletNode.connect(this.gainNode),this.worklet.updatePitchFactor(1/e)}).catch(n=>{console.warn("Failed to create preserve pitch worklet",n)})}).catch(n=>{console.warn("Web Audio unavailable, playing without pitch correction:",n)}):("preservesPitch"in this.mediaElement&&(this.mediaElement.preservesPitch=!1),this.worklet&&(this.worklet.destroy(),this.worklet=null,this.webAudioActive&&this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode.connect(this.gainNode))))}async activateWebAudio(){if(this.webAudioActive)return;const e=this.mediaElement.src;if(!e)return;const t=this.mediaElement.currentTime,n=this.isPlayingValue;n&&(this.mediaElement.pause(),this.isPlayingValue=!1),this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load();try{await new Promise((o,a)=>{const s=()=>{this.mediaElement.removeEventListener("canplaythrough",s),this.mediaElement.removeEventListener("error",l),o()},l=()=>{this.mediaElement.removeEventListener("canplaythrough",s),this.mediaElement.removeEventListener("error",l),a(new Error("Audio reload with CORS failed — server may not send Access-Control-Allow-Origin"))};this.mediaElement.addEventListener("canplaythrough",s),this.mediaElement.addEventListener("error",l)})}catch(o){throw this.mediaElement.removeAttribute("crossorigin"),this.mediaElement.src=e,this.mediaElement.load(),n?(await new Promise(a=>{const s=()=>{this.mediaElement.removeEventListener("canplaythrough",s),a()};this.mediaElement.addEventListener("canplaythrough",s)}),this.mediaElement.currentTime=t,await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1):this.mediaElement.currentTime=t,o}this.mediaElement.currentTime=t,this.sourceNode=new MediaElementAudioSourceNode(this.getOrCreateAudioContext(),{mediaElement:this.mediaElement});const i=this.getOrCreateAudioContext();this.gainNode=i.createGain(),this.gainNode.gain.value=this.mediaElement.volume,this.mediaElement.volume=1,this.sourceNode.connect(this.gainNode),this.gainNode.connect(i.destination),this.webAudioActive=!0,n&&(await this.ensureAudioContextRunning(),await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1)}get isWebAudioActive(){return this.webAudioActive}tearDownWebAudio(){this.worklet&&(this.worklet.destroy(),this.worklet=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.gainNode&&(this.mediaElement.volume=this.gainNode.gain.value,this.gainNode.disconnect(),this.gainNode=null),this.webAudioActive=!1}changeSrc(e){if(this.mediaElement.src!==e)if(this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadedValue=!1,this.isLoadingValue=!0,this.isEndedValue=!1,this.webAudioActive){this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load();const t=()=>{i()},n=()=>{i(),console.warn("CORS reload failed for new track — disabling Web Audio graph:",e),this.tearDownWebAudio(),this.mediaElement.removeAttribute("crossorigin"),this.mediaElement.src=e,this.mediaElement.load()},i=()=>{this.mediaElement.removeEventListener("canplaythrough",t),this.mediaElement.removeEventListener("error",n)};this.mediaElement.addEventListener("canplaythrough",t),this.mediaElement.addEventListener("error",n)}else this.mediaElement.src=e,this.mediaElement.load()}getMediaElement(){return this.mediaElement}}class Ye{constructor(e={}){this.volume=M(e.volume,Be.range),this.playbackRate=M(e.playbackRate,je.range),this.preservePitch=P(e.preservePitch),this.skipBackwardInterval=M(e.skipBackwardInterval,te.range),this.skipForwardInterval=M(e.skipForwardInterval,te.range),this.pollInterval=v(e.pollInterval),this.autoPlay=P(e.autoPlay),this.enableMediaSession=P(e.enableMediaSession)}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(t[n]=e[n]);return new Ye(t)}}class Xi{constructor(e={}){this.volume=M(e.volume,Be.range)??1,this.playbackRate=M(e.playbackRate,je.range)??1,this.preservePitch=P(e.preservePitch)??!0,this.skipBackwardInterval=M(e.skipBackwardInterval,te.range)??10,this.skipForwardInterval=M(e.skipForwardInterval,te.range)??10,this.pollInterval=v(e.pollInterval)??1e3,this.autoPlay=P(e.autoPlay)??!0,this.enableMediaSession=P(e.enableMediaSession)??!0}}class un{constructor(e,t){this.volume=e.volume??t.volume,this.playbackRate=e.playbackRate??t.playbackRate,this.preservePitch=e.preservePitch??t.preservePitch,this.skipBackwardInterval=e.skipBackwardInterval??t.skipBackwardInterval,this.skipForwardInterval=e.skipForwardInterval??t.skipForwardInterval,this.pollInterval=e.pollInterval??t.pollInterval,this.autoPlay=e.autoPlay??t.autoPlay,this.enableMediaSession=e.enableMediaSession??t.enableMediaSession}}class mn{constructor(e,t){this.preferences=e,this.settings=t}clear(){this.preferences=new Ye}updatePreference(e,t){this.preferences[e]=t}get volume(){return new E({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!==null,onChange:e=>{this.updatePreference("volume",e??null)},supportedRange:Be.range,step:Be.step})}get playbackRate(){return new E({initialValue:this.preferences.playbackRate,effectiveValue:this.settings.playbackRate,isEffective:this.preferences.playbackRate!==null,onChange:e=>{this.updatePreference("playbackRate",e??null)},supportedRange:je.range,step:je.step})}get preservePitch(){return new A({initialValue:this.preferences.preservePitch,effectiveValue:this.settings.preservePitch,isEffective:this.preferences.preservePitch!==null,onChange:e=>{this.updatePreference("preservePitch",e??null)}})}get skipBackwardInterval(){return new E({initialValue:this.preferences.skipBackwardInterval,effectiveValue:this.settings.skipBackwardInterval,isEffective:this.preferences.skipBackwardInterval!==null,onChange:e=>{this.updatePreference("skipBackwardInterval",e??null)},supportedRange:te.range,step:te.step})}get skipForwardInterval(){return new E({initialValue:this.preferences.skipForwardInterval,effectiveValue:this.settings.skipForwardInterval,isEffective:this.preferences.skipForwardInterval!==null,onChange:e=>{this.updatePreference("skipForwardInterval",e??null)},supportedRange:te.range,step:te.step})}get pollInterval(){return new T({initialValue:this.preferences.pollInterval,effectiveValue:this.settings.pollInterval,isEffective:this.preferences.pollInterval!==null,onChange:e=>{this.updatePreference("pollInterval",e??null)}})}get autoPlay(){return new A({initialValue:this.preferences.autoPlay,effectiveValue:this.settings.autoPlay,isEffective:this.preferences.autoPlay!==null,onChange:e=>{this.updatePreference("autoPlay",e??null)}})}get enableMediaSession(){return new A({initialValue:this.preferences.enableMediaSession,effectiveValue:this.settings.enableMediaSession,isEffective:this.preferences.enableMediaSession!==null,onChange:e=>{this.updatePreference("enableMediaSession",e??null)}})}}const Yi=1,qi=1;class zr{constructor(e,t,n={}){this.pool=new Map,this._audioEngine=e,this._publication=t,this._supportedAudioTypes=this.detectSupportedAudioTypes(),n.disableRemotePlayback&&(this._audioEngine.getMediaElement().disableRemotePlayback=!0)}detectSupportedAudioTypes(){const e=document.createElement("audio"),t=new Set;for(const i of this._publication.readingOrder.items){i.type&&t.add(i.type);for(const o of i.alternates?.items??[])o.type&&t.add(o.type)}const n=new Map;for(const i of t){const o=e.canPlayType(i);o!==""&&n.set(i,o)}return n}pickPlayableHref(e){const t=this._publication.baseURL,n=[e,...e.alternates?.items??[]];let i;for(const o of n){if(!o.type)continue;const a=this._supportedAudioTypes.get(o.type);if(!a)continue;const s=o.toURL(t)??o.href;if(a==="probably")return s;i||(i={href:s,confidence:a})}return i?.href??e.toURL(t)??e.href}get audioEngine(){return this._audioEngine}ensure(e){let t=this.pool.get(e);return t||(t=document.createElement("audio"),t.preload="auto",this._audioEngine.isWebAudioActive&&(t.crossOrigin="anonymous"),t.src=e,t.load(),this.pool.set(e,t)),t}update(e){const t=this._publication.readingOrder.items,n=new Set;for(let i=0;i<t.length;i++){if(i===e)continue;const o=this.pickPlayableHref(t[i]);i>=e-qi&&i<=e+qi?(this.ensure(o),n.add(o)):i>=e-Yi&&i<=e+Yi&&this.pool.has(o)&&n.add(o)}for(const[i,o]of this.pool)n.has(i)||(o.removeAttribute("src"),o.load(),this.pool.delete(i))}setCurrentAudio(e,t){const n=this.pickPlayableHref(this._publication.readingOrder.items[e]);if(this.audioEngine.changeSrc(n),this.pool.has(n)){const i=this.pool.get(n);i.removeAttribute("src"),i.load(),this.pool.delete(n)}this.update(e)}destroy(){this.audioEngine.stop();for(const[,e]of this.pool)e.removeAttribute("src"),e.load();this.pool.clear()}}class Or{constructor(e={}){this.dragstartHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onDragDetected?.(Array.from(t.dataTransfer?.types??[]))},this.dragoverHandler=t=>{t.preventDefault(),t.stopPropagation()},this.dropHandler=t=>{t.preventDefault(),t.stopPropagation();const n=Array.from(t.dataTransfer?.types??[]),i=t.dataTransfer?.files.length??0;e.onDropDetected?.(n,i)},this.unloadHandler=()=>this.destroy(),document.addEventListener("dragstart",this.dragstartHandler,!0),document.addEventListener("dragover",this.dragoverHandler,!0),document.addEventListener("drop",this.dropHandler,!0),window.addEventListener("unload",this.unloadHandler)}destroy(){document.removeEventListener("dragstart",this.dragstartHandler,!0),document.removeEventListener("dragover",this.dragoverHandler,!0),document.removeEventListener("drop",this.dropHandler,!0),window.removeEventListener("unload",this.unloadHandler)}}class Ar{constructor(e={}){this.copyHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onCopyBlocked?.()},this.unloadHandler=()=>this.destroy(),document.addEventListener("copy",this.copyHandler,!0),window.addEventListener("unload",this.unloadHandler)}destroy(){document.removeEventListener("copy",this.copyHandler,!0),window.removeEventListener("unload",this.unloadHandler)}}class Ur extends nn{constructor(e={}){super(e),e.disableDragAndDrop&&(this.dragAndDropProtector=new Or({onDragDetected:t=>{this.dispatchSuspiciousActivity("drag_detected",{dataTransferTypes:t,targetFrameSrc:""})},onDropDetected:(t,n)=>{this.dispatchSuspiciousActivity("drop_detected",{dataTransferTypes:t,fileCount:n,targetFrameSrc:""})}})),e.protectCopy&&(this.copyProtector=new Ar({onCopyBlocked:()=>{this.dispatchSuspiciousActivity("bulk_copy",{targetFrameSrc:""})}}))}destroy(){super.destroy(),this.dragAndDropProtector?.destroy(),this.copyProtector?.destroy()}}const Tr=r=>({trackLoaded:r.trackLoaded??(()=>{}),positionChanged:r.positionChanged??(()=>{}),timelineItemChanged:r.timelineItemChanged??(()=>{}),error:r.error??(()=>{}),trackEnded:r.trackEnded??(()=>{}),play:r.play??(()=>{}),pause:r.pause??(()=>{}),metadataLoaded:r.metadataLoaded??(()=>{}),stalled:r.stalled??(()=>{}),seeking:r.seeking??(()=>{}),seekable:r.seekable??(()=>{}),contentProtection:r.contentProtection??(()=>{}),peripheral:r.peripheral??(()=>{}),contextMenu:r.contextMenu??(()=>{}),remotePlaybackStateChanged:r.remotePlaybackStateChanged??(()=>{})});class Mr extends ai{constructor(e,t,n,i={preferences:{},defaults:{}}){if(super(),this.positionPollInterval=null,this.navigationId=0,this._playIntent=!1,this._preferencesEditor=null,this._mediaSessionEnabled=!1,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this._isNavigating=!1,this._isStalled=!1,this._stalledWatchdog=null,this._stalledCheckTime=0,this.pub=e,this.listeners=Tr(t),this._preferences=new Ye(i.preferences),this._defaults=new Xi(i.defaults),this._settings=new un(this._preferences,this._defaults),e.readingOrder.items.length===0)throw new Error("AudioNavigator: publication has an empty reading order");if(n)this.currentLocation=this.ensureLocatorLocations(n);else{const u=this.pub.readingOrder.items[0];this.currentLocation=new F({href:u.href,type:u.type||"audio/mpeg",title:u.title,locations:new k({position:1,progression:0,totalProgression:0,fragments:["t=0"]})})}const o=this.currentLocation.href.split("#")[0],a=this.hrefToTrackIndex(o);if(a===-1)throw new Error(`AudioNavigator: initial href "${o}" not found in reading order`);const s=this.currentLocation.locations?.time()||0,l=new $i({playback:{state:{currentTime:s,duration:0},playWhenReady:!1,index:a}});this.pool=new zr(l,e,i.contentProtection);const c=i.contentProtection||{};this._contentProtection=c;const h=this.mergeKeyboardPeripherals(c,i.keyboardPeripherals||[]);(c.disableContextMenu||c.checkAutomation||c.checkIFrameEmbedding||c.monitorDevTools||c.protectPrinting?.disable||c.disableDragAndDrop||c.protectCopy)&&(this._navigatorProtector=new Ur(c),this._suspiciousActivityListener=u=>{const{type:m,...f}=u.detail;m==="context_menu"?this.listeners.contextMenu(f):this.listeners.contentProtection(m,f)},window.addEventListener(de,this._suspiciousActivityListener)),h.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:h}),this._keyboardPeripheralListener=u=>{this.listeners.peripheral(u.detail)},window.addEventListener(ue,this._keyboardPeripheralListener)),this.setupEventListeners(),this._isNavigating=!0,this.pool.setCurrentAudio(a,"forward"),this.applyPreferences(),this.waitForLoadedAndSeeked(s).then(()=>{this._isNavigating=!1,this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._notifyTimelineChange(this.currentLocator),this.listeners.positionChanged(this.currentLocator),this._setupRemotePlayback()}).catch(()=>{this._isNavigating=!1})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new mn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){this._settings=new un(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new mn(this._preferences,this.settings)),this.pool.audioEngine.setVolume(this._settings.volume),this.pool.audioEngine.setPlaybackRate(this._settings.playbackRate,this._settings.preservePitch),this.positionPollInterval!==null&&this.startPositionPolling(),this._settings.enableMediaSession&&!this._mediaSessionEnabled?(this._mediaSessionEnabled=!0,this.setupMediaSession()):!this._settings.enableMediaSession&&this._mediaSessionEnabled&&(this._mediaSessionEnabled=!1,this.destroyMediaSession())}get publication(){return this.pub}get timeline(){return this.pub.timeline}_notifyTimelineChange(e){const t=this.pub.timeline.locate(e);t!==this._currentTimelineItem&&(this._currentTimelineItem=t,this.listeners.timelineItemChanged(t),this._settings.enableMediaSession&&this.updateMediaSessionMetadata())}ensureLocatorLocations(e){return new F({...e,locations:e.locations instanceof k?e.locations:e.locations?new k(e.locations):void 0})}hrefToTrackIndex(e){const t=e.split("#")[0];return this.pub.readingOrder.items.findIndex(n=>n.href===t)}currentTrackIndex(){return this.hrefToTrackIndex(this.currentLocation.href)}get currentLocator(){return this.currentLocation}get isPlaying(){return this.pool.audioEngine.isPlaying()}get isPaused(){return this.pool.audioEngine.isPaused()}get duration(){return this.pool.audioEngine.duration()}get currentTime(){return this.pool.audioEngine.currentTime()}createLocator(e,t){const n=this.pub.readingOrder.items[e];if(!n)throw new Error(`Invalid track index: ${e}`);const i=this.pool.audioEngine.duration();return new F({href:n.href,type:n.type||"audio/mpeg",title:n.title,locations:new k({progression:i>0?t/i:0,position:e+1,fragments:[`t=${t}`]})})}waitForLoadedAndSeeked(e,t){return new Promise((n,i)=>{const o=()=>{if(t!==void 0&&t!==this.navigationId){n();return}if(e<=0){n();return}const l=()=>{this.pool.audioEngine.off("seeked",l),n()};this.pool.audioEngine.on("seeked",l),this.seek(e)};if(this.pool.audioEngine.isLoaded()){o();return}const a=()=>{this.pool.audioEngine.off("canplaythrough",a),this.pool.audioEngine.off("error",s),o()},s=l=>{this.pool.audioEngine.off("canplaythrough",a),this.pool.audioEngine.off("error",s),i(l)};this.pool.audioEngine.on("canplaythrough",a),this.pool.audioEngine.on("error",s)})}setupEventListeners(){this.pool.audioEngine.on("error",e=>{this.listeners.error(e,this.currentLocator)}),this.pool.audioEngine.on("ended",async()=>{this.stopPositionPolling(),this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex()+1,progression:1,fragments:[`t=${this.duration}`]})),this.listeners.trackEnded(this.currentLocator),this.canGoForward&&(await this.nextTrack(),this._settings.autoPlay&&this.play())}),this.pool.audioEngine.on("play",()=>{this._isNavigating||(this.startPositionPolling(),this.listeners.play(this.currentLocator))}),this.pool.audioEngine.on("playing",()=>{this._isNavigating||this._setStalled(!1)}),this.pool.audioEngine.on("pause",()=>{this._isNavigating||(this.stopPositionPolling(),this.listeners.pause(this.currentLocator))}),this.pool.audioEngine.on("seeked",()=>{if(this._isNavigating)return;this.listeners.seeking(!1);const e=this.currentTime,t=this.duration,n=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex()+1,progression:n,fragments:[`t=${e}`]})),this._notifyTimelineChange(this.currentLocation),this.listeners.positionChanged(this.currentLocation)}),this.pool.audioEngine.on("seeking",()=>{this._isNavigating||this.listeners.seeking(!0)}),this.pool.audioEngine.on("waiting",()=>{this._isNavigating||this.listeners.seeking(!0)}),this.pool.audioEngine.on("stalled",()=>{this._isNavigating||this._setStalled(!0)}),this.pool.audioEngine.on("canplaythrough",()=>{this._isNavigating||this._setStalled(!1)}),this.pool.audioEngine.on("progress",e=>{this._isNavigating||this.listeners.seekable(e)}),this.pool.audioEngine.on("loadedmetadata",()=>{const e=this.pool.audioEngine.getMediaElement(),t={duration:this.pool.audioEngine.duration(),textTracks:e.textTracks,readyState:e.readyState,networkState:e.networkState};this.listeners.metadataLoaded(t)})}_setStalled(e){this._isStalled!==e&&(this._isStalled=e,this.listeners.stalled(e),e?(this._stalledCheckTime=this.currentTime,this._startStalledWatchdog()):this._stopStalledWatchdog())}_startStalledWatchdog(){this._stalledWatchdog=setInterval(()=>{if(!this.isPlaying){this._setStalled(!1);return}const e=this.currentTime;e!==this._stalledCheckTime&&this._setStalled(!1),this._stalledCheckTime=e},500)}_stopStalledWatchdog(){this._stalledWatchdog!==null&&(clearInterval(this._stalledWatchdog),this._stalledWatchdog=null)}setupMediaSession(){"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("previoustrack",()=>this.goBackward(!1,()=>{})),navigator.mediaSession.setActionHandler("nexttrack",()=>this.goForward(!1,()=>{})),navigator.mediaSession.setActionHandler("seekbackward",e=>this.jump(-(e.seekOffset||10))),navigator.mediaSession.setActionHandler("seekforward",e=>this.jump(e.seekOffset||10)),this.updateMediaSessionMetadata())}updateMediaSessionMetadata(){if(!("mediaSession"in navigator))return;const e=this.currentTrackIndex(),t=this.pub.readingOrder.items[e],n=this.pub.getCover();navigator.mediaSession.metadata=new MediaMetadata({title:t?.title||`Track ${e+1}`,artist:this.pub.metadata.authors?this.pub.metadata.authors.items.map(i=>i.name.getTranslation()).join(", "):void 0,album:this.pub.metadata.title.getTranslation(),artwork:n?[{src:n.toURL(this.pub.baseURL)??n.href,type:n.type}]:void 0})}startPositionPolling(){this.stopPositionPolling(),this.positionPollInterval=setInterval(()=>{const e=this.currentTime,t=this.duration,n=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex()+1,progression:n,fragments:[`t=${e}`]})),this._notifyTimelineChange(this.currentLocation),this.listeners.positionChanged(this.currentLocation)},this._settings.pollInterval)}stopPositionPolling(){this.positionPollInterval!==null&&(clearInterval(this.positionPollInterval),this.positionPollInterval=null)}async go(e,t,n){try{e=this.ensureLocatorLocations(e);const i=e.href.split("#")[0],o=this.hrefToTrackIndex(i),a=e.locations?.time()||0;if(o===-1){n(!1);return}const s=++this.navigationId,l=this.currentTrackIndex(),c=o>=l?"forward":"backward",h=this.isPlaying||this._playIntent;if(this._playIntent=h,this._isNavigating=!0,this.stopPositionPolling(),this.pool.setCurrentAudio(o,c),this.currentLocation=e.copyWithLocations(e.locations),await this.waitForLoadedAndSeeked(a,s),this._isNavigating=!1,s!==this.navigationId){n(!1);return}o!==l&&this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._notifyTimelineChange(this.currentLocator),this.listeners.positionChanged(this.currentLocator),this._settings.enableMediaSession&&this.updateMediaSessionMetadata(),h&&this.play(),n(!0)}catch(i){this._isNavigating=!1,console.error("Failed to go to locator:",i),n(!1)}finally{this._playIntent=!1}}async goLink(e,t,n){const i=this.hrefToTrackIndex(e.href);if(i===-1){n(!1);return}const o=e.locator.locations?.time()??0,a=this.createLocator(i,o);await this.go(a,t,n)}async goForward(e,t){if(!this.canGoForward){t(!1);return}await this.nextTrack(),t(!0)}async goBackward(e,t){if(!this.canGoBackward){t(!1);return}await this.previousTrack(),t(!0)}play(){this.pool.audioEngine.play()}pause(){this.pool.audioEngine.pause()}stop(){this.pool.audioEngine.stop()}async nextTrack(){if(!this.canGoForward)return;const e=this.createLocator(this.currentTrackIndex()+1,0);await this.go(e,!1,()=>{})}async previousTrack(){if(!this.canGoBackward)return;const e=this.createLocator(this.currentTrackIndex()-1,0);await this.go(e,!1,()=>{})}seek(e){this.pool.audioEngine.skip(e-this.pool.audioEngine.currentTime())}jump(e){this.pool.audioEngine.skip(e)}skipForward(){this.pool.audioEngine.skip(this._settings.skipForwardInterval)}skipBackward(){this.pool.audioEngine.skip(-this._settings.skipBackwardInterval)}get isTrackStart(){return this.currentTrackIndex()===0&&(this.currentLocation.locations?.time()||0)===0}get isTrackEnd(){const e=this.currentTrackIndex();if(e!==this.pub.readingOrder.items.length-1)return!1;const t=this.currentLocation.locations?.progression;if(t!==void 0)return t>=1;const n=this.pub.readingOrder.items[e],i=this.duration||n?.duration||0;return i>0&&(this.currentLocation.locations?.time()??0)>=i}get canGoBackward(){return this.currentTrackIndex()>0}get canGoForward(){return this.currentTrackIndex()<this.pub.readingOrder.items.length-1}get remotePlayback(){const e=this.pool.audioEngine.getMediaElement();return"remote"in e?e.remote:void 0}_setupRemotePlayback(){if(this._contentProtection.disableRemotePlayback)return;const e=this.remotePlayback;e&&(e.onconnecting=()=>this.listeners.remotePlaybackStateChanged("connecting"),e.onconnect=()=>this.listeners.remotePlaybackStateChanged("connected"),e.ondisconnect=()=>this.listeners.remotePlaybackStateChanged("disconnected"))}destroyMediaSession(){"mediaSession"in navigator&&(navigator.mediaSession.metadata=null,navigator.mediaSession.setActionHandler("play",null),navigator.mediaSession.setActionHandler("pause",null),navigator.mediaSession.setActionHandler("previoustrack",null),navigator.mediaSession.setActionHandler("nexttrack",null),navigator.mediaSession.setActionHandler("seekbackward",null),navigator.mediaSession.setActionHandler("seekforward",null))}destroy(){this.stopPositionPolling(),this._stopStalledWatchdog(),this.destroyMediaSession(),this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),this.pool.destroy()}}const Ki=JSON.parse(`{"format":{"audiobook":"Livre audio","audiobookJSON":"Manifeste de livre audio","cbz":"Bande dessinée","divina":"Bande dessinée Divina","divinaJSON":"Manifeste de bande dessinée Divina","epub":"EPUB","lcpa":"Livre audio protégé par LCP","lcpdf":"PDF protégé par LCP","lcpl":"Licence LCP","pdf":"PDF","rwp":"Publication web Readium","rwpm":"Manifeste de publication web Readium","zab":"Livre audio","zip":"Archive ZIP"},"kind":{"audiobook_many":"livres audio","audiobook_one":"livre audio","audiobook_other":"livres audio","book_many":"livres","book_one":"livre","book_other":"livres","comic_many":"bandes dessinées","comic_one":"bande dessinée","comic_other":"bandes dessinées","document_many":"documents","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"Aucune information disponible","publisher-contact":"Pour plus d'information à propos de l'accessibilité de cette publication, veuillez contacter l'éditeur : ","title":"Informations d'accessibilité supplémentaires fournies par l'éditeur"},"additional-accessibility-information":{"aria":{"compact":"Information enrichie pour les technologies d'assistances","descriptive":"La structure est enrichi de rôles ARIA afin d'optimiser l'organisation et de faciliter la navigation via les technologies d'assistances"},"audio-descriptions":"Description audio","braille":"Braille","color-not-sole-means-of-conveying-information":"La couleur n'est pas la seule manière de communiquer de l'information","dyslexia-readability":"Lisibilité adapté aux publics dys","full-ruby-annotations":"Annotations complètes au format ruby (langues asiatiques)","high-contrast-between-foreground-and-background-audio":"Contraste sonore amélioré entre les différents plans","high-contrast-between-text-and-background":"Contraste élevé entre le texte et l'arrière-plan","large-print":"Grands caractères","page-breaks":{"compact":"Pagination identique à l'imprimé","descriptive":"Contient une pagination identique à la version imprimée"},"ruby-annotations":"Annotations partielles au format ruby (langues asiatiques)","sign-language":"Langue des signes","tactile-graphics":{"compact":"Graphiques tactiles","descriptive":"Des graphiques tactiles ont été intégrés pour faciliter l'accès des personnes aveugles aux éléments visuels"},"tactile-objects":"Objets 3D ou tactiles","text-to-speech-hinting":"Prononciation améliorée pour la synthèse vocale","title":"Informations complémentaires sur l'accessibilité","ultra-high-contrast-between-text-and-background":"Contraste très élevé entre le texte et l'arrière-plan","visible-page-numbering":"Numérotation de page visible","without-background-sounds":"Aucun bruit de fond"},"conformance":{"a":{"compact":"Cette publication répond aux règles minimales d'accessibilité","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau A"},"aa":{"compact":"Cette publication répond aux règles d'accessibilité reconnues","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau AA"},"aaa":{"compact":"Cette publication dépasse les règles d'accessibilité reconnues","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau AAA"},"certifier":"Accessibilité évaluée par ","certifier-credentials":"L'évaluateur est accrédité par ","details":{"certification-info":"Cette publication a été certifié le","certifier-report":"Pour plus d'information, veuillez consulter le rapport de certification","claim":"Cette publication indique respecter","epub-accessibility-1-0":"EPUB Accessibilité 1.0","epub-accessibility-1-1":"EPUB Accessibilité 1.1","level-a":"Niveau A","level-aa":"Niveau AA","level-aaa":"Niveau AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.2"}},"details-title":"Information détaillée","no":"Aucune information disponible","title":"Règles d'accessibilité","unknown-standard":"Aucune indication concernant les normes d'accessibilité"},"hazards":{"flashing":{"compact":"Flashs lumineux","descriptive":"La publication contient des flashs lumineux qui peuvent provoquer des crises d’épilepsie"},"flashing-none":{"compact":"Pas de flashs lumineux","descriptive":"La publication ne contient pas de flashs lumineux susceptibles de provoquer des crises d’épilepsie"},"flashing-unknown":{"compact":"Pas d'information concernant la présence de flashs lumineux","descriptive":"La présence de flashs lumineux susceptibles de provoquer des crises d’épilepsie n'a pas pu être déterminée"},"motion":{"compact":"Sensations de mouvement","descriptive":"La publication contient des images en mouvement qui peuvent provoquer des nausées, des vertiges et des maux de tête"},"motion-none":{"compact":"Pas de sensations de mouvement","descriptive":"La publication ne contient pas d'images en mouvement qui pourraient provoquer des nausées, des vertiges et des maux de tête"},"motion-unknown":{"compact":"Pas d'information concernant la présence d'images en mouvement","descriptive":"La présence d'images en mouvement susceptibles de provoquer des nausées, des vertiges et des maux de tête n'a pas pu être déterminée"},"no-metadata":"Aucune information disponible","none":{"compact":"Aucun points d'attention","descriptive":"La publication ne présente aucun risque lié à la présence de flashs lumineux, de sensations de mouvement ou de sons"},"sound":{"compact":"Sons","descriptive":"La publication contient des sons qui peuvent causer des troubles de la sensibilité"},"sound-none":{"compact":"Pas de risques sonores","descriptive":"La publication ne contient pas de sons susceptibles de provoquer des troubles de la sensibilité"},"sound-unknown":{"compact":"Pas d'information concernant la présence de sons","descriptive":"La présence de sons susceptibles de causer des troubles de sensibilité n'a pas pu être déterminée"},"title":"Points d'attention","unknown":"La présence de risques est inconnue"},"legal-considerations":{"exempt":{"compact":"Déclare être sous le coup d'une exemption dans certaines juridictions","descriptive":"Cette publication dééclare être sous le coup d'une exemption dans certaines juridictions"},"no-metadata":"Aucune information disponible","title":"Considérations légales"},"navigation":{"index":{"compact":"Index","descriptive":"Index comportant des liens vers les entrées référencées"},"no-metadata":"Aucune information disponible","page-navigation":{"compact":"Aller à la page","descriptive":"Permet d'accéder aux pages de la version source imprimée"},"structural":{"compact":"Titres","descriptive":"Contient des titres pour une navigation structurée"},"title":"Points de repère","toc":{"compact":"Table des matières","descriptive":"Table des matières"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Formules chimiques en LaTeX","descriptive":"Formules chimiques en format accessible (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Formules chimiques en MathML","descriptive":"Formules chimiques en format accessible (MathML)"},"accessible-math-as-latex":{"compact":"Mathématiques en LaTeX","descriptive":"Formules mathématiques en format accessible (LaTeX)"},"accessible-math-described":"Des descriptions textuelles des formules mathématiques sont fournies","closed-captions":{"compact":"Sous-titres disponibles pour les vidéos","descriptive":"Des sous titres sont disponibles pour les vidéos"},"extended-descriptions":"Les images porteuses d'informations complexes sont décrites par des descriptions longues","math-as-mathml":{"compact":"Mathématiques en MathML","descriptive":"Formules mathématiques en format accessible (MathML)"},"open-captions":{"compact":"Sous-titres incrustés","descriptive":"Des sous titres sont incrustés pour les vidéos"},"title":"Contenus spécifiques","transcript":"Transcriptions fournies","unknown":"Aucune information disponible"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Images décrites","descriptive":"Les images sont décrites par un texte"},"no-metadata":"Aucune information pour la lecture en voix de synthèse ou en braille","none":{"compact":"Non lisible en voix de synthèse ou en braille","descriptive":"Le contenu n'est pas lisible en voix de synthèse ou en braille"},"not-fully":{"compact":"Pas entièrement lisible en voix de synthèse ou en braille","descriptive":"Tous les contenus ne pourront pas être lus à haute voix ou en braille"},"readable":{"compact":"Entièrement lisible en voix de synthèse ou en braille","descriptive":"Tous les contenus peuvent être lus en voix de synthèse ou en braille"}},"prerecorded-audio":{"complementary":{"compact":"Clips audio préenregistrés","descriptive":"Des clips audio préenregistrés sont intégrés au contenu"},"no-metadata":"Aucune information sur les enregistrements audio","only":{"compact":"Audio préenregistré uniquement","descriptive":"Livre audio sans texte alternatif"},"synchronized":{"compact":"Audio préenregistré synchronisé avec du texte","descriptive":"Tous les contenus sont disponibles comme audio préenregistrés synchronisés avec le texte"}},"title":"Lisibilité","visual-adjustments":{"modifiable":{"compact":"L'affichage peut être adapté","descriptive":"L'apparence du texte et la mise en page peuvent être modifiées en fonction des capacités du système de lecture (famille et taille des polices, espaces entre les paragraphes, les phrases, les mots et les lettres, ainsi que la couleur de l'arrière-plan et du texte)"},"unknown":"Aucune information sur les possibilités d'adaptation de l'affichage","unmodifiable":{"compact":"L'affichage ne peut pas être adapté","descriptive":"Le texte et la mise en page ne peuvent pas être adaptés étant donné que l'expérience de lecture est proche de celle de la version imprimée, mais l'application de lecture peut tout de même proposer la capacité de zoomer"}}}}},"altIdentifier_many":"","altIdentifier_one":"identifiant alternatif","altIdentifier_other":"identifiants alternatifs","artist_many":"","artist_one":"artiste","artist_other":"artiste","author_many":"","author_one":"auteur","author_other":"auteurs","collection_many":"","collection_one":"collection éditoriale","collection_other":"collections éditoriales","colorist_many":"","colorist_one":"coloriste","colorist_other":"coloristes","contributor_many":"","contributor_one":"contributeur","contributor_other":"contributeurs","description":"description","duration":"durée","editor_many":"","editor_one":"éditeur","editor_other":"éditeurs","identifier_many":"","identifier_one":"identifiant","identifier_other":"identifiants","illustrator_many":"","illustrator_one":"illustrateur","illustrator_other":"illustrateurs","imprint_many":"","imprint_one":"marque éditoriale","imprint_other":"marques éditoriales","inker_many":"","inker_one":"encreur","inker_other":"encreurs","language_many":"","language_one":"langue","language_other":"langues","letterer_many":"","letterer_one":"lettreur","letterer_other":"lettreurs","modified":"date de modification","narrator_many":"","narrator_one":"narrateur","narrator_other":"narrateurs","numberOfPages":"pagination papier","penciler_many":"","penciler_one":"dessinateur","penciler_other":"dessinateurs","published":"date de publication","publisher_many":"","publisher_one":"éditeur","publisher_other":"éditeurs","series_many":"","series_one":"série","series_other":"séries","subject_many":"","subject_one":"catégorie","subject_other":"catégories","subtitle":"sous-titre","title":"titre","translator_many":"","translator_one":"traducteur","translator_other":"traducteurs"}}`),Fr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Ki},publication:Ki},Symbol.toStringTag,{value:"Module"})),Zi={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"لا تتوفر أي معلومات","publisher-contact":"لمزيد من المعلومات حول إمكانية الوصول إلى هذا المنتج، يُرجى التواصل مع الناشر: ",title:"ملخص إمكانية الوصول"},"additional-accessibility-information":{aria:{compact:"أدوار ARIA مدرَجة",descriptive:"يتم تعزيز المحتوى باستخدام أدوار ARIA لتحسين التنظيم وتيسير التنقّل"},"audio-descriptions":"الوصف الصوتي",braille:"برايل","color-not-sole-means-of-conveying-information":"اللون ليس الوسيلة الوحيدة لنقل المعلومات","dyslexia-readability":"سهولة القراءة لذوي عُسر القراءة","full-ruby-annotations":"شروح روبي كاملة","high-contrast-between-foreground-and-background-audio":"تباين عالٍ بين الصوت الرئيسي وصوت الخلفية","high-contrast-between-text-and-background":"تباين عالٍ بين النص والخلفية","large-print":"خط كبير","page-breaks":{compact:"فواصل الصفحات متضمَّنة",descriptive:"فواصل الصفحات متضمَّنة من المصدر المطبوع الأصلي"},"ruby-annotations":"بعض شروح الروبي","sign-language":"لغة الإشارة","tactile-graphics":{compact:"الرسوم اللمسية مدرجة",descriptive:"تم دمج الرسوم اللمسية لتيسير الوصول إلى العناصر البصرية للأشخاص المكفوفين"},"tactile-objects":"مجسمات لمسية ثلاثية الأبعاد","text-to-speech-hinting":"إرشادات تحويل النص إلى كلام (TTS)متوفرة",title:"معلومات إضافية عن إمكانية الوصول","ultra-high-contrast-between-text-and-background":"تباين عالٍ جدًا بين النص والخلفية","visible-page-numbering":"ترقيم صفحات مرئي","without-background-sounds":"من دون أصوات في خلفية"},conformance:{a:{compact:"هذا المنشور يفي بالمعايير الدنيا لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى A من معيار WCAG 2"},aa:{compact:"هذا المنشور يفي بالمعايير المعتمدة لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى AA من معيار WCAG 2"},aaa:{compact:"هذا المنشور يفوق المعايير المقبولة لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى AAA من معيار WCAG 2"},certifier:"تم اعتماد هذا المنشور من قبل ","certifier-credentials":"بيانات اعتماد جهة التصديق ",details:{"certification-info":"تم اعتماد هذا المنشور في تاريخ ","certifier-report":"لمزيد من المعلومات، يرجى الرجوع إلى تقرير جهة التصديق",claim:"يدّعي هذا المنشور أنه يستوفي","epub-accessibility-1-0":"معيار إمكانية الوصول لـ EPUB إصدار 1.0","epub-accessibility-1-1":"معيار إمكانية الوصول لـ EPUB إصدار 1.1","level-a":"المستوى A","level-aa":"المستوى AA","level-aaa":"المستوى AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.2"}},"details-title":"معلومات تفصيلية عن مدى المطابقة",no:"لا تتوفر أي معلومات",title:"المطابقة","unknown-standard":"لا يمكن التأكد من مدى مطابقة هذا المنشور للمعايير المقبولة لإمكانية الوصول"},hazards:{flashing:{compact:"محتوى وامض",descriptive:"يحتوي هذا المنشور على محتوى وامض قد يسبب نوبات حساسة للضوء"},"flashing-none":{compact:"لا توجد مخاطر وميض",descriptive:"لا يحتوي هذا المنشور على محتوى وامض قد يسبب نوبات حساسة للضوء"},"flashing-unknown":{compact:"مخاطر الوميض غير معروفة",descriptive:"لم يُمكن التأكد من وجود محتوى وامض قد يسبب نوبات حساسية للضوء"},motion:{compact:"محاكاة الحركة",descriptive:"يحتوي المنشور على محاكاة حركة قد تسبّب دوار الحركة"},"motion-none":{compact:"لا توجد مخاطر محاكاة الحركة",descriptive:"لا يحتوي المنشور على محاكاة حركة قد تسبّب دوار الحركة"},"motion-unknown":{compact:"مخاطر محاكاة الحركة غير معروفة",descriptive:"تعذّر تحديد ما إذا كانت هناك محاكاة للحركة قد تُسبب دوار الحركة"},"no-metadata":"لا تتوفر أي معلومات",none:{compact:"لا توجد مخاطر",descriptive:"لا يحتوي المنشور على أي مخاطر"},sound:{compact:"أصوات",descriptive:"يحتوي المنشور على أصوات قد تؤدي إلى مشاكل حساسية صوتية"},"sound-none":{compact:"لا توجد مخاطر صوتية",descriptive:"لا يحتوي المنشور على أصوات قد تؤدي إلى مشاكل حساسية صوتية"},"sound-unknown":{compact:"مخاطر الصوت غير معروفة",descriptive:"تعذّر تحديد ما إذا كانت هناك أصوات قد تُسبب مشكلات في الحساسية"},title:"مخاطر",unknown:"وجود المخاطر غير معروف"},"legal-considerations":{exempt:{compact:"يُعلن عن استثناء من متطلبات إمكانية الوصول من بعض السلطات القضائية",descriptive:"يُصرّح هذا المنشور بوجود استثناء من متطلبات إمكانية الوصول من بعض السلطات القضائية"},"no-metadata":"لا تتوفر أي معلومات",title:"اعتبارات قانونية"},navigation:{index:{compact:"كشاف",descriptive:"كشاف يحتوي على روابط إلى الإدخالات المشار إليها"},"no-metadata":"لا تتوفر أي معلومات","page-navigation":{compact:"الانتقال إلى صفحة",descriptive:"قائمة الصفحات للانتقال إلى صفحات من النسخة المطبوعة الأصلية"},structural:{compact:"العناوين",descriptive:"عناصر مثل العناوين والجداول وغيرها للتنقل المنظّم"},title:"التنقل",toc:{compact:"جدول المحتويات",descriptive:"جدول المحتويات لكل فصول النص عبر روابط"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"الصيغ الكيميائية بصيغة LaTeX",descriptive:"الصيغ الكيميائية بشكل ميسر (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"الصيغ الكيميائية بصيغة MathML",descriptive:"الصيغ الكيميائية بشكل ميسر (MathML)"},"accessible-math-as-latex":{compact:"الرياضيات بصيغة LaTeX",descriptive:"الصيغ الرياضية بشكل ميسر (LaTeX)"},"accessible-math-described":"تتوفر أوصاف نصية للصيغ الرياضية","closed-captions":{compact:"تحتوي الفيديوهات على شروح مغلقة",descriptive:"الفيديوهات الموجودة في المنشورات تحتوي على شروح مغلقة"},"extended-descriptions":"يتم وصف الصور الغنية بالمعلومات بأوصاف مفصّلة","math-as-mathml":{compact:"الرياضيات بصيغة MathML",descriptive:"الصيغ الرياضية بشكل ميسر(MathML)"},"open-captions":{compact:"تحتوي الفيديوهات على شروح مدمجة",descriptive:"الفيديوهات الموجودة في المنشورات تحتوي على شروح مدمجة"},title:"محتوى غني",transcript:"يتوفر نص(نصوص)",unknown:"لا تتوفر أي معلومات"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"يحتوي على نص بديل",descriptive:"يحتوي على أوصاف نصية بديلة للصور"},"no-metadata":"لا تتوفر معلومات عن القراءة غير البصرية",none:{compact:"غير قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"المحتوى غير قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية"},"not-fully":{compact:"غير قابل للقراءة بالكامل بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"لن يكون كل المحتوى قابلًا للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية"},readable:{compact:"قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"يمكن قراءة كل المحتوى بصوتٍ عالٍ أو بطريقة برايل الديناميكية"}},"prerecorded-audio":{complementary:{compact:"مقاطع الصوت المسجّلة مسبقًا",descriptive:"مقاطع الصوت المسجّلة مسبقًا مدمجة في المحتوى"},"no-metadata":"لا توجد معلومات عن الصوت المسجّل مسبقًا",only:{compact:"الصوت المسجّل مسبقًا فقط",descriptive:"كتاب صوتي بدون بديل نصي"},synchronized:{compact:"صوت مسجّل مسبقًا متزامن مع النص",descriptive:"كل المحتوى متوفر كصوت مسجّل مسبقًا متزامن مع النص"}},title:"طرق القراءة","visual-adjustments":{modifiable:{compact:"يمكن تعديل المظهر",descriptive:"يمكن تعديل مظهر النص وتخطيط الصفحة وفقاً لإمكانات نظام القراءة (اسم الخط وحجمه، والمسافات بين الفقرات والجمل والكلمات والأحرف، بالإضافة إلى لون الخلفية والنص)"},unknown:"لا توجد معلومات عن إمكانية تعديل المظهر",unmodifiable:{compact:"لا يمكن تعديل المظهر",descriptive:"لا يمكن تعديل مظهر النص وتخطيط الصفحات لأن تجربة القراءة قريبة من النسخة المطبوعة، ولكن تطبيقات القراءة ما زالت تتيح خيارات التكبير"}}}}},altIdentifier_one:"رمز تعريفي بديل",altIdentifier_other:"رموز تعريفية بديلة",artist_one:"فنان",artist_other:"فنانون",author_one:"مؤلف",author_other:"مؤلفون",collection_one:"سلسلة تحريرية",collection_other:"سلاسل تحريرية",colorist_one:"ملوّن الألوان",colorist_other:"ملوّنو الألوان",contributor_one:"مساهم",contributor_other:"مساهمون",description:"وصف",duration:"مدة",editor_one:"محرر",editor_other:"محررون",identifier_one:"رمز تعريفي",identifier_other:"رموز تعريفية",illustrator_one:"رسًام",illustrator_other:"رسامون",imprint_one:"العلامة التجارية للنشر",imprint_other:"العلامات التجارية للنشر",inker_one:"مُحَبِّر",inker_other:"مُحَبِّرون",language_one:"اللغة",language_other:"اللغات",letterer_one:"خطّاط",letterer_other:"خطّاطون",modified:"تاريخ التعديل",narrator_one:"قارئ صوتي",narrator_other:"قرّاء صوتيون",numberOfPages:"عدد الصفحات في النسخة المطبوعة",penciler_one:"رسّام أولي",penciler_other:"رسّامون أوّليون",published:"تاريخ النشر",publisher_one:"ناشر",publisher_other:"ناشرون",series_one:"سلسلة",series_other:"سلاسل",subject_one:"موضوع",subject_other:"مواضيع",subtitle:"عنوان فرعي",title:"العنوان",translator_one:"مترجم",translator_other:"مترجمون"}},Nr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Zi},publication:Zi},Symbol.toStringTag,{value:"Module"})),Ji={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Ingen information tilgængelig","publisher-contact":"For mere information om tilgængeligheden af denne bog, kontakt venligst udgiveren: ",title:"Tilgængeligheds-oversigt"},"additional-accessibility-information":{aria:{compact:"Indeholder ARIA roller",descriptive:"Indhold forbedres med ARIA-roller for at optimere organisering og gøre navigation lettere"},"audio-descriptions":"Lydbeskrivelser",braille:"Punktskrift (braille)","color-not-sole-means-of-conveying-information":"Information gives ikke udelukkende via farver","dyslexia-readability":"Læsbarhed for ordblinde","full-ruby-annotations":'Indeholder såkalde "ruby" notationer (til asiatiske sprog)',"high-contrast-between-foreground-and-background-audio":"Høj kontrast imellem forgrunds- og baggrunds-lyd","high-contrast-between-text-and-background":"Høj kontrast imellem tekst og baggrunden","large-print":"Forstørret tekst","page-breaks":{compact:"Indeholder sideskift",descriptive:"Indeholder sideskift fra den trykte version af bogen"},"ruby-annotations":'Nogle "ruby" annotationer (til asiatiske sprog)',"sign-language":"Tegnsprog","tactile-graphics":{compact:"Indeholder taktil grafik",descriptive:"Indeholder taktil grafik for at muliggøre adgang til visuel information for blinde"},"tactile-objects":"Taktile 3D objekter","text-to-speech-hinting":"Udtaleforbedringer til syntetisk tale",title:"Yderligere information om tilgængelighed","ultra-high-contrast-between-text-and-background":"Ultra høj kontrast imellem tekst og baggrund","visible-page-numbering":"Synlige sidenumre","without-background-sounds":"Uden baggrundslyd"},conformance:{a:{compact:"Denne bog overholder minimum-tilgængelighedskravene",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau A"},aa:{compact:"Denne bog lever op til de accepterede tilgængelighedskrav",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau AA"},aaa:{compact:"Denne bog mere end opfylder de accepterede tilgængelighedskrav",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau AAA"},certifier:"Denne bog blev certificeret af ","certifier-credentials":"Certificeringsorganets legitimationsoplysninger er ",details:{"certification-info":"Bogen blev certificeret den ","certifier-report":"Se certificeringsorganets rapport for mere information",claim:"Denne bog hævder at opfylde","epub-accessibility-1-0":"EPUB Tilgængelighed 1.0","epub-accessibility-1-1":"EPUB Tilgængelighed 1.1","level-a":"Niveau A","level-aa":"Niveau AA","level-aaa":"Niveau AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.2"}},"details-title":"Detaljeret overholdelses-information",no:"Ingen information tilgængelig",title:"Overholdelse","unknown-standard":"Overholdelse af de accepterede tilgængelighedskrav kan ikke vurderes for denne bog"},hazards:{flashing:{compact:"Blinkende indhold",descriptive:"Bogen indeholder blinkende indhold der kan forårsage epileptiske anfald"},"flashing-none":{compact:"Ingen blinkende indhold",descriptive:"Bogen indeholder ikke noget blinkende indhold, der kunne forårsage epileptiske anfald"},"flashing-unknown":{compact:"Ingen information om bogen har blinkende indhold",descriptive:"Det kunne ikke afgøres om bogen indeholder blinkende indhold der kan lede til epileptiske anfald"},motion:{compact:"Simuleret bevægelse",descriptive:"Bogen indeholder simuleret bevægelse, der kan forårsage en følelse af køresyge"},"motion-none":{compact:"Indeholder ikke simuleret bevægelse",descriptive:"Denne bog indeholder ikke noget indhold med simuleret bevægelse, der kunne lede til en følelse af køresyge"},"motion-unknown":{compact:"Ingen information om simuleret bevægelse",descriptive:"Det kunne ikke vurderes om bogen indeholder simuleret bevægelse, der kan lede til en følelse af køresyge"},"no-metadata":"Ingen information tilgængelig",none:{compact:"Ingen farer",descriptive:"Bogen indeholder ikke noget indhold der kategoriseres som farligt"},sound:{compact:"Lyde",descriptive:"Bogen indeholder lyde der kan være ubehagelige hvis man er sensitiv overfor lyde"},"sound-none":{compact:"Ingen ubehagelige lyde",descriptive:"Bogen indeholder ikke lyde der kunne opleves som ubehagelige hvis man er sensitiv overfor lyde"},"sound-unknown":{compact:"Ingen information om ubehagelige lyde",descriptive:"Det kunne ikke afgøres om bogen indeholder ubehagelige lyde"},title:"Farer",unknown:"Ingen information om farligt indhold"},"legal-considerations":{exempt:{compact:"Gør krav på undtagelser fra tilgængelighedskrav",descriptive:"Denne bog gør krav på en tilgængelighedsundtagelse i en eller flere jurisdiktioner"},"no-metadata":"Ingen information tilgængelig",title:"Juridiske overvejelser"},navigation:{index:{compact:"Indholdsfortegnelse",descriptive:"Indholdsfortegnelse med links til referencer"},"no-metadata":"Ingen information tilgængelig","page-navigation":{compact:"Gå til side",descriptive:"Sideliste for at gå til sider fra den trykte kildeversion"},structural:{compact:"Overskrifter",descriptive:"Elementer så som overskrifter og tabeller til struktureret navigation"},title:"Navigation",toc:{compact:"Indholdsfortegnelse",descriptive:"Indholdsfortegnelse med links til alle kapitler"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Kemiske formularer i LaTeX",descriptive:"Kemiske formularer i tilgængeligt format (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Kemiske formularer i MathML notation",descriptive:"Kemiske formularer i tilgængeligt format (MathML)"},"accessible-math-as-latex":{compact:"Matematik som LaTeX",descriptive:"Matematikformler i tilgængeligt format (LaTeX)"},"accessible-math-described":"Tekstbeskrivelser til matematiske formler","closed-captions":{compact:"Videoer har undertekster",descriptive:"Videoer der optræder i bogen har undertekster"},"extended-descriptions":"Informationsrige billeder beskrives med udvidede beskrivelser","math-as-mathml":{compact:"Matematik som MathML",descriptive:"Matematiske formler i tilgængeligt format (MathML)"},"open-captions":{compact:"Videoer har indlejrede undertekster",descriptive:"Videoer der optræder i bogen har indlejrede undertekster"},title:"Komplekst indhold",transcript:"Indeholder transskription(er)",unknown:"Ingen information tilgængelig"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Har alternativ tekst",descriptive:"Har billedbeskrivelser"},"no-metadata":"Ingen information omkring ikke-visuel læsning",none:{compact:"Ikke læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Dette indhold er ikke læsbart med oplæsning eller dynamisk punktskrift"},"not-fully":{compact:"Ikke fuldt læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Alt indholdet er ikke fuldt læsbart med oplæsning eller dynamisk punktskrift"},readable:{compact:"Læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Alt indholdet er læsbart med oplæsning eller dynamisk punktskrift"}},"prerecorded-audio":{complementary:{compact:"Indlæste lydklip",descriptive:"Indlæste lydklip er indlejret i indholdet"},"no-metadata":"Ingen information om indlæst lyd",only:{compact:"Kun indlæst lyd",descriptive:"Lydbog uden tekst alternativer"},synchronized:{compact:"Indlæst lyd med synkroniseret tekst",descriptive:"Alt indholdet er tilgængeligt med indlæst lyd og synkroniseret tekst"}},title:"Læseformer","visual-adjustments":{modifiable:{compact:"Udseende kan ændres",descriptive:"Udseende af tekst og sidelayout kan ændres, så vidt muligt i læsesystemet (skrifttype, skriftstørrelse, afstand mellem afsnit, sætninger, ord og bogstaver, samt farven på tekst og baggrund)"},unknown:"Ingen information om mulighed for ændring af udseende",unmodifiable:{compact:"Udseende kan ikke ændres",descriptive:"Tekst og sidelayout kan ikke ændres, da læseoplevelsen afspejler den trykte version af materialet. Læsesystemet kan dog stadig give mulighed for zoom"}}}}},altIdentifier_one:"alternativt ID",altIdentifier_other:"alternative ID'er",artist_one:"kunstner",artist_other:"kunstnere",author_one:"forfatter",author_other:"forfattere",collection_one:"redaktionel samling",collection_other:"redaktionelle samlinger",colorist_one:"farvelægger",colorist_other:"farvelæggere",contributor_one:"bidragsyder",contributor_other:"bidragsydere",description:"beskrivelse",duration:"varighed",editor_one:"redaktør",editor_other:"redaktører",identifier_one:"ID",identifier_other:"ID'er",illustrator_one:"illustrator",illustrator_other:"illustratorer",imprint_one:"trykkeri",imprint_other:"trykkerier",inker_one:"tegner",inker_other:"tegnere",language_one:"sprog",language_other:"sprog",letterer_one:"taleboble-forfatter",letterer_other:"taleboble-forfattere",modified:"rettet dato",narrator_one:"indlæser",narrator_other:"indlæsere",numberOfPages:"printbare sider",penciler_one:"tegneseriekunstner",penciler_other:"tegneseriekunstnere",published:"udgivelsesdato",publisher_one:"udgiver",publisher_other:"udgivere",series_one:"serie",series_other:"serier",subject_one:"emne",subject_other:"emner",subtitle:"undertitel",title:"titel",translator_one:"oversætter",translator_other:"oversættere"}},Ir=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Ji},publication:Ji},Symbol.toStringTag,{value:"Module"})),Qi=JSON.parse(`{"format":{"audiobook":"Audiolibro","audiobookJSON":"Audiobook Manifest","cbz":"Comic book archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"Audiolibro protetto con LCP","lcpdf":"PDF protetto con LCP","lcpl":"Licenza LCP","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_many":"audiolibri","audiobook_one":"audiolibro","audiobook_other":"audiolibri","book_many":"libri","book_one":"libro","book_other":"libri","comic_many":"fumetti","comic_one":"fumetto","comic_other":"fumetti","document_many":"documenti","document_one":"documento","document_other":"documenti"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"Nessuna informazione disponibile","publisher-contact":"Per ulteriori informazioni sull'accessibilità di questa risorsa, contattare l'editore: ","title":"Informazioni aggiuntive sull'accessibilità fornite dall'editore"},"additional-accessibility-information":{"aria":{"compact":"Ruoli ARIA inclusi","descriptive":"Il contenuto è semanticamente arricchito con ruoli ARIA per ottimizzare l'organizzazione e facilitare la navigazione"},"audio-descriptions":"Descrizioni audio","braille":"Braille","color-not-sole-means-of-conveying-information":"Il colore non è l'unico mezzo per trasmettere informazioni","dyslexia-readability":"Leggibilità adatta alla dislessia","full-ruby-annotations":"Annotazioni complete in Ruby","high-contrast-between-foreground-and-background-audio":"Elevato contrasto tra audio principale e sottofondo","high-contrast-between-text-and-background":"Contrasto elevato tra testo in primo piano e sfondo","large-print":"Stampa a caratteri ingranditi","page-breaks":{"compact":"Interruzioni di pagina incluse","descriptive":"Interruzioni di pagina identiche alla versione originale a stampa"},"ruby-annotations":"Alcune annotazioni in Ruby","sign-language":"Lingua dei segni","tactile-graphics":{"compact":"Grafica tattile inclusa","descriptive":"La grafica tattile è stata integrata per facilitare l'accesso agli elementi visivi alle persone non vedenti"},"tactile-objects":"Oggetti 3D tattili","text-to-speech-hinting":"Pronuncia migliorata per la sintesi vocale","title":"Ulteriori informazioni sull'accessibilità","ultra-high-contrast-between-text-and-background":"Contrasto molto elevato tra testo e sfondo","visible-page-numbering":"Numerazione delle pagine visibile","without-background-sounds":"Nessun suono in sottofondo"},"conformance":{"a":{"compact":"Questa pubblicazione soddisfa gli standard minimi di accessibilità","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello A"},"aa":{"compact":"Questa pubblicazione soddisfa gli standard di accessibilità accettati","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello AAA"},"aaa":{"compact":"Questa pubblicazione supera gli standard di accessibilità","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello AAA"},"certifier":"La pubblicazione è stata certificata da ","certifier-credentials":"Le credenziali del certificatore sono ","details":{"certification-info":"La pubblicazione è stata certificata il ","certifier-report":"Per ulteriori informazioni, consultare il report di accessibilità del certificatore","claim":"Questa pubblicazione è conforme ai requisiti di","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Livello A","level-aa":"Livello AA","level-aaa":"Livello AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.2"}},"details-title":"Informazioni dettagliate sulla conformità","no":"Nessuna informazione disponibile","title":"Conformità","unknown-standard":"Nessuna indicazione sugli standard d'accessibilità"},"hazards":{"flashing":{"compact":"Contenuto lampeggiante","descriptive":"La pubblicazione contiene contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"flashing-none":{"compact":"Nessun contenuto lampeggiante","descriptive":"La pubblicazione non presenta contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"flashing-unknown":{"compact":"Nessuna informazione sulla presenza di contenuti lampeggianti","descriptive":"Non è stato possibile determinare la presenza di contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"motion":{"compact":"Simulazione del movimento","descriptive":"La pubblicazione contiene simulazioni di movimento che possono provocare cinetosi"},"motion-none":{"compact":"Nessun rischio di simulazione del movimento","descriptive":"La pubblicazione non contiene simulazioni di movimento che possono causare la malattia di movimento"},"motion-unknown":{"compact":"Nessuna informazione relativa alla presenza di simulazioni di movimento","descriptive":"Non è stato possibile determinare la presenza di contenuti che possono provocare cinetosi"},"no-metadata":"Nessuna informazione disponibile","none":{"compact":"Nessuna problematica","descriptive":"La pubblicazione non presenta contenuti a rischio di simulazione di movimento, di suoni, o di contenuti lampeggianti"},"sound":{"compact":"Suoni","descriptive":"La pubblicazione contiene suoni che possono causare problemi di sensibilità"},"sound-none":{"compact":"Nessun rischio acustico","descriptive":"La pubblicazione non contiene suoni che possono causare problemi di sensibilità"},"sound-unknown":{"compact":"Nessuna informazione sulla presenza di suoni","descriptive":"Non è stato possibile determinare la presenza di suoni che potrebbero causare problemi di sensibilità"},"title":"Problematiche","unknown":"La presenza di rischi è sconosciuta"},"legal-considerations":{"exempt":{"compact":"Dichiara di godere dell'esenzione d'accessibilità in alcune giurisdizioni","descriptive":"Questa risorsa gode dell'esenzione d'accessibilità in alcune giurisdizioni"},"no-metadata":"Nessuna informazione disponibile","title":"Note legali"},"navigation":{"index":{"compact":"Indice analitico interattivo","descriptive":"Indice analitico con link alle voci di riferimento"},"no-metadata":"Nessuna informazione disponibile","page-navigation":{"compact":"Vai alla pagina","descriptive":"Sono presenti i riferimenti ai numeri di pagina della versione a stampa corrispondente"},"structural":{"compact":"Intestazioni","descriptive":"Contiene elementi come titoli, elenchi e tabelle per permettere una navigazione strutturata"},"title":"Navigazione","toc":{"compact":"Indice interattivo","descriptive":"L’indice permette l’accesso diretto a tutti i capitoli tramite link"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Formule chimiche in LaTeX","descriptive":"Formule chimiche in formato accessibile (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Formule chimiche in MathML","descriptive":"Formule chimiche in formato accessibile (MathML)"},"accessible-math-as-latex":{"compact":"Matematica in LaTeX","descriptive":"Formule matematiche in formato accessibile (LaTeX)"},"accessible-math-described":"Sono disponibili descrizioni testuali per le formule matematiche","closed-captions":{"compact":"Sottotitoli disponibili per i video","descriptive":"Per i video sono disponibili dei sottotitoli"},"extended-descriptions":"Le immagini complesse presentano descrizioni estese","math-as-mathml":{"compact":"Matematica in MathML","descriptive":"Formule matematiche in formato accessibile (MathML)"},"open-captions":{"compact":"I video hanno i sottotitoli","descriptive":"I video inclusi nella pubblicazione hanno i sottotitoli"},"title":"Contenuti arricchiti","transcript":"Trascrizioni fornite","unknown":"Nessuna informazione disponibile"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Immagini descritte","descriptive":"Le immagini sono descritte da un testo"},"no-metadata":"Nessuna informazione sulla lettura non visiva","none":{"compact":"Non leggibile con lettura ad alta voce o in braille","descriptive":"Il contenuto non è leggibile con la lettura ad alta voce o in braille"},"not-fully":{"compact":"Non è interamente leggibile con lettura ad alta voce o in braille","descriptive":"Non tutti i contenuti potranno essere letti con lettura ad alta voce o in braille"},"readable":{"compact":"Interamente leggibile con lettura ad alta voce o in braille","descriptive":"Tutti i contenuti possono essere letti con la lettura ad alta voce o con il display braille"}},"prerecorded-audio":{"complementary":{"compact":"Clip audio preregistrate","descriptive":"Le clip audio preregistrate sono integrate nel contenuto"},"no-metadata":"Non sono disponibili informazioni sull'audio preregistrato","only":{"compact":"Solo audio preregistrato","descriptive":"Audiolibro senza testi alternativi"},"synchronized":{"compact":"Audio preregistrato sincronizzato con il testo","descriptive":"Tutti i contenuti sono disponibili come audio preregistrato sincronizzato con il testo"}},"title":"Leggibilità","visual-adjustments":{"modifiable":{"compact":"La formattazione del testo e il layout della pagina possono essere modificati","descriptive":"La formattazione del testo e il layout della pagina possono essere modificati in base alle funzionalità presenti nella soluzione di lettura (ingrandimento dei caratteri del testo, modifica dei colori e dei contrasti per il testo e lo sfondo, modifica degli spazi tra lettere, parole, frasi e paragrafi)"},"unknown":"Non sono disponibili informazioni sulla possibilità di formattare il testo","unmodifiable":{"compact":"La formattazione del testo e il display della pagina non possono essere modificati","descriptive":"Il layout di testo e pagina non può essere modificato poiché l'esperienza di lettura è vicina a una versione di stampa, ma i sistemi di lettura possono ancora fornire opzioni di zoom"}}}}},"altIdentifier_many":"identificatori alternativi","altIdentifier_one":"identificatore alternativo","altIdentifier_other":"identificatori alternativi","artist_many":"","artist_one":"artista","artist_other":"artisti","author_many":"","author_one":"autore","author_other":"autori","collection_many":"","collection_one":"collana","collection_other":"collane","colorist_many":"","colorist_one":"colorista","colorist_other":"coloristi","contributor_many":"","contributor_one":"contributore","contributor_other":"contributori","description":"descrizione","duration":"durata","editor_many":"","editor_one":"editor","editor_other":"editori","identifier_many":"identificatori","identifier_one":"identificatore","identifier_other":"identificatori","illustrator_many":"","illustrator_one":"illustratore","illustrator_other":"illustratori","imprint_many":"","imprint_one":"marca editoriale","imprint_other":"marche editoriali","inker_many":"","inker_one":"inchiostratore","inker_other":"inchiostratori","language_many":"","language_one":"lingua","language_other":"lingue","letterer_many":"letteristi","letterer_one":"letterista","letterer_other":"letteristi","modified":"Data di modifica","narrator_many":"","narrator_one":"narratore","narrator_other":"narratori","numberOfPages":"impaginazione versione cartacea","penciler_many":"","penciler_one":"disegnatore","penciler_other":"disegnatori","published":"Data di pubblicazione","publisher_many":"","publisher_one":"editore","publisher_other":"editori","series_many":"","series_one":"serie","series_other":"serie","subject_many":"","subject_one":"categoria","subject_other":"categorie","subtitle":"sottotitolo","title":"titolo","translator_many":"","translator_one":"traduttore","translator_other":"traduttori"}}`),Dr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Qi},publication:Qi},Symbol.toStringTag,{value:"Module"})),eo={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Sem informação disponível","publisher-contact":"Para mais informações sobre a acessibilidade deste produto, contacte a editora: ",title:"Resumo de acessibilidade"},"additional-accessibility-information":{aria:{compact:"Inclui funções ARIA",descriptive:"O conteúdo foi otimizado com funções ARIA para melhorar a organização e facilitar a navegação"},"audio-descriptions":"Descrições em áudio",braille:"Braille","color-not-sole-means-of-conveying-information":"A cor não é o único meio de transmitir informação","dyslexia-readability":"Otimizado para dislexia","full-ruby-annotations":"Anotações Ruby completas","high-contrast-between-foreground-and-background-audio":"Alto contraste entre som principal e fundo","high-contrast-between-text-and-background":"Alto contraste entre texto e fundo","large-print":"Impressão ampliada","page-breaks":{compact:"Inclui quebras de página",descriptive:"Inclui quebras de página da fonte impressa original"},"ruby-annotations":"Algumas anotações Ruby","sign-language":"Língua gestual","tactile-graphics":{compact:"Inclui gráficos táteis",descriptive:"Inclui gráficos táteis que facilitam o acesso a elementos visuais para pessoas cegas"},"tactile-objects":"Objetos táteis 3D","text-to-speech-hinting":"Sugestões para leitura em voz alta",title:"Informação adicional de acessibilidade","ultra-high-contrast-between-text-and-background":"Contraste muito elevado entre texto e fundo","visible-page-numbering":"Numeração de páginas visível","without-background-sounds":"Sem sons de fundo"},conformance:{a:{compact:"Cumpre as normas mínimas de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível A"},aa:{compact:"Cumpre as normas aceites de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível AA"},aaa:{compact:"Excede as normas aceites de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível AAA"},certifier:"A publicação foi certificada por ","certifier-credentials":"As credenciais do certificador são ",details:{"certification-info":"A publicação foi certificada em ","certifier-report":"Para mais informações, consulte o relatório do certificador",claim:"Esta publicação declara conformidade com","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Nível A","level-aa":"Nível AA","level-aaa":"Nível AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.2"}},"details-title":"Detalhes de conformidade",no:"Sem informação disponível",title:"Conformidade","unknown-standard":"Não foi possível determinar a conformidade com as normas de acessibilidade aceites para esta publicação"},hazards:{flashing:{compact:"Conteúdo intermitente",descriptive:"A publicação contém conteúdo intermitente que pode causar crises fotossensíveis"},"flashing-none":{compact:"Sem perigos de intermitência",descriptive:"A publicação não contém conteúdo intermitente que possa causar crises fotossensíveis"},"flashing-unknown":{compact:"Risco de intermitência desconhecido",descriptive:"Não foi possível determinar se existe conteúdo intermitente que possa causar crises fotossensíveis"},motion:{compact:"Simulação de movimento",descriptive:"A publicação contém simulações de movimento que podem causar enjoo"},"motion-none":{compact:"Sem simulação de movimento",descriptive:"A publicação não contém simulações de movimento que possam causar enjoo"},"motion-unknown":{compact:"Risco de movimento desconhecido",descriptive:"Não foi possível determinar se existem simulações de movimento que possam causar enjoo"},"no-metadata":"Sem informação disponível",none:{compact:"Sem perigos",descriptive:"A publicação não contém perigos conhecidos"},sound:{compact:"Sons sensíveis",descriptive:"A publicação contém sons que podem causar sensibilidade auditiva"},"sound-none":{compact:"Sem perigos sonoros",descriptive:"A publicação não contém sons que possam causar sensibilidade auditiva"},"sound-unknown":{compact:"Risco sonoro desconhecido",descriptive:"Não foi possível determinar se a publicação contém sons que possam causar sensibilidade auditiva"},title:"Perigos",unknown:"Presença de perigos não determinada"},"legal-considerations":{exempt:{compact:"Declara isenção de conformidade em algumas jurisdições",descriptive:"Esta publicação declara isenção de conformidade em algumas jurisdições"},"no-metadata":"Sem informação disponível",title:"Considerações legais"},navigation:{index:{compact:"Índice remissivo",descriptive:"Índice com ligações para entradas referenciadas"},"no-metadata":"Sem informação disponível","page-navigation":{compact:"Ir para página",descriptive:"Lista de páginas que permite aceder às páginas da versão impressa original"},structural:{compact:"Títulos e estrutura",descriptive:"Elementos como títulos, tabelas, etc., para navegação estruturada"},title:"Navegação",toc:{compact:"Índice",descriptive:"Índice de conteúdos com ligações para todos os capítulos do texto"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Fórmulas químicas em LaTeX",descriptive:"Fórmulas químicas em formato acessível (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Fórmulas químicas em MathML",descriptive:"Fórmulas químicas em formato acessível (MathML)"},"accessible-math-as-latex":{compact:"Matemática em LaTeX",descriptive:"Fórmulas matemáticas em formato acessível (LaTeX)"},"accessible-math-described":"Descrição textual das fórmulas matemáticas","closed-captions":{compact:"Vídeos com legendas ocultas",descriptive:"Os vídeos incluídos na publicação têm legendas ocultas"},"extended-descriptions":"Imagens complexas com descrições detalhadas","math-as-mathml":{compact:"Matemática em MathML",descriptive:"Fórmulas matemáticas em formato acessível (MathML)"},"open-captions":{compact:"Vídeos com legendas abertas",descriptive:"Os vídeos incluídos na publicação têm legendas abertas"},title:"Conteúdo rico",transcript:"Transcrição fornecida",unknown:"Sem informação disponível"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Contém texto alternativo",descriptive:"Inclui descrições alternativas de texto para imagens"},"no-metadata":"Sem informação sobre leitura não visual",none:{compact:"Não legível em leitura em voz alta ou braille dinâmico",descriptive:"O conteúdo não é legível em voz alta ou através de braille dinâmico"},"not-fully":{compact:"Parcialmente legível em leitura em voz alta ou braille dinâmico",descriptive:"Nem todo o conteúdo é legível em voz alta ou através de braille dinâmico"},readable:{compact:"Totalmente legível em leitura em voz alta ou braille dinâmico",descriptive:"Todo o conteúdo pode ser lido em voz alta ou através de braille dinâmico"}},"prerecorded-audio":{complementary:{compact:"Contém clipes de áudio pré-gravados",descriptive:"O conteúdo contém clipes de áudio pré-gravados incorporados"},"no-metadata":"Sem informação sobre áudio pré-gravado",only:{compact:"Apenas áudio pré-gravado",descriptive:"A publicação é apenas áudio e não possui alternativa em texto"},synchronized:{compact:"Áudio pré-gravado sincronizado com texto",descriptive:"Todo o conteúdo está disponível como áudio pré-gravado sincronizado com texto"}},title:"Formas de leitura","visual-adjustments":{modifiable:{compact:"Aspeto personalizável",descriptive:"O aspeto do texto e o layout da página podem ser modificados de acordo com as capacidades do sistema de leitura (tipo e tamanho de letra, espaçamento entre parágrafos, frases, palavras e letras, bem como a cor de fundo e do texto)"},unknown:"Sem informação sobre personalização do aspeto",unmodifiable:{compact:"Aspeto não ajustável",descriptive:"O texto e o layout da página não podem ser modificados, uma vez que a experiência de leitura é semelhante à versão impressa, mas os sistemas de leitura ainda podem oferecer opções de ampliação"}}}}},altIdentifier_one:"identificador alternativo",altIdentifier_other:"identificadores alternativos",artist_one:"artista",artist_other:"artistas",author_one:"autor",author_other:"autores",collection_one:"coleção",collection_other:"coleções",colorist_one:"colorista",colorist_other:"coloristas",contributor_one:"colaborador",contributor_other:"colaboradores",description:"descrição",duration:"duração",editor_one:"editor",editor_other:"editores",identifier_one:"identificador",identifier_other:"identificadores",illustrator_one:"ilustrador",illustrator_other:"ilustradores",imprint_one:"selo editorial",imprint_other:"selos editoriais",inker_one:"arte-finalista",inker_other:"arte-finalistas",language_one:"idioma",language_other:"idiomas",letterer_one:"letrista",letterer_other:"letristas",modified:"data de modificação",narrator_one:"narrador",narrator_other:"narradores",numberOfPages:"número de páginas",penciler_one:"desenhador",penciler_other:"desenhadores",published:"data de publicação",publisher_one:"editora",publisher_other:"editoras",series_one:"série",series_other:"séries",subject_one:"tema",subject_other:"temas",subtitle:"subtítulo",title:"título",translator_one:"tradutor",translator_other:"tradutores"}},Hr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:eo},publication:eo},Symbol.toStringTag,{value:"Module"})),to={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Information saknas","publisher-contact":"För mer information om den här publikationens tillgänglighet, kontakta utgivaren: ",title:"Kompletterande information om tillgänglighet"},"additional-accessibility-information":{aria:{compact:"Innehåller ARIA-roller",descriptive:"Innehållet har försetts med ARIA-roller för att tydliggöra strukturen och underlätta navigering"},"audio-descriptions":"Syntolkning",braille:"Punktskrift","color-not-sole-means-of-conveying-information":"Betydelse uttrycks aldrig enbart med färg","dyslexia-readability":"Förbättrad läsbarhet för personer med dyslexi","full-ruby-annotations":"Fullständig ruby-annotering","high-contrast-between-foreground-and-background-audio":"Hög kontrast mellan förgrundsljud och bakgrundsljud","high-contrast-between-text-and-background":"Hög kontrast mellan text och bakgrund","large-print":"Storstil","page-breaks":{compact:"Innehåller sidnummer",descriptive:"Innehåller sidnummer från tryckt förlaga"},"ruby-annotations":"Viss ruby-annotering","sign-language":"Teckenspråk","tactile-graphics":{compact:"Innehåller taktila bilder",descriptive:"Taktila bilder har lagts till för att tillgängliggöra visuella element för personer med synnedsättning"},"tactile-objects":"Taktila 3D-objekt","text-to-speech-hinting":"Innehåller uttalsinstruktioner för talsyntes",title:"Ytterligare tillgänglighetsinformation","ultra-high-contrast-between-text-and-background":"Extra hög kontrast mellan text och bakgrund","visible-page-numbering":"Synlig sidnumrering","without-background-sounds":"Utan bakgrundsljud"},conformance:{a:{compact:"Publikationen uppfyller tillgänglighetskrav på en grundläggande nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå A"},aa:{compact:"Publikationen uppfyller tillgänglighetskrav på en vedertagen nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå AA"},aaa:{compact:"Publikationen uppfyller tillgänglighetskrav utöver en vedertagen nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå AAA"},certifier:"Publikationen är certifierad av ","certifier-credentials":"Certifierarens märkning är ",details:{"certification-info":"Publikationen certifierades ","certifier-report":"Se certifieringsrapporten för mer information",claim:"Publikationen anger att den uppfyller kraven enligt","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"nivå A","level-aa":"nivå AA","level-aaa":"nivå AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detaljerad information om tillgänglighetskrav",no:"Information saknas",title:"Tillgänglighetskrav","unknown-standard":"Det går inte att avgöra om publikationen uppfyller vedertagna tillgänglighetskrav"},hazards:{flashing:{compact:"Blinkande innehåll",descriptive:"Publikationen har blinkande innehåll som kan vara skadligt för ljuskänsliga personer"},"flashing-none":{compact:"Inget blinkande innehåll",descriptive:"Publikationen har inget blinkande innehåll"},"flashing-unknown":{compact:"Förekomst av blinkande innehåll är okänd",descriptive:"Förekomst av blinkande innehåll är okänd"},motion:{compact:"Rörelsesimulering",descriptive:"Publikationen innehåller rörelsesimulering som skulle kunna orsaka illamående"},"motion-none":{compact:"Ingen rörelsesimulering",descriptive:"Publikationen innehåller ingen rörelsesimulering"},"motion-unknown":{compact:"Förekomst av rörelsesimulering är okänd",descriptive:"Förekomst av rörelsesimulering är okänd"},"no-metadata":"Information saknas",none:{compact:"Inga risker",descriptive:"Publikationen innehåller inga risker"},sound:{compact:"Ljud",descriptive:"Publikationen innehåller ljud som kan orsaka obehag"},"sound-none":{compact:"Inget ljud som kan orsaka obehag",descriptive:"Publikationen innehåller inget ljud som kan orsaka obehag"},"sound-unknown":{compact:"Förekomst av ljud som kan orsaka obehag är okänd",descriptive:"Förekomst av ljud som kan orsaka obehag är okänd"},title:"Risker",unknown:"Förekomst av risker är okänd"},"legal-considerations":{exempt:{compact:"Åberopar ett undantag från vissa lagstadgade tillgänglighetskrav",descriptive:"Publikationen åberopar ett undantag från vissa lagstadgade tillgänglighetskrav"},"no-metadata":"Information saknas",title:"Juridiska aspekter"},navigation:{index:{compact:"Register",descriptive:"Register med länkar till innehållet"},"no-metadata":"Information saknas","page-navigation":{compact:"Gå till sida",descriptive:"Sidindelning för navigering enligt sidnummer i tryckt förlaga"},structural:{compact:"Rubriker",descriptive:"Navigerbara element såsom rubriker eller tabeller"},title:"Navigering",toc:{compact:"Innehållsförteckning",descriptive:"Innehållsförteckning med länkar till alla kapitel"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Kemiska formler i LaTeX",descriptive:"Kemiska formler i tillgängligt format (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Kemiska formler i MathML",descriptive:"Kemiska formler i tillgängligt format (MathML)"},"accessible-math-as-latex":{compact:"Matematik som LaTeX",descriptive:"Matematiska formler i tillgängligt format (LaTeX)"},"accessible-math-described":"Innehåller textbeskrivningar av matematik","closed-captions":{compact:"Videoklipp har undertext som kan sättas på/stängas av",descriptive:"Videoklipp som ingår i publikationen har undertext som kan sättas på och stängas av (stängda undertexter)"},"extended-descriptions":"Informationsrika bilder har utökade bildbeskrivningar","math-as-mathml":{compact:"Matematik som MathML",descriptive:"Matematiska formler i tillgängligt format (MathML)"},"open-captions":{compact:"Videoklipp har undertext som inte kan stängas av",descriptive:"Videoklipp som ingår i publikationen har undertext som inte kan stängas av (öppna undertexter)"},title:"Berikat innehåll",transcript:"Innehåller transkriptioner",unknown:"Information saknas"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Har textalternativ (alt-texter)",descriptive:"Har textalternativ (alt-texter) till bilder"},"no-metadata":"Information om icke-visuell läsbarhet saknas",none:{compact:"Kan inte läsas med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Innehållet går inte att läsa med uppläsningsfunktion eller punktskriftsskärm"},"not-fully":{compact:"Inte läsbart i sin helhet med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Allt innehåll går inte att läsa med uppläsningsfunktion eller punktskriftsskärm"},readable:{compact:"Kan läsas med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Hela innehållet går att läsa med uppläsningsfunktion eller punktskriftsskärm"}},"prerecorded-audio":{complementary:{compact:"Förinspelade ljudklipp",descriptive:"Innehåller förinspelade ljudklipp"},"no-metadata":"Information om förinspelat ljud saknas",only:{compact:"Endast förinspelat ljud",descriptive:"Bok med ljud utan textalternativ"},synchronized:{compact:"Förinspelat ljud synkroniserat med texten",descriptive:"Hela innehållet finns tillgängligt som förinspelat ljud synkroniserat med texten"}},title:"Olika sätt att läsa","visual-adjustments":{modifiable:{compact:"Utseendet kan justeras",descriptive:"Det går att justera text och layout i den utsträckning som läsprogrammet tillåter, till exempel typsnitt, storlek på text, avstånd mellan rader och stycken samt färg på text och bakgrund"},unknown:"Information om möjlighet att justera utseende saknas",unmodifiable:{compact:"Utseendet kan inte justeras",descriptive:"Text- och sidlayout kan inte justeras eftersom presentationen liknar en tryckt version, men läsprogram kan ha funktioner för att zooma in"}}}}},altIdentifier_one:"alternativ identifierare",altIdentifier_other:"alternativa identifierare",artist_one:"konstnär",artist_other:"konstnärer",author_one:"författare",author_other:"författare",collection_one:"samling",collection_other:"samlingar",colorist_one:"kolorist",colorist_other:"kolorister",contributor_one:"medverkande",contributor_other:"medverkande",description:"beskrivning",duration:"speltid",editor_one:"redaktör",editor_other:"redaktörer",identifier_one:"identifierare",identifier_other:"identifierare",illustrator_one:"illustratör",illustrator_other:"illustratörer",imprint_one:"imprint",imprint_other:"imprint",inker_one:"tuschare",inker_other:"tuschare",language_one:"språk",language_other:"språk",letterer_one:"textare",letterer_other:"textare",modified:"ändringsdatum",narrator_one:"berättarröst",narrator_other:"berättarröster",numberOfPages:"sidantal",penciler_one:"tecknare",penciler_other:"tecknare",published:"publikationsdatum",publisher_one:"förlag",publisher_other:"förlag",series_one:"serie",series_other:"serier",subject_one:"ämne",subject_other:"ämnen",subtitle:"undertitel",title:"titel",translator_one:"översättare",translator_other:"översättare"}},Wr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:to},publication:to},Symbol.toStringTag,{value:"Module"})),Br=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
695
- * Readium CSS v.2.0.0
693
+ `;class dn{constructor(e){this.workletNode=null,this.url=null,this.ctx=e}static async createWorklet(e){const{ctx:t,pitchFactor:n,modulePath:i}=e,o=new dn(t);try{if(i)await t.audioWorklet.addModule(i);else{const a=new Blob([Ur],{type:"text/javascript"});o.url=URL.createObjectURL(a),await t.audioWorklet.addModule(o.url)}}catch(a){throw o.destroy(),new Error(`Error adding module: ${a}`)}try{o.workletNode=new AudioWorkletNode(t,"preserve-pitch-processor"),n&&o.updatePitchFactor(n)}catch(a){throw o.destroy(),new Error(`Error creating worklet node: ${a}`)}return o}updatePitchFactor(e){this.workletNode&&this.workletNode.port.postMessage({type:"setPitchFactor",factor:e})}destroy(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.url&&(URL.revokeObjectURL(this.url),this.url=null)}}class $i{constructor(e){this.audioContext=null,this.sourceNode=null,this.gainNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.isStoppedValue=!1,this.worklet=null,this.webAudioActive=!1,this.boundOnCanPlayThrough=this.onCanPlayThrough.bind(this),this.boundOnTimeUpdate=this.onTimeUpdate.bind(this),this.boundOnError=this.onError.bind(this),this.boundOnEnded=this.onEnded.bind(this),this.boundOnStalled=this.onStalled.bind(this),this.boundOnEmptied=this.onEmptied.bind(this),this.boundOnSuspend=this.onSuspend.bind(this),this.boundOnWaiting=this.onWaiting.bind(this),this.boundOnLoadedMetadata=this.onLoadedMetadata.bind(this),this.boundOnSeeking=this.onSeeking.bind(this),this.boundOnSeeked=this.onSeeked.bind(this),this.boundOnPlay=this.onPlay.bind(this),this.boundOnPlaying=this.onPlaying.bind(this),this.boundOnPause=this.onPause.bind(this),this.boundOnProgress=this.onProgress.bind(this),this.playback=e.playback,this.mediaElement=document.createElement("audio"),this.mediaElement.addEventListener("canplaythrough",this.boundOnCanPlayThrough),this.mediaElement.addEventListener("timeupdate",this.boundOnTimeUpdate),this.mediaElement.addEventListener("error",this.boundOnError),this.mediaElement.addEventListener("ended",this.boundOnEnded),this.mediaElement.addEventListener("stalled",this.boundOnStalled),this.mediaElement.addEventListener("emptied",this.boundOnEmptied),this.mediaElement.addEventListener("suspend",this.boundOnSuspend),this.mediaElement.addEventListener("waiting",this.boundOnWaiting),this.mediaElement.addEventListener("loadedmetadata",this.boundOnLoadedMetadata),this.mediaElement.addEventListener("seeking",this.boundOnSeeking),this.mediaElement.addEventListener("seeked",this.boundOnSeeked),this.mediaElement.addEventListener("play",this.boundOnPlay),this.mediaElement.addEventListener("playing",this.boundOnPlaying),this.mediaElement.addEventListener("pause",this.boundOnPause),this.mediaElement.addEventListener("progress",this.boundOnProgress),this.mediaElement.currentTime=this.playback.state.currentTime}on(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)}off(e,t){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter(n=>n!==t))}async ensureAudioContextRunning(){this.audioContext||(this.audioContext=new AudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume()}getOrCreateAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}onStalled(e){this.emit("stalled",e)}onEmptied(e){this.emit("emptied",e)}onSuspend(e){this.emit("suspend",e)}onWaiting(e){this.emit("waiting",e)}onLoadedMetadata(e){this.emit("loadedmetadata",e)}onSeeking(e){this.emit("seeking",e)}onSeeked(e){this.emit("seeked",e)}onPlay(){this.emit("play",null)}onPlaying(){this.emit("playing",null)}onPause(){this.emit("pause",null)}onProgress(){this.emit("progress",this.mediaElement.seekable)}emit(e,t){this.listeners[e]&&this.listeners[e].forEach(n=>n(t))}async play(){if(!this.isPlayingValue)try{this.audioContext&&await this.ensureAudioContextRunning(),await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1,this.isStoppedValue=!1}catch(e){if(e?.name==="AbortError")return;console.error("error trying to play media element",e),this.emit("error",e)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1,this.isStoppedValue=!0}setVolume(e){const t=Math.max(0,Math.min(1,e));this.gainNode?(this.mediaElement.volume=1,this.gainNode.gain.value=t):this.mediaElement.volume=t,this.isMutedValue=t===0}skip(e){const t=this.mediaElement.duration;if(!isFinite(t))return;const n=this.mediaElement.currentTime+e;n<0?this.mediaElement.currentTime=0:n>t?this.mediaElement.currentTime=t:this.mediaElement.currentTime=n}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return this.isStoppedValue}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}setPlaybackRate(e,t){this.mediaElement.playbackRate=e,t?"preservesPitch"in this.mediaElement?this.mediaElement.preservesPitch=!0:this.activateWebAudio().then(()=>{this.worklet?this.worklet.updatePitchFactor(1/e):dn.createWorklet({ctx:this.getOrCreateAudioContext(),pitchFactor:1}).then(n=>{this.sourceNode&&this.sourceNode.disconnect(),this.worklet=n,this.sourceNode?.connect(this.worklet.workletNode),this.worklet.workletNode.connect(this.gainNode),this.worklet.updatePitchFactor(1/e)}).catch(n=>{console.warn("Failed to create preserve pitch worklet",n)})}).catch(n=>{console.warn("Web Audio unavailable, playing without pitch correction:",n)}):("preservesPitch"in this.mediaElement&&(this.mediaElement.preservesPitch=!1),this.worklet&&(this.worklet.destroy(),this.worklet=null,this.webAudioActive&&this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode.connect(this.gainNode))))}async activateWebAudio(){if(this.webAudioActive)return;const e=this.mediaElement.src;if(!e)return;const t=this.mediaElement.currentTime,n=this.isPlayingValue;n&&(this.mediaElement.pause(),this.isPlayingValue=!1),this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load();try{await new Promise((o,a)=>{const s=()=>{this.mediaElement.removeEventListener("canplaythrough",s),this.mediaElement.removeEventListener("error",l),o()},l=()=>{this.mediaElement.removeEventListener("canplaythrough",s),this.mediaElement.removeEventListener("error",l),a(new Error("Audio reload with CORS failed — server may not send Access-Control-Allow-Origin"))};this.mediaElement.addEventListener("canplaythrough",s),this.mediaElement.addEventListener("error",l)})}catch(o){throw this.mediaElement.removeAttribute("crossorigin"),this.mediaElement.src=e,this.mediaElement.load(),n?(await new Promise(a=>{const s=()=>{this.mediaElement.removeEventListener("canplaythrough",s),a()};this.mediaElement.addEventListener("canplaythrough",s)}),this.mediaElement.currentTime=t,await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1):this.mediaElement.currentTime=t,o}this.mediaElement.currentTime=t,this.sourceNode=new MediaElementAudioSourceNode(this.getOrCreateAudioContext(),{mediaElement:this.mediaElement});const i=this.getOrCreateAudioContext();this.gainNode=i.createGain(),this.gainNode.gain.value=this.mediaElement.volume,this.mediaElement.volume=1,this.sourceNode.connect(this.gainNode),this.gainNode.connect(i.destination),this.webAudioActive=!0,n&&(await this.ensureAudioContextRunning(),await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1)}get isWebAudioActive(){return this.webAudioActive}tearDownWebAudio(){this.worklet&&(this.worklet.destroy(),this.worklet=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.gainNode&&(this.mediaElement.volume=this.gainNode.gain.value,this.gainNode.disconnect(),this.gainNode=null),this.webAudioActive=!1}changeSrc(e){if(this.mediaElement.src!==e)if(this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadedValue=!1,this.isLoadingValue=!0,this.isEndedValue=!1,this.webAudioActive){this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load();const t=()=>{i()},n=()=>{i(),console.warn("CORS reload failed for new track — disabling Web Audio graph:",e),this.tearDownWebAudio(),this.mediaElement.removeAttribute("crossorigin"),this.mediaElement.src=e,this.mediaElement.load()},i=()=>{this.mediaElement.removeEventListener("canplaythrough",t),this.mediaElement.removeEventListener("error",n)};this.mediaElement.addEventListener("canplaythrough",t),this.mediaElement.addEventListener("error",n)}else this.mediaElement.src=e,this.mediaElement.load()}getMediaElement(){return this.mediaElement}}class Xe{constructor(e={}){this.volume=T(e.volume,Be.range),this.playbackRate=T(e.playbackRate,je.range),this.preservePitch=R(e.preservePitch),this.skipBackwardInterval=T(e.skipBackwardInterval,te.range),this.skipForwardInterval=T(e.skipForwardInterval,te.range),this.pollInterval=v(e.pollInterval),this.autoPlay=R(e.autoPlay),this.enableMediaSession=R(e.enableMediaSession)}merging(e){const t={...this};for(const n of Object.keys(e))e[n]!==void 0&&(t[n]=e[n]);return new Xe(t)}}class Ki{constructor(e={}){this.volume=T(e.volume,Be.range)??1,this.playbackRate=T(e.playbackRate,je.range)??1,this.preservePitch=R(e.preservePitch)??!0,this.skipBackwardInterval=T(e.skipBackwardInterval,te.range)??10,this.skipForwardInterval=T(e.skipForwardInterval,te.range)??10,this.pollInterval=v(e.pollInterval)??1e3,this.autoPlay=R(e.autoPlay)??!0,this.enableMediaSession=R(e.enableMediaSession)??!0}}class un{constructor(e,t){this.volume=e.volume??t.volume,this.playbackRate=e.playbackRate??t.playbackRate,this.preservePitch=e.preservePitch??t.preservePitch,this.skipBackwardInterval=e.skipBackwardInterval??t.skipBackwardInterval,this.skipForwardInterval=e.skipForwardInterval??t.skipForwardInterval,this.pollInterval=e.pollInterval??t.pollInterval,this.autoPlay=e.autoPlay??t.autoPlay,this.enableMediaSession=e.enableMediaSession??t.enableMediaSession}}class mn{constructor(e,t){this.preferences=e,this.settings=t}clear(){this.preferences=new Xe}updatePreference(e,t){this.preferences[e]=t}get volume(){return new k({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!==null,onChange:e=>{this.updatePreference("volume",e??null)},supportedRange:Be.range,step:Be.step})}get playbackRate(){return new k({initialValue:this.preferences.playbackRate,effectiveValue:this.settings.playbackRate,isEffective:this.preferences.playbackRate!==null,onChange:e=>{this.updatePreference("playbackRate",e??null)},supportedRange:je.range,step:je.step})}get preservePitch(){return new O({initialValue:this.preferences.preservePitch,effectiveValue:this.settings.preservePitch,isEffective:this.preferences.preservePitch!==null,onChange:e=>{this.updatePreference("preservePitch",e??null)}})}get skipBackwardInterval(){return new k({initialValue:this.preferences.skipBackwardInterval,effectiveValue:this.settings.skipBackwardInterval,isEffective:this.preferences.skipBackwardInterval!==null,onChange:e=>{this.updatePreference("skipBackwardInterval",e??null)},supportedRange:te.range,step:te.step})}get skipForwardInterval(){return new k({initialValue:this.preferences.skipForwardInterval,effectiveValue:this.settings.skipForwardInterval,isEffective:this.preferences.skipForwardInterval!==null,onChange:e=>{this.updatePreference("skipForwardInterval",e??null)},supportedRange:te.range,step:te.step})}get pollInterval(){return new U({initialValue:this.preferences.pollInterval,effectiveValue:this.settings.pollInterval,isEffective:this.preferences.pollInterval!==null,onChange:e=>{this.updatePreference("pollInterval",e??null)}})}get autoPlay(){return new O({initialValue:this.preferences.autoPlay,effectiveValue:this.settings.autoPlay,isEffective:this.preferences.autoPlay!==null,onChange:e=>{this.updatePreference("autoPlay",e??null)}})}get enableMediaSession(){return new O({initialValue:this.preferences.enableMediaSession,effectiveValue:this.settings.enableMediaSession,isEffective:this.preferences.enableMediaSession!==null,onChange:e=>{this.updatePreference("enableMediaSession",e??null)}})}}const Xi=1,Yi=1;class Tr{constructor(e,t,n={}){this.pool=new Map,this._audioEngine=e,this._publication=t,this._supportedAudioTypes=this.detectSupportedAudioTypes(),n.disableRemotePlayback&&(this._audioEngine.getMediaElement().disableRemotePlayback=!0)}detectSupportedAudioTypes(){const e=document.createElement("audio"),t=new Set;for(const i of this._publication.readingOrder.items){i.type&&t.add(i.type);for(const o of i.alternates?.items??[])o.type&&t.add(o.type)}const n=new Map;for(const i of t){const o=e.canPlayType(i);o!==""&&n.set(i,o)}return n}pickPlayableHref(e){const t=this._publication.baseURL,n=[e,...e.alternates?.items??[]];let i;for(const o of n){if(!o.type)continue;const a=this._supportedAudioTypes.get(o.type);if(!a)continue;const s=o.toURL(t)??o.href;if(a==="probably")return s;i||(i={href:s,confidence:a})}return i?.href??e.toURL(t)??e.href}get audioEngine(){return this._audioEngine}ensure(e){let t=this.pool.get(e);return t||(t=document.createElement("audio"),t.preload="auto",this._audioEngine.isWebAudioActive&&(t.crossOrigin="anonymous"),t.src=e,t.load(),this.pool.set(e,t)),t}update(e){const t=this._publication.readingOrder.items,n=new Set;for(let i=0;i<t.length;i++){if(i===e)continue;const o=this.pickPlayableHref(t[i]);i>=e-Yi&&i<=e+Yi?(this.ensure(o),n.add(o)):i>=e-Xi&&i<=e+Xi&&this.pool.has(o)&&n.add(o)}for(const[i,o]of this.pool)n.has(i)||(o.removeAttribute("src"),o.load(),this.pool.delete(i))}setCurrentAudio(e,t){const n=this.pickPlayableHref(this._publication.readingOrder.items[e]);if(this.audioEngine.changeSrc(n),this.pool.has(n)){const i=this.pool.get(n);i.removeAttribute("src"),i.load(),this.pool.delete(n)}this.update(e)}destroy(){this.audioEngine.stop();for(const[,e]of this.pool)e.removeAttribute("src"),e.load();this.pool.clear()}}class Nr{constructor(e={}){this.dragstartHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onDragDetected?.(Array.from(t.dataTransfer?.types??[]))},this.dragoverHandler=t=>{t.preventDefault(),t.stopPropagation()},this.dropHandler=t=>{t.preventDefault(),t.stopPropagation();const n=Array.from(t.dataTransfer?.types??[]),i=t.dataTransfer?.files.length??0;e.onDropDetected?.(n,i)},this.unloadHandler=()=>this.destroy(),document.addEventListener("dragstart",this.dragstartHandler,!0),document.addEventListener("dragover",this.dragoverHandler,!0),document.addEventListener("drop",this.dropHandler,!0),window.addEventListener("unload",this.unloadHandler)}destroy(){document.removeEventListener("dragstart",this.dragstartHandler,!0),document.removeEventListener("dragover",this.dragoverHandler,!0),document.removeEventListener("drop",this.dropHandler,!0),window.removeEventListener("unload",this.unloadHandler)}}class Mr{constructor(e={}){this.copyHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onCopyBlocked?.()},this.unloadHandler=()=>this.destroy(),document.addEventListener("copy",this.copyHandler,!0),window.addEventListener("unload",this.unloadHandler)}destroy(){document.removeEventListener("copy",this.copyHandler,!0),window.removeEventListener("unload",this.unloadHandler)}}class Ir extends nn{constructor(e={}){super(e),e.disableDragAndDrop&&(this.dragAndDropProtector=new Nr({onDragDetected:t=>{this.dispatchSuspiciousActivity("drag_detected",{dataTransferTypes:t,targetFrameSrc:""})},onDropDetected:(t,n)=>{this.dispatchSuspiciousActivity("drop_detected",{dataTransferTypes:t,fileCount:n,targetFrameSrc:""})}})),e.protectCopy&&(this.copyProtector=new Mr({onCopyBlocked:()=>{this.dispatchSuspiciousActivity("bulk_copy",{targetFrameSrc:""})}}))}destroy(){super.destroy(),this.dragAndDropProtector?.destroy(),this.copyProtector?.destroy()}}const Hr=r=>({trackLoaded:r.trackLoaded??(()=>{}),positionChanged:r.positionChanged??(()=>{}),timelineItemChanged:r.timelineItemChanged??(()=>{}),error:r.error??(()=>{}),trackEnded:r.trackEnded??(()=>{}),play:r.play??(()=>{}),pause:r.pause??(()=>{}),metadataLoaded:r.metadataLoaded??(()=>{}),stalled:r.stalled??(()=>{}),seeking:r.seeking??(()=>{}),seekable:r.seekable??(()=>{}),contentProtection:r.contentProtection??(()=>{}),peripheral:r.peripheral??(()=>{}),contextMenu:r.contextMenu??(()=>{}),remotePlaybackStateChanged:r.remotePlaybackStateChanged??(()=>{})});class Dr extends ai{constructor(e,t,n,i={preferences:{},defaults:{}}){if(super(),this.positionPollInterval=null,this.navigationId=0,this._playIntent=!1,this._preferencesEditor=null,this._mediaSessionEnabled=!1,this._navigatorProtector=null,this._keyboardPeripheralsManager=null,this._suspiciousActivityListener=null,this._keyboardPeripheralListener=null,this._isNavigating=!1,this._isStalled=!1,this._stalledWatchdog=null,this._stalledCheckTime=0,this.pub=e,this.listeners=Hr(t),this._preferences=new Xe(i.preferences),this._defaults=new Ki(i.defaults),this._settings=new un(this._preferences,this._defaults),e.readingOrder.items.length===0)throw new Error("AudioNavigator: publication has an empty reading order");if(n)this.currentLocation=this.ensureLocatorLocations(n);else{const u=this.pub.readingOrder.items[0];this.currentLocation=new N({href:u.href,type:u.type||"audio/mpeg",title:u.title,locations:new C({position:1,progression:0,totalProgression:0,fragments:["t=0"]})})}const o=this.currentLocation.href.split("#")[0],a=this.hrefToTrackIndex(o);if(a===-1)throw new Error(`AudioNavigator: initial href "${o}" not found in reading order`);const s=this.currentLocation.locations?.time()||0,l=new $i({playback:{state:{currentTime:s,duration:0},playWhenReady:!1,index:a}});this.pool=new Tr(l,e,i.contentProtection);const c=i.contentProtection||{};this._contentProtection=c;const h=this.mergeKeyboardPeripherals(c,i.keyboardPeripherals||[]);(c.disableContextMenu||c.checkAutomation||c.checkIFrameEmbedding||c.monitorDevTools||c.protectPrinting?.disable||c.disableDragAndDrop||c.protectCopy)&&(this._navigatorProtector=new Ir(c),this._suspiciousActivityListener=u=>{const{type:m,...f}=u.detail;m==="context_menu"?this.listeners.contextMenu(f):this.listeners.contentProtection(m,f)},window.addEventListener(de,this._suspiciousActivityListener)),h.length>0&&(this._keyboardPeripheralsManager=new on({keyboardPeripherals:h}),this._keyboardPeripheralListener=u=>{this.listeners.peripheral(u.detail)},window.addEventListener(ue,this._keyboardPeripheralListener)),this.setupEventListeners(),this._isNavigating=!0,this.pool.setCurrentAudio(a,"forward"),this.applyPreferences(),this.waitForLoadedAndSeeked(s).then(()=>{this._isNavigating=!1,this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._notifyTimelineChange(this.currentLocator),this.listeners.positionChanged(this.currentLocator),this._setupRemotePlayback()}).catch(()=>{this._isNavigating=!1})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new mn(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){this._settings=new un(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new mn(this._preferences,this.settings)),this.pool.audioEngine.setVolume(this._settings.volume),this.pool.audioEngine.setPlaybackRate(this._settings.playbackRate,this._settings.preservePitch),this.positionPollInterval!==null&&this.startPositionPolling(),this._settings.enableMediaSession&&!this._mediaSessionEnabled?(this._mediaSessionEnabled=!0,this.setupMediaSession()):!this._settings.enableMediaSession&&this._mediaSessionEnabled&&(this._mediaSessionEnabled=!1,this.destroyMediaSession())}get publication(){return this.pub}get timeline(){return this.pub.timeline}_notifyTimelineChange(e){const t=this.pub.timeline.locate(e);t!==this._currentTimelineItem&&(this._currentTimelineItem=t,this.listeners.timelineItemChanged(t),this._settings.enableMediaSession&&this.updateMediaSessionMetadata())}ensureLocatorLocations(e){return new N({...e,locations:e.locations instanceof C?e.locations:e.locations?new C(e.locations):void 0})}hrefToTrackIndex(e){const t=e.split("#")[0];return this.pub.readingOrder.items.findIndex(n=>n.href===t)}currentTrackIndex(){return this.hrefToTrackIndex(this.currentLocation.href)}get currentLocator(){return this.currentLocation}get isPlaying(){return this.pool.audioEngine.isPlaying()}get isPaused(){return this.pool.audioEngine.isPaused()}get duration(){return this.pool.audioEngine.duration()}get currentTime(){return this.pool.audioEngine.currentTime()}createLocator(e,t){const n=this.pub.readingOrder.items[e];if(!n)throw new Error(`Invalid track index: ${e}`);const i=this.pool.audioEngine.duration();return new N({href:n.href,type:n.type||"audio/mpeg",title:n.title,locations:new C({progression:i>0?t/i:0,position:e+1,fragments:[`t=${t}`]})})}waitForLoadedAndSeeked(e,t){return new Promise((n,i)=>{const o=()=>{if(t!==void 0&&t!==this.navigationId){n();return}if(e<=0){n();return}const l=()=>{this.pool.audioEngine.off("seeked",l),n()};this.pool.audioEngine.on("seeked",l),this.seek(e)};if(this.pool.audioEngine.isLoaded()){o();return}const a=()=>{this.pool.audioEngine.off("canplaythrough",a),this.pool.audioEngine.off("error",s),o()},s=l=>{this.pool.audioEngine.off("canplaythrough",a),this.pool.audioEngine.off("error",s),i(l)};this.pool.audioEngine.on("canplaythrough",a),this.pool.audioEngine.on("error",s)})}setupEventListeners(){this.pool.audioEngine.on("error",e=>{this.listeners.error(e,this.currentLocator)}),this.pool.audioEngine.on("ended",async()=>{this.stopPositionPolling(),this.currentLocation=this.currentLocation.copyWithLocations(new C({position:this.currentTrackIndex()+1,progression:1,fragments:[`t=${this.duration}`]})),this.listeners.trackEnded(this.currentLocator),this.canGoForward&&(await this.nextTrack(),this._settings.autoPlay&&this.play())}),this.pool.audioEngine.on("play",()=>{this._isNavigating||(this.startPositionPolling(),this.listeners.play(this.currentLocator))}),this.pool.audioEngine.on("playing",()=>{this._isNavigating||this._setStalled(!1)}),this.pool.audioEngine.on("pause",()=>{this._isNavigating||(this.stopPositionPolling(),this.listeners.pause(this.currentLocator))}),this.pool.audioEngine.on("seeked",()=>{if(this._isNavigating)return;this.listeners.seeking(!1);const e=this.currentTime,t=this.duration,n=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new C({position:this.currentTrackIndex()+1,progression:n,fragments:[`t=${e}`]})),this._notifyTimelineChange(this.currentLocation),this.listeners.positionChanged(this.currentLocation)}),this.pool.audioEngine.on("seeking",()=>{this._isNavigating||this.listeners.seeking(!0)}),this.pool.audioEngine.on("waiting",()=>{this._isNavigating||this.listeners.seeking(!0)}),this.pool.audioEngine.on("stalled",()=>{this._isNavigating||this._setStalled(!0)}),this.pool.audioEngine.on("canplaythrough",()=>{this._isNavigating||this._setStalled(!1)}),this.pool.audioEngine.on("progress",e=>{this._isNavigating||this.listeners.seekable(e)}),this.pool.audioEngine.on("loadedmetadata",()=>{const e=this.pool.audioEngine.getMediaElement(),t={duration:this.pool.audioEngine.duration(),textTracks:e.textTracks,readyState:e.readyState,networkState:e.networkState};this.listeners.metadataLoaded(t)})}_setStalled(e){this._isStalled!==e&&(this._isStalled=e,this.listeners.stalled(e),e?(this._stalledCheckTime=this.currentTime,this._startStalledWatchdog()):this._stopStalledWatchdog())}_startStalledWatchdog(){this._stalledWatchdog=setInterval(()=>{if(!this.isPlaying){this._setStalled(!1);return}const e=this.currentTime;e!==this._stalledCheckTime&&this._setStalled(!1),this._stalledCheckTime=e},500)}_stopStalledWatchdog(){this._stalledWatchdog!==null&&(clearInterval(this._stalledWatchdog),this._stalledWatchdog=null)}setupMediaSession(){"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("play",()=>this.play()),navigator.mediaSession.setActionHandler("pause",()=>this.pause()),navigator.mediaSession.setActionHandler("previoustrack",()=>this.goBackward(!1,()=>{})),navigator.mediaSession.setActionHandler("nexttrack",()=>this.goForward(!1,()=>{})),navigator.mediaSession.setActionHandler("seekbackward",e=>this.jump(-(e.seekOffset||10))),navigator.mediaSession.setActionHandler("seekforward",e=>this.jump(e.seekOffset||10)),this.updateMediaSessionMetadata())}updateMediaSessionMetadata(){if(!("mediaSession"in navigator))return;const e=this.currentTrackIndex(),t=this.pub.readingOrder.items[e],n=this.pub.getCover();navigator.mediaSession.metadata=new MediaMetadata({title:t?.title||`Track ${e+1}`,artist:this.pub.metadata.authors?this.pub.metadata.authors.items.map(i=>i.name.getTranslation()).join(", "):void 0,album:this.pub.metadata.title.getTranslation(),artwork:n?[{src:n.toURL(this.pub.baseURL)??n.href,type:n.type}]:void 0})}startPositionPolling(){this.stopPositionPolling(),this.positionPollInterval=setInterval(()=>{const e=this.currentTime,t=this.duration,n=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new C({position:this.currentTrackIndex()+1,progression:n,fragments:[`t=${e}`]})),this._notifyTimelineChange(this.currentLocation),this.listeners.positionChanged(this.currentLocation)},this._settings.pollInterval)}stopPositionPolling(){this.positionPollInterval!==null&&(clearInterval(this.positionPollInterval),this.positionPollInterval=null)}async go(e,t,n){try{e=this.ensureLocatorLocations(e);const i=e.href.split("#")[0],o=this.hrefToTrackIndex(i),a=e.locations?.time()||0;if(o===-1){n(!1);return}const s=++this.navigationId,l=this.currentTrackIndex(),c=o>=l?"forward":"backward",h=this.isPlaying||this._playIntent;if(this._playIntent=h,this._isNavigating=!0,this.stopPositionPolling(),this.pool.setCurrentAudio(o,c),this.currentLocation=e.copyWithLocations(e.locations),await this.waitForLoadedAndSeeked(a,s),this._isNavigating=!1,s!==this.navigationId){n(!1);return}o!==l&&this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._notifyTimelineChange(this.currentLocator),this.listeners.positionChanged(this.currentLocator),this._settings.enableMediaSession&&this.updateMediaSessionMetadata(),h&&this.play(),n(!0)}catch(i){this._isNavigating=!1,console.error("Failed to go to locator:",i),n(!1)}finally{this._playIntent=!1}}async goLink(e,t,n){const i=this.hrefToTrackIndex(e.href);if(i===-1){n(!1);return}const o=e.locator.locations?.time()??0,a=this.createLocator(i,o);await this.go(a,t,n)}async goForward(e,t){if(!this.canGoForward){t(!1);return}await this.nextTrack(),t(!0)}async goBackward(e,t){if(!this.canGoBackward){t(!1);return}await this.previousTrack(),t(!0)}play(){this.pool.audioEngine.play()}pause(){this.pool.audioEngine.pause()}stop(){this.pool.audioEngine.stop()}async nextTrack(){if(!this.canGoForward)return;const e=this.createLocator(this.currentTrackIndex()+1,0);await this.go(e,!1,()=>{})}async previousTrack(){if(!this.canGoBackward)return;const e=this.createLocator(this.currentTrackIndex()-1,0);await this.go(e,!1,()=>{})}seek(e){this.pool.audioEngine.skip(e-this.pool.audioEngine.currentTime())}jump(e){this.pool.audioEngine.skip(e)}skipForward(){this.pool.audioEngine.skip(this._settings.skipForwardInterval)}skipBackward(){this.pool.audioEngine.skip(-this._settings.skipBackwardInterval)}get isTrackStart(){return this.currentTrackIndex()===0&&(this.currentLocation.locations?.time()||0)===0}get isTrackEnd(){const e=this.currentTrackIndex();if(e!==this.pub.readingOrder.items.length-1)return!1;const t=this.currentLocation.locations?.progression;if(t!==void 0)return t>=1;const n=this.pub.readingOrder.items[e],i=this.duration||n?.duration||0;return i>0&&(this.currentLocation.locations?.time()??0)>=i}get canGoBackward(){return this.currentTrackIndex()>0}get canGoForward(){return this.currentTrackIndex()<this.pub.readingOrder.items.length-1}get remotePlayback(){const e=this.pool.audioEngine.getMediaElement();return"remote"in e?e.remote:void 0}_setupRemotePlayback(){if(this._contentProtection.disableRemotePlayback)return;const e=this.remotePlayback;e&&(e.onconnecting=()=>this.listeners.remotePlaybackStateChanged("connecting"),e.onconnect=()=>this.listeners.remotePlaybackStateChanged("connected"),e.ondisconnect=()=>this.listeners.remotePlaybackStateChanged("disconnected"))}destroyMediaSession(){"mediaSession"in navigator&&(navigator.mediaSession.metadata=null,navigator.mediaSession.setActionHandler("play",null),navigator.mediaSession.setActionHandler("pause",null),navigator.mediaSession.setActionHandler("previoustrack",null),navigator.mediaSession.setActionHandler("nexttrack",null),navigator.mediaSession.setActionHandler("seekbackward",null),navigator.mediaSession.setActionHandler("seekforward",null))}destroy(){this.stopPositionPolling(),this._stopStalledWatchdog(),this.destroyMediaSession(),this._suspiciousActivityListener&&window.removeEventListener(de,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(ue,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),this.pool.destroy()}}const qi=JSON.parse(`{"format":{"audiobook":"Livre audio","audiobookJSON":"Manifeste de livre audio","cbz":"Bande dessinée","divina":"Bande dessinée Divina","divinaJSON":"Manifeste de bande dessinée Divina","epub":"EPUB","lcpa":"Livre audio protégé par LCP","lcpdf":"PDF protégé par LCP","lcpl":"Licence LCP","pdf":"PDF","rwp":"Publication web Readium","rwpm":"Manifeste de publication web Readium","zab":"Livre audio","zip":"Archive ZIP"},"kind":{"audiobook_many":"livres audio","audiobook_one":"livre audio","audiobook_other":"livres audio","book_many":"livres","book_one":"livre","book_other":"livres","comic_many":"bandes dessinées","comic_one":"bande dessinée","comic_other":"bandes dessinées","document_many":"documents","document_one":"document","document_other":"documents"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"Aucune information disponible","publisher-contact":"Pour plus d'information à propos de l'accessibilité de cette publication, veuillez contacter l'éditeur : ","title":"Informations d'accessibilité supplémentaires fournies par l'éditeur"},"additional-accessibility-information":{"aria":{"compact":"Information enrichie pour les technologies d'assistances","descriptive":"La structure est enrichi de rôles ARIA afin d'optimiser l'organisation et de faciliter la navigation via les technologies d'assistances"},"audio-descriptions":"Description audio","braille":"Braille","color-not-sole-means-of-conveying-information":"La couleur n'est pas la seule manière de communiquer de l'information","dyslexia-readability":"Lisibilité adapté aux publics dys","full-ruby-annotations":"Annotations complètes au format ruby (langues asiatiques)","high-contrast-between-foreground-and-background-audio":"Contraste sonore amélioré entre les différents plans","high-contrast-between-text-and-background":"Contraste élevé entre le texte et l'arrière-plan","large-print":"Grands caractères","page-breaks":{"compact":"Pagination identique à l'imprimé","descriptive":"Contient une pagination identique à la version imprimée"},"ruby-annotations":"Annotations partielles au format ruby (langues asiatiques)","sign-language":"Langue des signes","tactile-graphics":{"compact":"Graphiques tactiles","descriptive":"Des graphiques tactiles ont été intégrés pour faciliter l'accès des personnes aveugles aux éléments visuels"},"tactile-objects":"Objets 3D ou tactiles","text-to-speech-hinting":"Prononciation améliorée pour la synthèse vocale","title":"Informations complémentaires sur l'accessibilité","ultra-high-contrast-between-text-and-background":"Contraste très élevé entre le texte et l'arrière-plan","visible-page-numbering":"Numérotation de page visible","without-background-sounds":"Aucun bruit de fond"},"conformance":{"a":{"compact":"Cette publication répond aux règles minimales d'accessibilité","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau A"},"aa":{"compact":"Cette publication répond aux règles d'accessibilité reconnues","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau AA"},"aaa":{"compact":"Cette publication dépasse les règles d'accessibilité reconnues","descriptive":"La publication indique qu'elle respecte les règles d'accessibilité EPUB et WCAG 2 niveau AAA"},"certifier":"Accessibilité évaluée par ","certifier-credentials":"L'évaluateur est accrédité par ","details":{"certification-info":"Cette publication a été certifié le","certifier-report":"Pour plus d'information, veuillez consulter le rapport de certification","claim":"Cette publication indique respecter","epub-accessibility-1-0":"EPUB Accessibilité 1.0","epub-accessibility-1-1":"EPUB Accessibilité 1.1","level-a":"Niveau A","level-aa":"Niveau AA","level-aaa":"Niveau AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Règles pour l’accessibilité des contenus Web (WCAG) 2.2"}},"details-title":"Information détaillée","no":"Aucune information disponible","title":"Règles d'accessibilité","unknown-standard":"Aucune indication concernant les normes d'accessibilité"},"hazards":{"flashing":{"compact":"Flashs lumineux","descriptive":"La publication contient des flashs lumineux qui peuvent provoquer des crises d’épilepsie"},"flashing-none":{"compact":"Pas de flashs lumineux","descriptive":"La publication ne contient pas de flashs lumineux susceptibles de provoquer des crises d’épilepsie"},"flashing-unknown":{"compact":"Pas d'information concernant la présence de flashs lumineux","descriptive":"La présence de flashs lumineux susceptibles de provoquer des crises d’épilepsie n'a pas pu être déterminée"},"motion":{"compact":"Sensations de mouvement","descriptive":"La publication contient des images en mouvement qui peuvent provoquer des nausées, des vertiges et des maux de tête"},"motion-none":{"compact":"Pas de sensations de mouvement","descriptive":"La publication ne contient pas d'images en mouvement qui pourraient provoquer des nausées, des vertiges et des maux de tête"},"motion-unknown":{"compact":"Pas d'information concernant la présence d'images en mouvement","descriptive":"La présence d'images en mouvement susceptibles de provoquer des nausées, des vertiges et des maux de tête n'a pas pu être déterminée"},"no-metadata":"Aucune information disponible","none":{"compact":"Aucun points d'attention","descriptive":"La publication ne présente aucun risque lié à la présence de flashs lumineux, de sensations de mouvement ou de sons"},"sound":{"compact":"Sons","descriptive":"La publication contient des sons qui peuvent causer des troubles de la sensibilité"},"sound-none":{"compact":"Pas de risques sonores","descriptive":"La publication ne contient pas de sons susceptibles de provoquer des troubles de la sensibilité"},"sound-unknown":{"compact":"Pas d'information concernant la présence de sons","descriptive":"La présence de sons susceptibles de causer des troubles de sensibilité n'a pas pu être déterminée"},"title":"Points d'attention","unknown":"La présence de risques est inconnue"},"legal-considerations":{"exempt":{"compact":"Déclare être sous le coup d'une exemption dans certaines juridictions","descriptive":"Cette publication dééclare être sous le coup d'une exemption dans certaines juridictions"},"no-metadata":"Aucune information disponible","title":"Considérations légales"},"navigation":{"index":{"compact":"Index","descriptive":"Index comportant des liens vers les entrées référencées"},"no-metadata":"Aucune information disponible","page-navigation":{"compact":"Aller à la page","descriptive":"Permet d'accéder aux pages de la version source imprimée"},"structural":{"compact":"Titres","descriptive":"Contient des titres pour une navigation structurée"},"title":"Points de repère","toc":{"compact":"Table des matières","descriptive":"Table des matières"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Formules chimiques en LaTeX","descriptive":"Formules chimiques en format accessible (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Formules chimiques en MathML","descriptive":"Formules chimiques en format accessible (MathML)"},"accessible-math-as-latex":{"compact":"Mathématiques en LaTeX","descriptive":"Formules mathématiques en format accessible (LaTeX)"},"accessible-math-described":"Des descriptions textuelles des formules mathématiques sont fournies","closed-captions":{"compact":"Sous-titres disponibles pour les vidéos","descriptive":"Des sous titres sont disponibles pour les vidéos"},"extended-descriptions":"Les images porteuses d'informations complexes sont décrites par des descriptions longues","math-as-mathml":{"compact":"Mathématiques en MathML","descriptive":"Formules mathématiques en format accessible (MathML)"},"open-captions":{"compact":"Sous-titres incrustés","descriptive":"Des sous titres sont incrustés pour les vidéos"},"title":"Contenus spécifiques","transcript":"Transcriptions fournies","unknown":"Aucune information disponible"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Images décrites","descriptive":"Les images sont décrites par un texte"},"no-metadata":"Aucune information pour la lecture en voix de synthèse ou en braille","none":{"compact":"Non lisible en voix de synthèse ou en braille","descriptive":"Le contenu n'est pas lisible en voix de synthèse ou en braille"},"not-fully":{"compact":"Pas entièrement lisible en voix de synthèse ou en braille","descriptive":"Tous les contenus ne pourront pas être lus à haute voix ou en braille"},"readable":{"compact":"Entièrement lisible en voix de synthèse ou en braille","descriptive":"Tous les contenus peuvent être lus en voix de synthèse ou en braille"}},"prerecorded-audio":{"complementary":{"compact":"Clips audio préenregistrés","descriptive":"Des clips audio préenregistrés sont intégrés au contenu"},"no-metadata":"Aucune information sur les enregistrements audio","only":{"compact":"Audio préenregistré uniquement","descriptive":"Livre audio sans texte alternatif"},"synchronized":{"compact":"Audio préenregistré synchronisé avec du texte","descriptive":"Tous les contenus sont disponibles comme audio préenregistrés synchronisés avec le texte"}},"title":"Lisibilité","visual-adjustments":{"modifiable":{"compact":"L'affichage peut être adapté","descriptive":"L'apparence du texte et la mise en page peuvent être modifiées en fonction des capacités du système de lecture (famille et taille des polices, espaces entre les paragraphes, les phrases, les mots et les lettres, ainsi que la couleur de l'arrière-plan et du texte)"},"unknown":"Aucune information sur les possibilités d'adaptation de l'affichage","unmodifiable":{"compact":"L'affichage ne peut pas être adapté","descriptive":"Le texte et la mise en page ne peuvent pas être adaptés étant donné que l'expérience de lecture est proche de celle de la version imprimée, mais l'application de lecture peut tout de même proposer la capacité de zoomer"}}}}},"altIdentifier_many":"","altIdentifier_one":"identifiant alternatif","altIdentifier_other":"identifiants alternatifs","artist_many":"","artist_one":"artiste","artist_other":"artiste","author_many":"","author_one":"auteur","author_other":"auteurs","collection_many":"","collection_one":"collection éditoriale","collection_other":"collections éditoriales","colorist_many":"","colorist_one":"coloriste","colorist_other":"coloristes","contributor_many":"","contributor_one":"contributeur","contributor_other":"contributeurs","description":"description","duration":"durée","editor_many":"","editor_one":"éditeur","editor_other":"éditeurs","identifier_many":"","identifier_one":"identifiant","identifier_other":"identifiants","illustrator_many":"","illustrator_one":"illustrateur","illustrator_other":"illustrateurs","imprint_many":"","imprint_one":"marque éditoriale","imprint_other":"marques éditoriales","inker_many":"","inker_one":"encreur","inker_other":"encreurs","language_many":"","language_one":"langue","language_other":"langues","letterer_many":"","letterer_one":"lettreur","letterer_other":"lettreurs","modified":"date de modification","narrator_many":"","narrator_one":"narrateur","narrator_other":"narrateurs","numberOfPages":"pagination papier","penciler_many":"","penciler_one":"dessinateur","penciler_other":"dessinateurs","published":"date de publication","publisher_many":"","publisher_one":"éditeur","publisher_other":"éditeurs","series_many":"","series_one":"série","series_other":"séries","subject_many":"","subject_one":"catégorie","subject_other":"catégories","subtitle":"sous-titre","title":"titre","translator_many":"","translator_one":"traducteur","translator_other":"traducteurs"}}`),Wr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:qi},publication:qi},Symbol.toStringTag,{value:"Module"})),Ji={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"لا تتوفر أي معلومات","publisher-contact":"لمزيد من المعلومات حول إمكانية الوصول إلى هذا المنتج، يُرجى التواصل مع الناشر: ",title:"ملخص إمكانية الوصول"},"additional-accessibility-information":{aria:{compact:"أدوار ARIA مدرَجة",descriptive:"يتم تعزيز المحتوى باستخدام أدوار ARIA لتحسين التنظيم وتيسير التنقّل"},"audio-descriptions":"الوصف الصوتي",braille:"برايل","color-not-sole-means-of-conveying-information":"اللون ليس الوسيلة الوحيدة لنقل المعلومات","dyslexia-readability":"سهولة القراءة لذوي عُسر القراءة","full-ruby-annotations":"شروح روبي كاملة","high-contrast-between-foreground-and-background-audio":"تباين عالٍ بين الصوت الرئيسي وصوت الخلفية","high-contrast-between-text-and-background":"تباين عالٍ بين النص والخلفية","large-print":"خط كبير","page-breaks":{compact:"فواصل الصفحات متضمَّنة",descriptive:"فواصل الصفحات متضمَّنة من المصدر المطبوع الأصلي"},"ruby-annotations":"بعض شروح الروبي","sign-language":"لغة الإشارة","tactile-graphics":{compact:"الرسوم اللمسية مدرجة",descriptive:"تم دمج الرسوم اللمسية لتيسير الوصول إلى العناصر البصرية للأشخاص المكفوفين"},"tactile-objects":"مجسمات لمسية ثلاثية الأبعاد","text-to-speech-hinting":"إرشادات تحويل النص إلى كلام (TTS)متوفرة",title:"معلومات إضافية عن إمكانية الوصول","ultra-high-contrast-between-text-and-background":"تباين عالٍ جدًا بين النص والخلفية","visible-page-numbering":"ترقيم صفحات مرئي","without-background-sounds":"من دون أصوات في خلفية"},conformance:{a:{compact:"هذا المنشور يفي بالمعايير الدنيا لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى A من معيار WCAG 2"},aa:{compact:"هذا المنشور يفي بالمعايير المعتمدة لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى AA من معيار WCAG 2"},aaa:{compact:"هذا المنشور يفوق المعايير المقبولة لإمكانية الوصول",descriptive:"يحتوي هذا المنشور على بيان مطابقة يفيد بأنه يفي بمعيار إمكانية الوصول في EPUB وبمستوى AAA من معيار WCAG 2"},certifier:"تم اعتماد هذا المنشور من قبل ","certifier-credentials":"بيانات اعتماد جهة التصديق ",details:{"certification-info":"تم اعتماد هذا المنشور في تاريخ ","certifier-report":"لمزيد من المعلومات، يرجى الرجوع إلى تقرير جهة التصديق",claim:"يدّعي هذا المنشور أنه يستوفي","epub-accessibility-1-0":"معيار إمكانية الوصول لـ EPUB إصدار 1.0","epub-accessibility-1-1":"معيار إمكانية الوصول لـ EPUB إصدار 1.1","level-a":"المستوى A","level-aa":"المستوى AA","level-aaa":"المستوى AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"مبادئ النفاذ إلى محتوى الويب (WCAG) 2.2"}},"details-title":"معلومات تفصيلية عن مدى المطابقة",no:"لا تتوفر أي معلومات",title:"المطابقة","unknown-standard":"لا يمكن التأكد من مدى مطابقة هذا المنشور للمعايير المقبولة لإمكانية الوصول"},hazards:{flashing:{compact:"محتوى وامض",descriptive:"يحتوي هذا المنشور على محتوى وامض قد يسبب نوبات حساسة للضوء"},"flashing-none":{compact:"لا توجد مخاطر وميض",descriptive:"لا يحتوي هذا المنشور على محتوى وامض قد يسبب نوبات حساسة للضوء"},"flashing-unknown":{compact:"مخاطر الوميض غير معروفة",descriptive:"لم يُمكن التأكد من وجود محتوى وامض قد يسبب نوبات حساسية للضوء"},motion:{compact:"محاكاة الحركة",descriptive:"يحتوي المنشور على محاكاة حركة قد تسبّب دوار الحركة"},"motion-none":{compact:"لا توجد مخاطر محاكاة الحركة",descriptive:"لا يحتوي المنشور على محاكاة حركة قد تسبّب دوار الحركة"},"motion-unknown":{compact:"مخاطر محاكاة الحركة غير معروفة",descriptive:"تعذّر تحديد ما إذا كانت هناك محاكاة للحركة قد تُسبب دوار الحركة"},"no-metadata":"لا تتوفر أي معلومات",none:{compact:"لا توجد مخاطر",descriptive:"لا يحتوي المنشور على أي مخاطر"},sound:{compact:"أصوات",descriptive:"يحتوي المنشور على أصوات قد تؤدي إلى مشاكل حساسية صوتية"},"sound-none":{compact:"لا توجد مخاطر صوتية",descriptive:"لا يحتوي المنشور على أصوات قد تؤدي إلى مشاكل حساسية صوتية"},"sound-unknown":{compact:"مخاطر الصوت غير معروفة",descriptive:"تعذّر تحديد ما إذا كانت هناك أصوات قد تُسبب مشكلات في الحساسية"},title:"مخاطر",unknown:"وجود المخاطر غير معروف"},"legal-considerations":{exempt:{compact:"يُعلن عن استثناء من متطلبات إمكانية الوصول من بعض السلطات القضائية",descriptive:"يُصرّح هذا المنشور بوجود استثناء من متطلبات إمكانية الوصول من بعض السلطات القضائية"},"no-metadata":"لا تتوفر أي معلومات",title:"اعتبارات قانونية"},navigation:{index:{compact:"كشاف",descriptive:"كشاف يحتوي على روابط إلى الإدخالات المشار إليها"},"no-metadata":"لا تتوفر أي معلومات","page-navigation":{compact:"الانتقال إلى صفحة",descriptive:"قائمة الصفحات للانتقال إلى صفحات من النسخة المطبوعة الأصلية"},structural:{compact:"العناوين",descriptive:"عناصر مثل العناوين والجداول وغيرها للتنقل المنظّم"},title:"التنقل",toc:{compact:"جدول المحتويات",descriptive:"جدول المحتويات لكل فصول النص عبر روابط"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"الصيغ الكيميائية بصيغة LaTeX",descriptive:"الصيغ الكيميائية بشكل ميسر (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"الصيغ الكيميائية بصيغة MathML",descriptive:"الصيغ الكيميائية بشكل ميسر (MathML)"},"accessible-math-as-latex":{compact:"الرياضيات بصيغة LaTeX",descriptive:"الصيغ الرياضية بشكل ميسر (LaTeX)"},"accessible-math-described":"تتوفر أوصاف نصية للصيغ الرياضية","closed-captions":{compact:"تحتوي الفيديوهات على شروح مغلقة",descriptive:"الفيديوهات الموجودة في المنشورات تحتوي على شروح مغلقة"},"extended-descriptions":"يتم وصف الصور الغنية بالمعلومات بأوصاف مفصّلة","math-as-mathml":{compact:"الرياضيات بصيغة MathML",descriptive:"الصيغ الرياضية بشكل ميسر(MathML)"},"open-captions":{compact:"تحتوي الفيديوهات على شروح مدمجة",descriptive:"الفيديوهات الموجودة في المنشورات تحتوي على شروح مدمجة"},title:"محتوى غني",transcript:"يتوفر نص(نصوص)",unknown:"لا تتوفر أي معلومات"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"يحتوي على نص بديل",descriptive:"يحتوي على أوصاف نصية بديلة للصور"},"no-metadata":"لا تتوفر معلومات عن القراءة غير البصرية",none:{compact:"غير قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"المحتوى غير قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية"},"not-fully":{compact:"غير قابل للقراءة بالكامل بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"لن يكون كل المحتوى قابلًا للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية"},readable:{compact:"قابل للقراءة بصوتٍ عالٍ أو بطريقة برايل الديناميكية",descriptive:"يمكن قراءة كل المحتوى بصوتٍ عالٍ أو بطريقة برايل الديناميكية"}},"prerecorded-audio":{complementary:{compact:"مقاطع الصوت المسجّلة مسبقًا",descriptive:"مقاطع الصوت المسجّلة مسبقًا مدمجة في المحتوى"},"no-metadata":"لا توجد معلومات عن الصوت المسجّل مسبقًا",only:{compact:"الصوت المسجّل مسبقًا فقط",descriptive:"كتاب صوتي بدون بديل نصي"},synchronized:{compact:"صوت مسجّل مسبقًا متزامن مع النص",descriptive:"كل المحتوى متوفر كصوت مسجّل مسبقًا متزامن مع النص"}},title:"طرق القراءة","visual-adjustments":{modifiable:{compact:"يمكن تعديل المظهر",descriptive:"يمكن تعديل مظهر النص وتخطيط الصفحة وفقاً لإمكانات نظام القراءة (اسم الخط وحجمه، والمسافات بين الفقرات والجمل والكلمات والأحرف، بالإضافة إلى لون الخلفية والنص)"},unknown:"لا توجد معلومات عن إمكانية تعديل المظهر",unmodifiable:{compact:"لا يمكن تعديل المظهر",descriptive:"لا يمكن تعديل مظهر النص وتخطيط الصفحات لأن تجربة القراءة قريبة من النسخة المطبوعة، ولكن تطبيقات القراءة ما زالت تتيح خيارات التكبير"}}}}},altIdentifier_one:"رمز تعريفي بديل",altIdentifier_other:"رموز تعريفية بديلة",artist_one:"فنان",artist_other:"فنانون",author_one:"مؤلف",author_other:"مؤلفون",collection_one:"سلسلة تحريرية",collection_other:"سلاسل تحريرية",colorist_one:"ملوّن الألوان",colorist_other:"ملوّنو الألوان",contributor_one:"مساهم",contributor_other:"مساهمون",description:"وصف",duration:"مدة",editor_one:"محرر",editor_other:"محررون",identifier_one:"رمز تعريفي",identifier_other:"رموز تعريفية",illustrator_one:"رسًام",illustrator_other:"رسامون",imprint_one:"العلامة التجارية للنشر",imprint_other:"العلامات التجارية للنشر",inker_one:"مُحَبِّر",inker_other:"مُحَبِّرون",language_one:"اللغة",language_other:"اللغات",letterer_one:"خطّاط",letterer_other:"خطّاطون",modified:"تاريخ التعديل",narrator_one:"قارئ صوتي",narrator_other:"قرّاء صوتيون",numberOfPages:"عدد الصفحات في النسخة المطبوعة",penciler_one:"رسّام أولي",penciler_other:"رسّامون أوّليون",published:"تاريخ النشر",publisher_one:"ناشر",publisher_other:"ناشرون",series_one:"سلسلة",series_other:"سلاسل",subject_one:"موضوع",subject_other:"مواضيع",subtitle:"عنوان فرعي",title:"العنوان",translator_one:"مترجم",translator_other:"مترجمون"}},Br=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Ji},publication:Ji},Symbol.toStringTag,{value:"Module"})),Zi={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Ingen information tilgængelig","publisher-contact":"For mere information om tilgængeligheden af denne bog, kontakt venligst udgiveren: ",title:"Tilgængeligheds-oversigt"},"additional-accessibility-information":{aria:{compact:"Indeholder ARIA roller",descriptive:"Indhold forbedres med ARIA-roller for at optimere organisering og gøre navigation lettere"},"audio-descriptions":"Lydbeskrivelser",braille:"Punktskrift (braille)","color-not-sole-means-of-conveying-information":"Information gives ikke udelukkende via farver","dyslexia-readability":"Læsbarhed for ordblinde","full-ruby-annotations":'Indeholder såkalde "ruby" notationer (til asiatiske sprog)',"high-contrast-between-foreground-and-background-audio":"Høj kontrast imellem forgrunds- og baggrunds-lyd","high-contrast-between-text-and-background":"Høj kontrast imellem tekst og baggrunden","large-print":"Forstørret tekst","page-breaks":{compact:"Indeholder sideskift",descriptive:"Indeholder sideskift fra den trykte version af bogen"},"ruby-annotations":'Nogle "ruby" annotationer (til asiatiske sprog)',"sign-language":"Tegnsprog","tactile-graphics":{compact:"Indeholder taktil grafik",descriptive:"Indeholder taktil grafik for at muliggøre adgang til visuel information for blinde"},"tactile-objects":"Taktile 3D objekter","text-to-speech-hinting":"Udtaleforbedringer til syntetisk tale",title:"Yderligere information om tilgængelighed","ultra-high-contrast-between-text-and-background":"Ultra høj kontrast imellem tekst og baggrund","visible-page-numbering":"Synlige sidenumre","without-background-sounds":"Uden baggrundslyd"},conformance:{a:{compact:"Denne bog overholder minimum-tilgængelighedskravene",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau A"},aa:{compact:"Denne bog lever op til de accepterede tilgængelighedskrav",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau AA"},aaa:{compact:"Denne bog mere end opfylder de accepterede tilgængelighedskrav",descriptive:"Denne bog en overensstemmelseserklæring om, at den opfylder EPUB Tilgængelighedskrav og WCAG 2 standarden på niveau AAA"},certifier:"Denne bog blev certificeret af ","certifier-credentials":"Certificeringsorganets legitimationsoplysninger er ",details:{"certification-info":"Bogen blev certificeret den ","certifier-report":"Se certificeringsorganets rapport for mere information",claim:"Denne bog hævder at opfylde","epub-accessibility-1-0":"EPUB Tilgængelighed 1.0","epub-accessibility-1-1":"EPUB Tilgængelighed 1.1","level-a":"Niveau A","level-aa":"Niveau AA","level-aaa":"Niveau AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Retningslinjer for tilgængeligt webindhold (WCAG) 2.2"}},"details-title":"Detaljeret overholdelses-information",no:"Ingen information tilgængelig",title:"Overholdelse","unknown-standard":"Overholdelse af de accepterede tilgængelighedskrav kan ikke vurderes for denne bog"},hazards:{flashing:{compact:"Blinkende indhold",descriptive:"Bogen indeholder blinkende indhold der kan forårsage epileptiske anfald"},"flashing-none":{compact:"Ingen blinkende indhold",descriptive:"Bogen indeholder ikke noget blinkende indhold, der kunne forårsage epileptiske anfald"},"flashing-unknown":{compact:"Ingen information om bogen har blinkende indhold",descriptive:"Det kunne ikke afgøres om bogen indeholder blinkende indhold der kan lede til epileptiske anfald"},motion:{compact:"Simuleret bevægelse",descriptive:"Bogen indeholder simuleret bevægelse, der kan forårsage en følelse af køresyge"},"motion-none":{compact:"Indeholder ikke simuleret bevægelse",descriptive:"Denne bog indeholder ikke noget indhold med simuleret bevægelse, der kunne lede til en følelse af køresyge"},"motion-unknown":{compact:"Ingen information om simuleret bevægelse",descriptive:"Det kunne ikke vurderes om bogen indeholder simuleret bevægelse, der kan lede til en følelse af køresyge"},"no-metadata":"Ingen information tilgængelig",none:{compact:"Ingen farer",descriptive:"Bogen indeholder ikke noget indhold der kategoriseres som farligt"},sound:{compact:"Lyde",descriptive:"Bogen indeholder lyde der kan være ubehagelige hvis man er sensitiv overfor lyde"},"sound-none":{compact:"Ingen ubehagelige lyde",descriptive:"Bogen indeholder ikke lyde der kunne opleves som ubehagelige hvis man er sensitiv overfor lyde"},"sound-unknown":{compact:"Ingen information om ubehagelige lyde",descriptive:"Det kunne ikke afgøres om bogen indeholder ubehagelige lyde"},title:"Farer",unknown:"Ingen information om farligt indhold"},"legal-considerations":{exempt:{compact:"Gør krav på undtagelser fra tilgængelighedskrav",descriptive:"Denne bog gør krav på en tilgængelighedsundtagelse i en eller flere jurisdiktioner"},"no-metadata":"Ingen information tilgængelig",title:"Juridiske overvejelser"},navigation:{index:{compact:"Indholdsfortegnelse",descriptive:"Indholdsfortegnelse med links til referencer"},"no-metadata":"Ingen information tilgængelig","page-navigation":{compact:"Gå til side",descriptive:"Sideliste for at gå til sider fra den trykte kildeversion"},structural:{compact:"Overskrifter",descriptive:"Elementer så som overskrifter og tabeller til struktureret navigation"},title:"Navigation",toc:{compact:"Indholdsfortegnelse",descriptive:"Indholdsfortegnelse med links til alle kapitler"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Kemiske formularer i LaTeX",descriptive:"Kemiske formularer i tilgængeligt format (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Kemiske formularer i MathML notation",descriptive:"Kemiske formularer i tilgængeligt format (MathML)"},"accessible-math-as-latex":{compact:"Matematik som LaTeX",descriptive:"Matematikformler i tilgængeligt format (LaTeX)"},"accessible-math-described":"Tekstbeskrivelser til matematiske formler","closed-captions":{compact:"Videoer har undertekster",descriptive:"Videoer der optræder i bogen har undertekster"},"extended-descriptions":"Informationsrige billeder beskrives med udvidede beskrivelser","math-as-mathml":{compact:"Matematik som MathML",descriptive:"Matematiske formler i tilgængeligt format (MathML)"},"open-captions":{compact:"Videoer har indlejrede undertekster",descriptive:"Videoer der optræder i bogen har indlejrede undertekster"},title:"Komplekst indhold",transcript:"Indeholder transskription(er)",unknown:"Ingen information tilgængelig"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Har alternativ tekst",descriptive:"Har billedbeskrivelser"},"no-metadata":"Ingen information omkring ikke-visuel læsning",none:{compact:"Ikke læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Dette indhold er ikke læsbart med oplæsning eller dynamisk punktskrift"},"not-fully":{compact:"Ikke fuldt læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Alt indholdet er ikke fuldt læsbart med oplæsning eller dynamisk punktskrift"},readable:{compact:"Læsbar med oplæsning eller dynamisk punktskrift",descriptive:"Alt indholdet er læsbart med oplæsning eller dynamisk punktskrift"}},"prerecorded-audio":{complementary:{compact:"Indlæste lydklip",descriptive:"Indlæste lydklip er indlejret i indholdet"},"no-metadata":"Ingen information om indlæst lyd",only:{compact:"Kun indlæst lyd",descriptive:"Lydbog uden tekst alternativer"},synchronized:{compact:"Indlæst lyd med synkroniseret tekst",descriptive:"Alt indholdet er tilgængeligt med indlæst lyd og synkroniseret tekst"}},title:"Læseformer","visual-adjustments":{modifiable:{compact:"Udseende kan ændres",descriptive:"Udseende af tekst og sidelayout kan ændres, så vidt muligt i læsesystemet (skrifttype, skriftstørrelse, afstand mellem afsnit, sætninger, ord og bogstaver, samt farven på tekst og baggrund)"},unknown:"Ingen information om mulighed for ændring af udseende",unmodifiable:{compact:"Udseende kan ikke ændres",descriptive:"Tekst og sidelayout kan ikke ændres, da læseoplevelsen afspejler den trykte version af materialet. Læsesystemet kan dog stadig give mulighed for zoom"}}}}},altIdentifier_one:"alternativt ID",altIdentifier_other:"alternative ID'er",artist_one:"kunstner",artist_other:"kunstnere",author_one:"forfatter",author_other:"forfattere",collection_one:"redaktionel samling",collection_other:"redaktionelle samlinger",colorist_one:"farvelægger",colorist_other:"farvelæggere",contributor_one:"bidragsyder",contributor_other:"bidragsydere",description:"beskrivelse",duration:"varighed",editor_one:"redaktør",editor_other:"redaktører",identifier_one:"ID",identifier_other:"ID'er",illustrator_one:"illustrator",illustrator_other:"illustratorer",imprint_one:"trykkeri",imprint_other:"trykkerier",inker_one:"tegner",inker_other:"tegnere",language_one:"sprog",language_other:"sprog",letterer_one:"taleboble-forfatter",letterer_other:"taleboble-forfattere",modified:"rettet dato",narrator_one:"indlæser",narrator_other:"indlæsere",numberOfPages:"printbare sider",penciler_one:"tegneseriekunstner",penciler_other:"tegneseriekunstnere",published:"udgivelsesdato",publisher_one:"udgiver",publisher_other:"udgivere",series_one:"serie",series_other:"serier",subject_one:"emne",subject_other:"emner",subtitle:"undertitel",title:"titel",translator_one:"oversætter",translator_other:"oversættere"}},jr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Zi},publication:Zi},Symbol.toStringTag,{value:"Module"})),Qi=JSON.parse(`{"format":{"audiobook":"Audiolibro","audiobookJSON":"Audiobook Manifest","cbz":"Comic book archive","divina":"Divina Publication","divinaJSON":"Divina Publication Manifest","epub":"EPUB","lcpa":"Audiolibro protetto con LCP","lcpdf":"PDF protetto con LCP","lcpl":"Licenza LCP","pdf":"PDF","rwp":"Readium Web Publication","rwpm":"Readium Web Publication Manifest","zab":"Audiobook Archive","zip":"ZIP Archive"},"kind":{"audiobook_many":"audiolibri","audiobook_one":"audiolibro","audiobook_other":"audiolibri","book_many":"libri","book_one":"libro","book_other":"libri","comic_many":"fumetti","comic_one":"fumetto","comic_other":"fumetti","document_many":"documenti","document_one":"documento","document_other":"documenti"},"metadata":{"accessibility":{"display-guide":{"accessibility-summary":{"no-metadata":"Nessuna informazione disponibile","publisher-contact":"Per ulteriori informazioni sull'accessibilità di questa risorsa, contattare l'editore: ","title":"Informazioni aggiuntive sull'accessibilità fornite dall'editore"},"additional-accessibility-information":{"aria":{"compact":"Ruoli ARIA inclusi","descriptive":"Il contenuto è semanticamente arricchito con ruoli ARIA per ottimizzare l'organizzazione e facilitare la navigazione"},"audio-descriptions":"Descrizioni audio","braille":"Braille","color-not-sole-means-of-conveying-information":"Il colore non è l'unico mezzo per trasmettere informazioni","dyslexia-readability":"Leggibilità adatta alla dislessia","full-ruby-annotations":"Annotazioni complete in Ruby","high-contrast-between-foreground-and-background-audio":"Elevato contrasto tra audio principale e sottofondo","high-contrast-between-text-and-background":"Contrasto elevato tra testo in primo piano e sfondo","large-print":"Stampa a caratteri ingranditi","page-breaks":{"compact":"Interruzioni di pagina incluse","descriptive":"Interruzioni di pagina identiche alla versione originale a stampa"},"ruby-annotations":"Alcune annotazioni in Ruby","sign-language":"Lingua dei segni","tactile-graphics":{"compact":"Grafica tattile inclusa","descriptive":"La grafica tattile è stata integrata per facilitare l'accesso agli elementi visivi alle persone non vedenti"},"tactile-objects":"Oggetti 3D tattili","text-to-speech-hinting":"Pronuncia migliorata per la sintesi vocale","title":"Ulteriori informazioni sull'accessibilità","ultra-high-contrast-between-text-and-background":"Contrasto molto elevato tra testo e sfondo","visible-page-numbering":"Numerazione delle pagine visibile","without-background-sounds":"Nessun suono in sottofondo"},"conformance":{"a":{"compact":"Questa pubblicazione soddisfa gli standard minimi di accessibilità","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello A"},"aa":{"compact":"Questa pubblicazione soddisfa gli standard di accessibilità accettati","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello AAA"},"aaa":{"compact":"Questa pubblicazione supera gli standard di accessibilità","descriptive":"La pubblicazione contiene una dichiarazione di conformità che attesta il rispetto degli standard EPUB Accessibility e WCAG 2 Livello AAA"},"certifier":"La pubblicazione è stata certificata da ","certifier-credentials":"Le credenziali del certificatore sono ","details":{"certification-info":"La pubblicazione è stata certificata il ","certifier-report":"Per ulteriori informazioni, consultare il report di accessibilità del certificatore","claim":"Questa pubblicazione è conforme ai requisiti di","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Livello A","level-aa":"Livello AA","level-aaa":"Livello AAA","wcag-2-0":{"compact":"WCAG 2.0","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.0"},"wcag-2-1":{"compact":"WCAG 2.1","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.1"},"wcag-2-2":{"compact":"WCAG 2.2","descriptive":"Linee guida per l'accessibilità dei contenuti web (WCAG) 2.2"}},"details-title":"Informazioni dettagliate sulla conformità","no":"Nessuna informazione disponibile","title":"Conformità","unknown-standard":"Nessuna indicazione sugli standard d'accessibilità"},"hazards":{"flashing":{"compact":"Contenuto lampeggiante","descriptive":"La pubblicazione contiene contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"flashing-none":{"compact":"Nessun contenuto lampeggiante","descriptive":"La pubblicazione non presenta contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"flashing-unknown":{"compact":"Nessuna informazione sulla presenza di contenuti lampeggianti","descriptive":"Non è stato possibile determinare la presenza di contenuti lampeggianti che possono causare crisi d'epilessia fotosensibile"},"motion":{"compact":"Simulazione del movimento","descriptive":"La pubblicazione contiene simulazioni di movimento che possono provocare cinetosi"},"motion-none":{"compact":"Nessun rischio di simulazione del movimento","descriptive":"La pubblicazione non contiene simulazioni di movimento che possono causare la malattia di movimento"},"motion-unknown":{"compact":"Nessuna informazione relativa alla presenza di simulazioni di movimento","descriptive":"Non è stato possibile determinare la presenza di contenuti che possono provocare cinetosi"},"no-metadata":"Nessuna informazione disponibile","none":{"compact":"Nessuna problematica","descriptive":"La pubblicazione non presenta contenuti a rischio di simulazione di movimento, di suoni, o di contenuti lampeggianti"},"sound":{"compact":"Suoni","descriptive":"La pubblicazione contiene suoni che possono causare problemi di sensibilità"},"sound-none":{"compact":"Nessun rischio acustico","descriptive":"La pubblicazione non contiene suoni che possono causare problemi di sensibilità"},"sound-unknown":{"compact":"Nessuna informazione sulla presenza di suoni","descriptive":"Non è stato possibile determinare la presenza di suoni che potrebbero causare problemi di sensibilità"},"title":"Problematiche","unknown":"La presenza di rischi è sconosciuta"},"legal-considerations":{"exempt":{"compact":"Dichiara di godere dell'esenzione d'accessibilità in alcune giurisdizioni","descriptive":"Questa risorsa gode dell'esenzione d'accessibilità in alcune giurisdizioni"},"no-metadata":"Nessuna informazione disponibile","title":"Note legali"},"navigation":{"index":{"compact":"Indice analitico interattivo","descriptive":"Indice analitico con link alle voci di riferimento"},"no-metadata":"Nessuna informazione disponibile","page-navigation":{"compact":"Vai alla pagina","descriptive":"Sono presenti i riferimenti ai numeri di pagina della versione a stampa corrispondente"},"structural":{"compact":"Intestazioni","descriptive":"Contiene elementi come titoli, elenchi e tabelle per permettere una navigazione strutturata"},"title":"Navigazione","toc":{"compact":"Indice interattivo","descriptive":"L’indice permette l’accesso diretto a tutti i capitoli tramite link"}},"rich-content":{"accessible-chemistry-as-latex":{"compact":"Formule chimiche in LaTeX","descriptive":"Formule chimiche in formato accessibile (LaTeX)"},"accessible-chemistry-as-mathml":{"compact":"Formule chimiche in MathML","descriptive":"Formule chimiche in formato accessibile (MathML)"},"accessible-math-as-latex":{"compact":"Matematica in LaTeX","descriptive":"Formule matematiche in formato accessibile (LaTeX)"},"accessible-math-described":"Sono disponibili descrizioni testuali per le formule matematiche","closed-captions":{"compact":"Sottotitoli disponibili per i video","descriptive":"Per i video sono disponibili dei sottotitoli"},"extended-descriptions":"Le immagini complesse presentano descrizioni estese","math-as-mathml":{"compact":"Matematica in MathML","descriptive":"Formule matematiche in formato accessibile (MathML)"},"open-captions":{"compact":"I video hanno i sottotitoli","descriptive":"I video inclusi nella pubblicazione hanno i sottotitoli"},"title":"Contenuti arricchiti","transcript":"Trascrizioni fornite","unknown":"Nessuna informazione disponibile"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{"compact":"Immagini descritte","descriptive":"Le immagini sono descritte da un testo"},"no-metadata":"Nessuna informazione sulla lettura non visiva","none":{"compact":"Non leggibile con lettura ad alta voce o in braille","descriptive":"Il contenuto non è leggibile con la lettura ad alta voce o in braille"},"not-fully":{"compact":"Non è interamente leggibile con lettura ad alta voce o in braille","descriptive":"Non tutti i contenuti potranno essere letti con lettura ad alta voce o in braille"},"readable":{"compact":"Interamente leggibile con lettura ad alta voce o in braille","descriptive":"Tutti i contenuti possono essere letti con la lettura ad alta voce o con il display braille"}},"prerecorded-audio":{"complementary":{"compact":"Clip audio preregistrate","descriptive":"Le clip audio preregistrate sono integrate nel contenuto"},"no-metadata":"Non sono disponibili informazioni sull'audio preregistrato","only":{"compact":"Solo audio preregistrato","descriptive":"Audiolibro senza testi alternativi"},"synchronized":{"compact":"Audio preregistrato sincronizzato con il testo","descriptive":"Tutti i contenuti sono disponibili come audio preregistrato sincronizzato con il testo"}},"title":"Leggibilità","visual-adjustments":{"modifiable":{"compact":"La formattazione del testo e il layout della pagina possono essere modificati","descriptive":"La formattazione del testo e il layout della pagina possono essere modificati in base alle funzionalità presenti nella soluzione di lettura (ingrandimento dei caratteri del testo, modifica dei colori e dei contrasti per il testo e lo sfondo, modifica degli spazi tra lettere, parole, frasi e paragrafi)"},"unknown":"Non sono disponibili informazioni sulla possibilità di formattare il testo","unmodifiable":{"compact":"La formattazione del testo e il display della pagina non possono essere modificati","descriptive":"Il layout di testo e pagina non può essere modificato poiché l'esperienza di lettura è vicina a una versione di stampa, ma i sistemi di lettura possono ancora fornire opzioni di zoom"}}}}},"altIdentifier_many":"identificatori alternativi","altIdentifier_one":"identificatore alternativo","altIdentifier_other":"identificatori alternativi","artist_many":"","artist_one":"artista","artist_other":"artisti","author_many":"","author_one":"autore","author_other":"autori","collection_many":"","collection_one":"collana","collection_other":"collane","colorist_many":"","colorist_one":"colorista","colorist_other":"coloristi","contributor_many":"","contributor_one":"contributore","contributor_other":"contributori","description":"descrizione","duration":"durata","editor_many":"","editor_one":"editor","editor_other":"editori","identifier_many":"identificatori","identifier_one":"identificatore","identifier_other":"identificatori","illustrator_many":"","illustrator_one":"illustratore","illustrator_other":"illustratori","imprint_many":"","imprint_one":"marca editoriale","imprint_other":"marche editoriali","inker_many":"","inker_one":"inchiostratore","inker_other":"inchiostratori","language_many":"","language_one":"lingua","language_other":"lingue","letterer_many":"letteristi","letterer_one":"letterista","letterer_other":"letteristi","modified":"Data di modifica","narrator_many":"","narrator_one":"narratore","narrator_other":"narratori","numberOfPages":"impaginazione versione cartacea","penciler_many":"","penciler_one":"disegnatore","penciler_other":"disegnatori","published":"Data di pubblicazione","publisher_many":"","publisher_one":"editore","publisher_other":"editori","series_many":"","series_one":"serie","series_other":"serie","subject_many":"","subject_one":"categoria","subject_other":"categorie","subtitle":"sottotitolo","title":"titolo","translator_many":"","translator_one":"traduttore","translator_other":"traduttori"}}`),Gr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Qi},publication:Qi},Symbol.toStringTag,{value:"Module"})),eo={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Sem informação disponível","publisher-contact":"Para mais informações sobre a acessibilidade deste produto, contacte a editora: ",title:"Resumo de acessibilidade"},"additional-accessibility-information":{aria:{compact:"Inclui funções ARIA",descriptive:"O conteúdo foi otimizado com funções ARIA para melhorar a organização e facilitar a navegação"},"audio-descriptions":"Descrições em áudio",braille:"Braille","color-not-sole-means-of-conveying-information":"A cor não é o único meio de transmitir informação","dyslexia-readability":"Otimizado para dislexia","full-ruby-annotations":"Anotações Ruby completas","high-contrast-between-foreground-and-background-audio":"Alto contraste entre som principal e fundo","high-contrast-between-text-and-background":"Alto contraste entre texto e fundo","large-print":"Impressão ampliada","page-breaks":{compact:"Inclui quebras de página",descriptive:"Inclui quebras de página da fonte impressa original"},"ruby-annotations":"Algumas anotações Ruby","sign-language":"Língua gestual","tactile-graphics":{compact:"Inclui gráficos táteis",descriptive:"Inclui gráficos táteis que facilitam o acesso a elementos visuais para pessoas cegas"},"tactile-objects":"Objetos táteis 3D","text-to-speech-hinting":"Sugestões para leitura em voz alta",title:"Informação adicional de acessibilidade","ultra-high-contrast-between-text-and-background":"Contraste muito elevado entre texto e fundo","visible-page-numbering":"Numeração de páginas visível","without-background-sounds":"Sem sons de fundo"},conformance:{a:{compact:"Cumpre as normas mínimas de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível A"},aa:{compact:"Cumpre as normas aceites de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível AA"},aaa:{compact:"Excede as normas aceites de acessibilidade",descriptive:"A publicação contém uma declaração de conformidade que indica que cumpre o padrão EPUB Accessibility e WCAG 2 nível AAA"},certifier:"A publicação foi certificada por ","certifier-credentials":"As credenciais do certificador são ",details:{"certification-info":"A publicação foi certificada em ","certifier-report":"Para mais informações, consulte o relatório do certificador",claim:"Esta publicação declara conformidade com","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"Nível A","level-aa":"Nível AA","level-aaa":"Nível AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Diretrizes de Acessibilidade para Conteúdo Web (WCAG) 2.2"}},"details-title":"Detalhes de conformidade",no:"Sem informação disponível",title:"Conformidade","unknown-standard":"Não foi possível determinar a conformidade com as normas de acessibilidade aceites para esta publicação"},hazards:{flashing:{compact:"Conteúdo intermitente",descriptive:"A publicação contém conteúdo intermitente que pode causar crises fotossensíveis"},"flashing-none":{compact:"Sem perigos de intermitência",descriptive:"A publicação não contém conteúdo intermitente que possa causar crises fotossensíveis"},"flashing-unknown":{compact:"Risco de intermitência desconhecido",descriptive:"Não foi possível determinar se existe conteúdo intermitente que possa causar crises fotossensíveis"},motion:{compact:"Simulação de movimento",descriptive:"A publicação contém simulações de movimento que podem causar enjoo"},"motion-none":{compact:"Sem simulação de movimento",descriptive:"A publicação não contém simulações de movimento que possam causar enjoo"},"motion-unknown":{compact:"Risco de movimento desconhecido",descriptive:"Não foi possível determinar se existem simulações de movimento que possam causar enjoo"},"no-metadata":"Sem informação disponível",none:{compact:"Sem perigos",descriptive:"A publicação não contém perigos conhecidos"},sound:{compact:"Sons sensíveis",descriptive:"A publicação contém sons que podem causar sensibilidade auditiva"},"sound-none":{compact:"Sem perigos sonoros",descriptive:"A publicação não contém sons que possam causar sensibilidade auditiva"},"sound-unknown":{compact:"Risco sonoro desconhecido",descriptive:"Não foi possível determinar se a publicação contém sons que possam causar sensibilidade auditiva"},title:"Perigos",unknown:"Presença de perigos não determinada"},"legal-considerations":{exempt:{compact:"Declara isenção de conformidade em algumas jurisdições",descriptive:"Esta publicação declara isenção de conformidade em algumas jurisdições"},"no-metadata":"Sem informação disponível",title:"Considerações legais"},navigation:{index:{compact:"Índice remissivo",descriptive:"Índice com ligações para entradas referenciadas"},"no-metadata":"Sem informação disponível","page-navigation":{compact:"Ir para página",descriptive:"Lista de páginas que permite aceder às páginas da versão impressa original"},structural:{compact:"Títulos e estrutura",descriptive:"Elementos como títulos, tabelas, etc., para navegação estruturada"},title:"Navegação",toc:{compact:"Índice",descriptive:"Índice de conteúdos com ligações para todos os capítulos do texto"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Fórmulas químicas em LaTeX",descriptive:"Fórmulas químicas em formato acessível (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Fórmulas químicas em MathML",descriptive:"Fórmulas químicas em formato acessível (MathML)"},"accessible-math-as-latex":{compact:"Matemática em LaTeX",descriptive:"Fórmulas matemáticas em formato acessível (LaTeX)"},"accessible-math-described":"Descrição textual das fórmulas matemáticas","closed-captions":{compact:"Vídeos com legendas ocultas",descriptive:"Os vídeos incluídos na publicação têm legendas ocultas"},"extended-descriptions":"Imagens complexas com descrições detalhadas","math-as-mathml":{compact:"Matemática em MathML",descriptive:"Fórmulas matemáticas em formato acessível (MathML)"},"open-captions":{compact:"Vídeos com legendas abertas",descriptive:"Os vídeos incluídos na publicação têm legendas abertas"},title:"Conteúdo rico",transcript:"Transcrição fornecida",unknown:"Sem informação disponível"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Contém texto alternativo",descriptive:"Inclui descrições alternativas de texto para imagens"},"no-metadata":"Sem informação sobre leitura não visual",none:{compact:"Não legível em leitura em voz alta ou braille dinâmico",descriptive:"O conteúdo não é legível em voz alta ou através de braille dinâmico"},"not-fully":{compact:"Parcialmente legível em leitura em voz alta ou braille dinâmico",descriptive:"Nem todo o conteúdo é legível em voz alta ou através de braille dinâmico"},readable:{compact:"Totalmente legível em leitura em voz alta ou braille dinâmico",descriptive:"Todo o conteúdo pode ser lido em voz alta ou através de braille dinâmico"}},"prerecorded-audio":{complementary:{compact:"Contém clipes de áudio pré-gravados",descriptive:"O conteúdo contém clipes de áudio pré-gravados incorporados"},"no-metadata":"Sem informação sobre áudio pré-gravado",only:{compact:"Apenas áudio pré-gravado",descriptive:"A publicação é apenas áudio e não possui alternativa em texto"},synchronized:{compact:"Áudio pré-gravado sincronizado com texto",descriptive:"Todo o conteúdo está disponível como áudio pré-gravado sincronizado com texto"}},title:"Formas de leitura","visual-adjustments":{modifiable:{compact:"Aspeto personalizável",descriptive:"O aspeto do texto e o layout da página podem ser modificados de acordo com as capacidades do sistema de leitura (tipo e tamanho de letra, espaçamento entre parágrafos, frases, palavras e letras, bem como a cor de fundo e do texto)"},unknown:"Sem informação sobre personalização do aspeto",unmodifiable:{compact:"Aspeto não ajustável",descriptive:"O texto e o layout da página não podem ser modificados, uma vez que a experiência de leitura é semelhante à versão impressa, mas os sistemas de leitura ainda podem oferecer opções de ampliação"}}}}},altIdentifier_one:"identificador alternativo",altIdentifier_other:"identificadores alternativos",artist_one:"artista",artist_other:"artistas",author_one:"autor",author_other:"autores",collection_one:"coleção",collection_other:"coleções",colorist_one:"colorista",colorist_other:"coloristas",contributor_one:"colaborador",contributor_other:"colaboradores",description:"descrição",duration:"duração",editor_one:"editor",editor_other:"editores",identifier_one:"identificador",identifier_other:"identificadores",illustrator_one:"ilustrador",illustrator_other:"ilustradores",imprint_one:"selo editorial",imprint_other:"selos editoriais",inker_one:"arte-finalista",inker_other:"arte-finalistas",language_one:"idioma",language_other:"idiomas",letterer_one:"letrista",letterer_other:"letristas",modified:"data de modificação",narrator_one:"narrador",narrator_other:"narradores",numberOfPages:"número de páginas",penciler_one:"desenhador",penciler_other:"desenhadores",published:"data de publicação",publisher_one:"editora",publisher_other:"editoras",series_one:"série",series_other:"séries",subject_one:"tema",subject_other:"temas",subtitle:"subtítulo",title:"título",translator_one:"tradutor",translator_other:"tradutores"}},Vr=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:eo},publication:eo},Symbol.toStringTag,{value:"Module"})),to={metadata:{accessibility:{"display-guide":{"accessibility-summary":{"no-metadata":"Information saknas","publisher-contact":"För mer information om den här publikationens tillgänglighet, kontakta utgivaren: ",title:"Kompletterande information om tillgänglighet"},"additional-accessibility-information":{aria:{compact:"Innehåller ARIA-roller",descriptive:"Innehållet har försetts med ARIA-roller för att tydliggöra strukturen och underlätta navigering"},"audio-descriptions":"Syntolkning",braille:"Punktskrift","color-not-sole-means-of-conveying-information":"Betydelse uttrycks aldrig enbart med färg","dyslexia-readability":"Förbättrad läsbarhet för personer med dyslexi","full-ruby-annotations":"Fullständig ruby-annotering","high-contrast-between-foreground-and-background-audio":"Hög kontrast mellan förgrundsljud och bakgrundsljud","high-contrast-between-text-and-background":"Hög kontrast mellan text och bakgrund","large-print":"Storstil","page-breaks":{compact:"Innehåller sidnummer",descriptive:"Innehåller sidnummer från tryckt förlaga"},"ruby-annotations":"Viss ruby-annotering","sign-language":"Teckenspråk","tactile-graphics":{compact:"Innehåller taktila bilder",descriptive:"Taktila bilder har lagts till för att tillgängliggöra visuella element för personer med synnedsättning"},"tactile-objects":"Taktila 3D-objekt","text-to-speech-hinting":"Innehåller uttalsinstruktioner för talsyntes",title:"Ytterligare tillgänglighetsinformation","ultra-high-contrast-between-text-and-background":"Extra hög kontrast mellan text och bakgrund","visible-page-numbering":"Synlig sidnumrering","without-background-sounds":"Utan bakgrundsljud"},conformance:{a:{compact:"Publikationen uppfyller tillgänglighetskrav på en grundläggande nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå A"},aa:{compact:"Publikationen uppfyller tillgänglighetskrav på en vedertagen nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå AA"},aaa:{compact:"Publikationen uppfyller tillgänglighetskrav utöver en vedertagen nivå",descriptive:"Publikationen anger att den uppfyller standarderna EPUB Accessibility och WCAG 2 nivå AAA"},certifier:"Publikationen är certifierad av ","certifier-credentials":"Certifierarens märkning är ",details:{"certification-info":"Publikationen certifierades ","certifier-report":"Se certifieringsrapporten för mer information",claim:"Publikationen anger att den uppfyller kraven enligt","epub-accessibility-1-0":"EPUB Accessibility 1.0","epub-accessibility-1-1":"EPUB Accessibility 1.1","level-a":"nivå A","level-aa":"nivå AA","level-aaa":"nivå AAA","wcag-2-0":{compact:"WCAG 2.0",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.0"},"wcag-2-1":{compact:"WCAG 2.1",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.1"},"wcag-2-2":{compact:"WCAG 2.2",descriptive:"Web Content Accessibility Guidelines (WCAG) 2.2"}},"details-title":"Detaljerad information om tillgänglighetskrav",no:"Information saknas",title:"Tillgänglighetskrav","unknown-standard":"Det går inte att avgöra om publikationen uppfyller vedertagna tillgänglighetskrav"},hazards:{flashing:{compact:"Blinkande innehåll",descriptive:"Publikationen har blinkande innehåll som kan vara skadligt för ljuskänsliga personer"},"flashing-none":{compact:"Inget blinkande innehåll",descriptive:"Publikationen har inget blinkande innehåll"},"flashing-unknown":{compact:"Förekomst av blinkande innehåll är okänd",descriptive:"Förekomst av blinkande innehåll är okänd"},motion:{compact:"Rörelsesimulering",descriptive:"Publikationen innehåller rörelsesimulering som skulle kunna orsaka illamående"},"motion-none":{compact:"Ingen rörelsesimulering",descriptive:"Publikationen innehåller ingen rörelsesimulering"},"motion-unknown":{compact:"Förekomst av rörelsesimulering är okänd",descriptive:"Förekomst av rörelsesimulering är okänd"},"no-metadata":"Information saknas",none:{compact:"Inga risker",descriptive:"Publikationen innehåller inga risker"},sound:{compact:"Ljud",descriptive:"Publikationen innehåller ljud som kan orsaka obehag"},"sound-none":{compact:"Inget ljud som kan orsaka obehag",descriptive:"Publikationen innehåller inget ljud som kan orsaka obehag"},"sound-unknown":{compact:"Förekomst av ljud som kan orsaka obehag är okänd",descriptive:"Förekomst av ljud som kan orsaka obehag är okänd"},title:"Risker",unknown:"Förekomst av risker är okänd"},"legal-considerations":{exempt:{compact:"Åberopar ett undantag från vissa lagstadgade tillgänglighetskrav",descriptive:"Publikationen åberopar ett undantag från vissa lagstadgade tillgänglighetskrav"},"no-metadata":"Information saknas",title:"Juridiska aspekter"},navigation:{index:{compact:"Register",descriptive:"Register med länkar till innehållet"},"no-metadata":"Information saknas","page-navigation":{compact:"Gå till sida",descriptive:"Sidindelning för navigering enligt sidnummer i tryckt förlaga"},structural:{compact:"Rubriker",descriptive:"Navigerbara element såsom rubriker eller tabeller"},title:"Navigering",toc:{compact:"Innehållsförteckning",descriptive:"Innehållsförteckning med länkar till alla kapitel"}},"rich-content":{"accessible-chemistry-as-latex":{compact:"Kemiska formler i LaTeX",descriptive:"Kemiska formler i tillgängligt format (LaTeX)"},"accessible-chemistry-as-mathml":{compact:"Kemiska formler i MathML",descriptive:"Kemiska formler i tillgängligt format (MathML)"},"accessible-math-as-latex":{compact:"Matematik som LaTeX",descriptive:"Matematiska formler i tillgängligt format (LaTeX)"},"accessible-math-described":"Innehåller textbeskrivningar av matematik","closed-captions":{compact:"Videoklipp har undertext som kan sättas på/stängas av",descriptive:"Videoklipp som ingår i publikationen har undertext som kan sättas på och stängas av (stängda undertexter)"},"extended-descriptions":"Informationsrika bilder har utökade bildbeskrivningar","math-as-mathml":{compact:"Matematik som MathML",descriptive:"Matematiska formler i tillgängligt format (MathML)"},"open-captions":{compact:"Videoklipp har undertext som inte kan stängas av",descriptive:"Videoklipp som ingår i publikationen har undertext som inte kan stängas av (öppna undertexter)"},title:"Berikat innehåll",transcript:"Innehåller transkriptioner",unknown:"Information saknas"},"ways-of-reading":{"nonvisual-reading":{"alt-text":{compact:"Har textalternativ (alt-texter)",descriptive:"Har textalternativ (alt-texter) till bilder"},"no-metadata":"Information om icke-visuell läsbarhet saknas",none:{compact:"Kan inte läsas med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Innehållet går inte att läsa med uppläsningsfunktion eller punktskriftsskärm"},"not-fully":{compact:"Inte läsbart i sin helhet med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Allt innehåll går inte att läsa med uppläsningsfunktion eller punktskriftsskärm"},readable:{compact:"Kan läsas med uppläsningsfunktion eller punktskriftsskärm",descriptive:"Hela innehållet går att läsa med uppläsningsfunktion eller punktskriftsskärm"}},"prerecorded-audio":{complementary:{compact:"Förinspelade ljudklipp",descriptive:"Innehåller förinspelade ljudklipp"},"no-metadata":"Information om förinspelat ljud saknas",only:{compact:"Endast förinspelat ljud",descriptive:"Bok med ljud utan textalternativ"},synchronized:{compact:"Förinspelat ljud synkroniserat med texten",descriptive:"Hela innehållet finns tillgängligt som förinspelat ljud synkroniserat med texten"}},title:"Olika sätt att läsa","visual-adjustments":{modifiable:{compact:"Utseendet kan justeras",descriptive:"Det går att justera text och layout i den utsträckning som läsprogrammet tillåter, till exempel typsnitt, storlek på text, avstånd mellan rader och stycken samt färg på text och bakgrund"},unknown:"Information om möjlighet att justera utseende saknas",unmodifiable:{compact:"Utseendet kan inte justeras",descriptive:"Text- och sidlayout kan inte justeras eftersom presentationen liknar en tryckt version, men läsprogram kan ha funktioner för att zooma in"}}}}},altIdentifier_one:"alternativ identifierare",altIdentifier_other:"alternativa identifierare",artist_one:"konstnär",artist_other:"konstnärer",author_one:"författare",author_other:"författare",collection_one:"samling",collection_other:"samlingar",colorist_one:"kolorist",colorist_other:"kolorister",contributor_one:"medverkande",contributor_other:"medverkande",description:"beskrivning",duration:"speltid",editor_one:"redaktör",editor_other:"redaktörer",identifier_one:"identifierare",identifier_other:"identifierare",illustrator_one:"illustratör",illustrator_other:"illustratörer",imprint_one:"imprint",imprint_other:"imprint",inker_one:"tuschare",inker_other:"tuschare",language_one:"språk",language_other:"språk",letterer_one:"textare",letterer_other:"textare",modified:"ändringsdatum",narrator_one:"berättarröst",narrator_other:"berättarröster",numberOfPages:"sidantal",penciler_one:"tecknare",penciler_other:"tecknare",published:"publikationsdatum",publisher_one:"förlag",publisher_other:"förlag",series_one:"serie",series_other:"serier",subject_one:"ämne",subject_other:"ämnen",subtitle:"undertitel",title:"titel",translator_one:"översättare",translator_other:"översättare"}},$r=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:to},publication:to},Symbol.toStringTag,{value:"Module"})),Kr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
694
+ * Readium CSS v.2.0.4
696
695
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
697
696
  * Use of this source code is governed by a BSD-style license which is detailed in the
698
697
  * LICENSE file present in the project repository where this source code is maintained.
@@ -725,6 +724,14 @@ registerProcessor('preserve-pitch-processor', PreservePitchProcessor);
725
724
 
726
725
  :root{
727
726
 
727
+ --RS__sans-serif-ja-v:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDGothic', 'Yu Gothic', 'MSゴシック', 'MS Gothic', sans-serif;
728
+
729
+ --RS__serif-ja-v:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDMincho', 'Yu Mincho', 'MS明朝', 'MS Mincho', serif;
730
+
731
+ --RS__sans-serif-ja:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDPGothic', 'Yu Gothic', 'MS Pゴシック', 'MS PGothic', sans-serif;
732
+
733
+ --RS__serif-ja:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDPMincho', 'Yu Mincho', 'MS P明朝', 'MS PMincho', serif;
734
+
728
735
  --RS__monospaceTf:ui-monospace, 'Andale Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
729
736
 
730
737
  --RS__humanistTf:Seravek, Calibri, 'Gill Sans Nova', Roboto, Ubuntu, 'DejaVu Sans', source-sans-pro, sans-serif;
@@ -734,9 +741,106 @@ registerProcessor('preserve-pitch-processor', PreservePitchProcessor);
734
741
  --RS__modernTf:Athelas, Constantia, Charter, 'Bitstream Charter', Cambria, 'Georgia Pro', Georgia, serif;
735
742
 
736
743
  --RS__oldStyleTf:'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif;
737
- --RS__baseFontFamily:var(--RS__oldStyleTf);
738
- --RS__lineHeightCompensation:1;
739
744
 
745
+ --RS__zh-HK-lineHeightCompensation:1.167;
746
+
747
+ --RS__zh-HK-baseFontFamily:'方體', 'PingFang HK', '方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
748
+
749
+ --RS__zh-TW-lineHeightCompensation:1.167;
750
+
751
+ --RS__zh-TW-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
752
+
753
+ --RS__zh-Hant-lineHeightCompensation:1.167;
754
+
755
+ --RS__zh-Hant-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
756
+
757
+ --RS__zh-lineHeightCompensation:1.167;
758
+
759
+ --RS__zh-baseFontFamily:'方体', 'PingFang SC', '黑体', 'Heiti SC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK SC', sans-serif;
760
+
761
+ --RS__th-lineHeightCompensation:1.067;
762
+
763
+ --RS__th-baseFontFamily:Thonburi, 'Leelawadee UI', 'Cordia New', Roboto, Noto, 'Noto Sans Thai', sans-serif;
764
+
765
+ --RS__te-baseFontFamily:'Kohinoor Telugu', 'Telugu Sangam MN', 'Nirmala UI', Gautami, Roboto, Noto, 'Noto Sans Telugu', sans-serif;
766
+
767
+ --RS__ta-lineHeightCompensation:1.067;
768
+
769
+ --RS__ta-baseFontFamily:'Tamil Sangam MN', 'Nirmala UI', Latha, Roboto, Noto, 'Noto Sans Tamil', sans-serif;
770
+
771
+ --RS__si-lineHeightCompensation:1.167;
772
+
773
+ --RS__si-baseFontFamily:'Sinhala Sangam MN', 'Nirmala UI', 'Iskoola Pota', Roboto, Noto, 'Noto Sans Sinhala', sans-serif;
774
+
775
+ --RS__pa-lineHeightCompensation:1.1;
776
+
777
+ --RS__pa-baseFontFamily:'Gurmukhi MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Gurmukhi', sans-serif;
778
+
779
+ --RS__or-lineHeightCompensation:1.167;
780
+
781
+ --RS__or-baseFontFamily:'Oriya Sangam MN', 'Nirmala UI', Kalinga, Roboto, Noto, 'Noto Sans Oriya', sans-serif;
782
+
783
+ --RS__ml-lineHeightCompensation:1.067;
784
+
785
+ --RS__ml-baseFontFamily:'Malayalam Sangam MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Malayalam', sans-serif;
786
+
787
+ --RS__lo-baseFontFamily:'Lao Sangam MN', 'Leelawadee UI', 'Lao UI', Roboto, Noto, 'Noto Sans Lao', sans-serif;
788
+
789
+ --RS__ko-lineHeightCompensation:1.167;
790
+
791
+ --RS__ko-baseFontFamily:'Nanum Gothic', 'Apple SD Gothic Neo', 'Malgun Gothic', Roboto, Noto, 'Noto Sans CJK KR', sans-serif;
792
+
793
+ --RS__kn-lineHeightCompensation:1.1;
794
+
795
+ --RS__kn-baseFontFamily:'Kannada Sangam MN', 'Nirmala UI', Tunga, Roboto, Noto, 'Noto Sans Kannada', sans-serif;
796
+
797
+ --RS__km-lineHeightCompensation:1.067;
798
+
799
+ --RS__km-baseFontFamily:'Khmer Sangam MN', 'Leelawadee UI', 'Khmer UI', Roboto, Noto, 'Noto Sans Khmer', sans-serif;
800
+
801
+ --RS__ja-lineHeightCompensation:1.167;
802
+
803
+ --RS__ja-baseFontFamily:YuGothic, 'Hiragino Maru Gothic ProN', 'Hiragino Sans', 'Yu Gothic UI', 'Meiryo UI', 'MS Gothic', Roboto, Noto, 'Noto Sans CJK JP', sans-serif;
804
+
805
+ --RS__iu-baseFontFamily:'Euphemia UCAS', Euphemia, Roboto, Noto, 'Noto Sans Canadian Aboriginal', sans-serif;
806
+
807
+ --RS__hy-baseFontFamily:Mshtakan, Sylfaen, Roboto, Noto, 'Noto Serif Armenian', serif;
808
+
809
+ --RS__hi-lineHeightCompensation:1.1;
810
+
811
+ --RS__hi-baseFontFamily:'Kohinoor Devanagari', 'Devanagari Sangam MN', Kokila, 'Nirmala UI', Roboto, Noto, 'Noto Sans Devanagari', sans-serif;
812
+
813
+ --RS__he-lineHeightCompensation:1.1;
814
+
815
+ --RS__he-baseFontFamily:'New Peninim MT', 'Arial Hebrew', Gisha, 'Times New Roman', Roboto, Noto, 'Noto Sans Hebrew', sans-serif;
816
+
817
+ --RS__gu-lineHeightCompensation:1.167;
818
+
819
+ --RS__gu-baseFontFamily:'Gujarati Sangam MN', 'Nirmala UI', Shruti, Roboto, Noto, 'Noto Sans Gujarati', sans-serif;
820
+
821
+ --RS__fa-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
822
+
823
+ --RS__chr-lineHeightCompensation:1.167;
824
+
825
+ --RS__chr-baseFontFamily:'Plantagenet Cherokee', Roboto, Noto, 'Noto Sans Cherokee';
826
+
827
+ --RS__bo-baseFontFamily:Kailasa, 'Microsoft Himalaya', Roboto, Noto, 'Noto Sans Tibetan', sans-serif;
828
+
829
+ --RS__bn-lineHeightCompensation:1.067;
830
+
831
+ --RS__bn-baseFontFamily:'Kohinoor Bangla', 'Bangla Sangam MN', Vrinda, Roboto, Noto, 'Noto Sans Bengali', sans-serif;
832
+
833
+ --RS__ar-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
834
+
835
+ --RS__am-lineHeightCompensation:1.167;
836
+
837
+ --RS__am-baseFontFamily:Kefa, Nyala, Roboto, Noto, 'Noto Sans Ethiopic', serif;
838
+
839
+ --RS__default-lineHeightCompensation:1;
840
+
841
+ --RS__default-baseFontFamily:var(--RS__oldStyleTf);
842
+ --RS__baseFontFamily:var(--RS__default-baseFontFamily);
843
+ --RS__lineHeightCompensation:var(--RS__default-lineHeightCompensation);
740
844
  --RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));
741
845
 
742
846
  --RS__selectionTextColor:inherit;
@@ -790,132 +894,131 @@ math{
790
894
  }
791
895
 
792
896
  :lang(am){
793
- --RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;
794
- --RS__lineHeightCompensation:1.167;
897
+ --RS__baseFontFamily:var(--RS__am-baseFontFamily);
898
+ --RS__lineHeightCompensation:var(--RS__am-lineHeightCompensation);
795
899
  }
796
900
 
797
901
  :lang(ar){
798
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
902
+ --RS__baseFontFamily:var(--RS__ar-baseFontFamily);
799
903
  }
800
904
 
801
905
  :lang(bn){
802
- --RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;
803
- --RS__lineHeightCompensation:1.067;
906
+ --RS__baseFontFamily:var(--RS__bn-baseFontFamily);
907
+ --RS__lineHeightCompensation:var(--RS__bn-lineHeightCompensation);
804
908
  }
805
909
 
806
910
  :lang(bo){
807
- --RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif;
911
+ --RS__baseFontFamily:var(--RS__bo-baseFontFamily);
808
912
  }
809
913
 
810
914
  :lang(chr){
811
- --RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";
812
- --RS__lineHeightCompensation:1.167;
915
+ --RS__baseFontFamily:var(--RS__chr-baseFontFamily);
916
+ --RS__lineHeightCompensation:var(--RS__chr-lineHeightCompensation);
813
917
  }
814
918
 
815
919
  :lang(fa){
816
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
920
+ --RS__baseFontFamily:var(--RS__fa-baseFontFamily);
817
921
  }
818
922
 
819
923
  :lang(gu){
820
- --RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;
821
- --RS__lineHeightCompensation:1.167;
924
+ --RS__baseFontFamily:var(--RS__gu-baseFontFamily);
925
+ --RS__lineHeightCompensation:var(--RS__gu-lineHeightCompensation);
822
926
  }
823
927
 
824
928
  :lang(he){
825
- --RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;
826
- --RS__lineHeightCompensation:1.1;
929
+ --RS__baseFontFamily:var(--RS__he-baseFontFamily);
930
+ --RS__lineHeightCompensation:var(--RS__he-lineHeightCompensation);
827
931
  }
828
932
 
829
933
  :lang(hi){
830
- --RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;
831
-
832
- --RS__lineHeightCompensation:1.1;
934
+ --RS__baseFontFamily:var(--RS__hi-baseFontFamily);
935
+ --RS__lineHeightCompensation:var(--RS__hi-lineHeightCompensation);
833
936
  }
834
937
 
835
938
  :lang(hy){
836
- --RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif;
939
+ --RS__baseFontFamily:var(--RS__hy-baseFontFamily);
837
940
  }
838
941
 
839
942
  :lang(iu){
840
- --RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif;
943
+ --RS__baseFontFamily:var(--RS__iu-baseFontFamily);
841
944
  }
842
945
 
843
946
  :lang(ja){
844
- --RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;
845
- --RS__lineHeightCompensation:1.167;
846
- --RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;
847
- --RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;
848
- --RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;
849
- --RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif;
947
+ --RS__baseFontFamily:var(--RS__ja-baseFontFamily);
948
+ --RS__lineHeightCompensation:var(--RS__ja-lineHeightCompensation);
850
949
  }
851
950
 
852
951
  :lang(km){
853
- --RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;
854
- --RS__lineHeightCompensation:1.067;
952
+ --RS__baseFontFamily:var(--RS__km-baseFontFamily);
953
+ --RS__lineHeightCompensation:var(--RS__km-lineHeightCompensation);
855
954
  }
856
955
 
857
956
  :lang(kn){
858
- --RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;
859
- --RS__lineHeightCompensation:1.1;
957
+ --RS__baseFontFamily:var(--RS__kn-baseFontFamily);
958
+ --RS__lineHeightCompensation:var(--RS__kn-lineHeightCompensation);
860
959
  }
861
960
 
862
961
  :lang(ko){
863
- --RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;
864
- --RS__lineHeightCompensation:1.167;
962
+ --RS__baseFontFamily:var(--RS__ko-baseFontFamily);
963
+ --RS__lineHeightCompensation:var(--RS__ko-lineHeightCompensation);
865
964
  }
866
965
 
867
966
  :lang(lo){
868
- --RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif;
967
+ --RS__baseFontFamily:var(--RS__lo-baseFontFamily);
869
968
  }
870
969
 
871
970
  :lang(ml){
872
- --RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;
873
- --RS__lineHeightCompensation:1.067;
971
+ --RS__baseFontFamily:var(--RS__ml-baseFontFamily);
972
+ --RS__lineHeightCompensation:var(--RS__ml-lineHeightCompensation);
874
973
  }
875
974
 
876
975
  :lang(or){
877
- --RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;
878
- --RS__lineHeightCompensation:1.167;
976
+ --RS__baseFontFamily:var(--RS__or-baseFontFamily);
977
+ --RS__lineHeightCompensation:var(--RS__or-lineHeightCompensation);
879
978
  }
880
979
 
881
980
  :lang(pa){
882
- --RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;
883
- --RS__lineHeightCompensation:1.1;
981
+ --RS__baseFontFamily:var(--RS__pa-baseFontFamily);
982
+ --RS__lineHeightCompensation:var(--RS__pa-lineHeightCompensation);
884
983
  }
885
984
 
886
985
  :lang(si){
887
- --RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;
888
- --RS__lineHeightCompensation:1.167;
986
+ --RS__baseFontFamily:var(--RS__si-baseFontFamily);
987
+ --RS__lineHeightCompensation:var(--RS__si-lineHeightCompensation);
889
988
  }
890
989
 
891
990
  :lang(ta){
892
- --RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;
893
- --RS__lineHeightCompensation:1.067;
991
+ --RS__baseFontFamily:var(--RS__ta-baseFontFamily);
992
+ --RS__lineHeightCompensation:var(--RS__ta-lineHeightCompensation);
894
993
  }
895
994
 
896
995
  :lang(te){
897
- --RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif;
996
+ --RS__baseFontFamily:var(--RS__te-baseFontFamily);
898
997
  }
899
998
 
900
999
  :lang(th){
901
- --RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;
902
- --RS__lineHeightCompensation:1.067;
1000
+ --RS__baseFontFamily:var(--RS__th-baseFontFamily);
1001
+ --RS__lineHeightCompensation:var(--RS__th-lineHeightCompensation);
903
1002
  }
904
1003
 
905
1004
  :lang(zh){
906
- --RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;
907
- --RS__lineHeightCompensation:1.167;
1005
+ --RS__baseFontFamily:var(--RS__zh-baseFontFamily);
1006
+ --RS__lineHeightCompensation:var(--RS__zh-lineHeightCompensation);
1007
+ }
1008
+
1009
+ :lang(zh-Hant){
1010
+ --RS__baseFontFamily:var(--RS__zh-Hant-baseFontFamily);
1011
+ --RS__lineHeightCompensation:var(--RS__zh-Hant-lineHeightCompensation);
908
1012
  }
909
1013
 
910
- :lang(zh-Hant),
911
1014
  :lang(zh-TW){
912
- --RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
913
- --RS__lineHeightCompensation:1.167;
1015
+ --RS__baseFontFamily:var(--RS__zh-TW-baseFontFamily);
1016
+ --RS__lineHeightCompensation:var(--RS__zh-TW-lineHeightCompensation);
914
1017
  }
915
1018
 
916
1019
  :lang(zh-HK){
917
- --RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
918
- --RS__lineHeightCompensation:1.167;
1020
+ --RS__baseFontFamily:var(--RS__zh-HK-baseFontFamily);
1021
+ --RS__lineHeightCompensation:var(--RS__zh-HK-lineHeightCompensation);
919
1022
  }
920
1023
 
921
1024
  body{
@@ -1112,8 +1215,8 @@ audio{
1112
1215
  table{
1113
1216
  max-width:var(--RS__maxMediaWidth);
1114
1217
  box-sizing:var(--RS__boxSizingTable);
1115
- }`},Symbol.toStringTag,{value:"Module"})),jr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1116
- * Readium CSS v.2.0.0
1218
+ }`},Symbol.toStringTag,{value:"Module"})),Xr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1219
+ * Readium CSS v.2.0.4
1117
1220
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
1118
1221
  * Use of this source code is governed by a BSD-style license which is detailed in the
1119
1222
  * LICENSE file present in the project repository where this source code is maintained.
@@ -1270,8 +1373,8 @@ th{
1270
1373
  th, td{
1271
1374
  padding:4px;
1272
1375
  border:1px solid currentcolor;
1273
- }`},Symbol.toStringTag,{value:"Module"})),Gr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1274
- * Readium CSS v.2.0.0
1376
+ }`},Symbol.toStringTag,{value:"Module"})),Yr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1377
+ * Readium CSS v.2.0.4
1275
1378
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
1276
1379
  * Use of this source code is governed by a BSD-style license which is detailed in the
1277
1380
  * LICENSE file present in the project repository where this source code is maintained.
@@ -1567,7 +1670,7 @@ body{
1567
1670
  :root[style*="--USER__lineHeight"] p,
1568
1671
  :root[style*="--USER__lineHeight"] li,
1569
1672
  :root[style*="--USER__lineHeight"] div{
1570
- line-height:inherit;
1673
+ line-height:var(--USER__lineHeight) !important;
1571
1674
  }
1572
1675
 
1573
1676
  :root[style*="--USER__paraSpacing"] p{
@@ -1587,8 +1690,7 @@ body{
1587
1690
  text-indent:var(--USER__paraIndent) !important;
1588
1691
  }
1589
1692
 
1590
- :root[style*="--USER__paraIndent"] p *,
1591
- :root[style*="--USER__paraIndent"] p:first-letter{
1693
+ :root[style*="--USER__paraIndent"] p *{
1592
1694
  text-indent:0 !important;
1593
1695
  }
1594
1696
 
@@ -1603,7 +1705,7 @@ body{
1603
1705
  :root[style*="--USER__wordSpacing"] div,
1604
1706
  :root[style*="--USER__wordSpacing"] dt,
1605
1707
  :root[style*="--USER__wordSpacing"] dd{
1606
- word-spacing:var(--USER__wordSpacing);
1708
+ word-spacing:var(--USER__wordSpacing) !important;
1607
1709
  }
1608
1710
 
1609
1711
  :root[style*="--USER__ligatures"]{
@@ -1797,8 +1899,8 @@ body{
1797
1899
 
1798
1900
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
1799
1901
  -webkit-text-zoom:normal;
1800
- }`},Symbol.toStringTag,{value:"Module"})),Vr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1801
- * Readium CSS v.2.0.0
1902
+ }`},Symbol.toStringTag,{value:"Module"})),qr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
1903
+ * Readium CSS v.2.0.4
1802
1904
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
1803
1905
  * Use of this source code is governed by a BSD-style license which is detailed in the
1804
1906
  * LICENSE file present in the project repository where this source code is maintained.
@@ -1831,6 +1933,14 @@ body{
1831
1933
 
1832
1934
  :root{
1833
1935
 
1936
+ --RS__sans-serif-ja-v:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDGothic', 'Yu Gothic', 'MSゴシック', 'MS Gothic', sans-serif;
1937
+
1938
+ --RS__serif-ja-v:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDMincho', 'Yu Mincho', 'MS明朝', 'MS Mincho', serif;
1939
+
1940
+ --RS__sans-serif-ja:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDPGothic', 'Yu Gothic', 'MS Pゴシック', 'MS PGothic', sans-serif;
1941
+
1942
+ --RS__serif-ja:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDPMincho', 'Yu Mincho', 'MS P明朝', 'MS PMincho', serif;
1943
+
1834
1944
  --RS__monospaceTf:ui-monospace, 'Andale Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
1835
1945
 
1836
1946
  --RS__humanistTf:Seravek, Calibri, 'Gill Sans Nova', Roboto, Ubuntu, 'DejaVu Sans', source-sans-pro, sans-serif;
@@ -1840,9 +1950,106 @@ body{
1840
1950
  --RS__modernTf:Athelas, Constantia, Charter, 'Bitstream Charter', Cambria, 'Georgia Pro', Georgia, serif;
1841
1951
 
1842
1952
  --RS__oldStyleTf:'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif;
1843
- --RS__baseFontFamily:var(--RS__oldStyleTf);
1844
- --RS__lineHeightCompensation:1;
1845
1953
 
1954
+ --RS__zh-HK-lineHeightCompensation:1.167;
1955
+
1956
+ --RS__zh-HK-baseFontFamily:'方體', 'PingFang HK', '方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
1957
+
1958
+ --RS__zh-TW-lineHeightCompensation:1.167;
1959
+
1960
+ --RS__zh-TW-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
1961
+
1962
+ --RS__zh-Hant-lineHeightCompensation:1.167;
1963
+
1964
+ --RS__zh-Hant-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
1965
+
1966
+ --RS__zh-lineHeightCompensation:1.167;
1967
+
1968
+ --RS__zh-baseFontFamily:'方体', 'PingFang SC', '黑体', 'Heiti SC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK SC', sans-serif;
1969
+
1970
+ --RS__th-lineHeightCompensation:1.067;
1971
+
1972
+ --RS__th-baseFontFamily:Thonburi, 'Leelawadee UI', 'Cordia New', Roboto, Noto, 'Noto Sans Thai', sans-serif;
1973
+
1974
+ --RS__te-baseFontFamily:'Kohinoor Telugu', 'Telugu Sangam MN', 'Nirmala UI', Gautami, Roboto, Noto, 'Noto Sans Telugu', sans-serif;
1975
+
1976
+ --RS__ta-lineHeightCompensation:1.067;
1977
+
1978
+ --RS__ta-baseFontFamily:'Tamil Sangam MN', 'Nirmala UI', Latha, Roboto, Noto, 'Noto Sans Tamil', sans-serif;
1979
+
1980
+ --RS__si-lineHeightCompensation:1.167;
1981
+
1982
+ --RS__si-baseFontFamily:'Sinhala Sangam MN', 'Nirmala UI', 'Iskoola Pota', Roboto, Noto, 'Noto Sans Sinhala', sans-serif;
1983
+
1984
+ --RS__pa-lineHeightCompensation:1.1;
1985
+
1986
+ --RS__pa-baseFontFamily:'Gurmukhi MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Gurmukhi', sans-serif;
1987
+
1988
+ --RS__or-lineHeightCompensation:1.167;
1989
+
1990
+ --RS__or-baseFontFamily:'Oriya Sangam MN', 'Nirmala UI', Kalinga, Roboto, Noto, 'Noto Sans Oriya', sans-serif;
1991
+
1992
+ --RS__ml-lineHeightCompensation:1.067;
1993
+
1994
+ --RS__ml-baseFontFamily:'Malayalam Sangam MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Malayalam', sans-serif;
1995
+
1996
+ --RS__lo-baseFontFamily:'Lao Sangam MN', 'Leelawadee UI', 'Lao UI', Roboto, Noto, 'Noto Sans Lao', sans-serif;
1997
+
1998
+ --RS__ko-lineHeightCompensation:1.167;
1999
+
2000
+ --RS__ko-baseFontFamily:'Nanum Gothic', 'Apple SD Gothic Neo', 'Malgun Gothic', Roboto, Noto, 'Noto Sans CJK KR', sans-serif;
2001
+
2002
+ --RS__kn-lineHeightCompensation:1.1;
2003
+
2004
+ --RS__kn-baseFontFamily:'Kannada Sangam MN', 'Nirmala UI', Tunga, Roboto, Noto, 'Noto Sans Kannada', sans-serif;
2005
+
2006
+ --RS__km-lineHeightCompensation:1.067;
2007
+
2008
+ --RS__km-baseFontFamily:'Khmer Sangam MN', 'Leelawadee UI', 'Khmer UI', Roboto, Noto, 'Noto Sans Khmer', sans-serif;
2009
+
2010
+ --RS__ja-lineHeightCompensation:1.167;
2011
+
2012
+ --RS__ja-baseFontFamily:YuGothic, 'Hiragino Maru Gothic ProN', 'Hiragino Sans', 'Yu Gothic UI', 'Meiryo UI', 'MS Gothic', Roboto, Noto, 'Noto Sans CJK JP', sans-serif;
2013
+
2014
+ --RS__iu-baseFontFamily:'Euphemia UCAS', Euphemia, Roboto, Noto, 'Noto Sans Canadian Aboriginal', sans-serif;
2015
+
2016
+ --RS__hy-baseFontFamily:Mshtakan, Sylfaen, Roboto, Noto, 'Noto Serif Armenian', serif;
2017
+
2018
+ --RS__hi-lineHeightCompensation:1.1;
2019
+
2020
+ --RS__hi-baseFontFamily:'Kohinoor Devanagari', 'Devanagari Sangam MN', Kokila, 'Nirmala UI', Roboto, Noto, 'Noto Sans Devanagari', sans-serif;
2021
+
2022
+ --RS__he-lineHeightCompensation:1.1;
2023
+
2024
+ --RS__he-baseFontFamily:'New Peninim MT', 'Arial Hebrew', Gisha, 'Times New Roman', Roboto, Noto, 'Noto Sans Hebrew', sans-serif;
2025
+
2026
+ --RS__gu-lineHeightCompensation:1.167;
2027
+
2028
+ --RS__gu-baseFontFamily:'Gujarati Sangam MN', 'Nirmala UI', Shruti, Roboto, Noto, 'Noto Sans Gujarati', sans-serif;
2029
+
2030
+ --RS__fa-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
2031
+
2032
+ --RS__chr-lineHeightCompensation:1.167;
2033
+
2034
+ --RS__chr-baseFontFamily:'Plantagenet Cherokee', Roboto, Noto, 'Noto Sans Cherokee';
2035
+
2036
+ --RS__bo-baseFontFamily:Kailasa, 'Microsoft Himalaya', Roboto, Noto, 'Noto Sans Tibetan', sans-serif;
2037
+
2038
+ --RS__bn-lineHeightCompensation:1.067;
2039
+
2040
+ --RS__bn-baseFontFamily:'Kohinoor Bangla', 'Bangla Sangam MN', Vrinda, Roboto, Noto, 'Noto Sans Bengali', sans-serif;
2041
+
2042
+ --RS__ar-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
2043
+
2044
+ --RS__am-lineHeightCompensation:1.167;
2045
+
2046
+ --RS__am-baseFontFamily:Kefa, Nyala, Roboto, Noto, 'Noto Sans Ethiopic', serif;
2047
+
2048
+ --RS__default-lineHeightCompensation:1;
2049
+
2050
+ --RS__default-baseFontFamily:var(--RS__oldStyleTf);
2051
+ --RS__baseFontFamily:var(--RS__default-baseFontFamily);
2052
+ --RS__lineHeightCompensation:var(--RS__default-lineHeightCompensation);
1846
2053
  --RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));
1847
2054
 
1848
2055
  --RS__selectionTextColor:inherit;
@@ -1896,132 +2103,131 @@ math{
1896
2103
  }
1897
2104
 
1898
2105
  :lang(am){
1899
- --RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;
1900
- --RS__lineHeightCompensation:1.167;
2106
+ --RS__baseFontFamily:var(--RS__am-baseFontFamily);
2107
+ --RS__lineHeightCompensation:var(--RS__am-lineHeightCompensation);
1901
2108
  }
1902
2109
 
1903
2110
  :lang(ar){
1904
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
2111
+ --RS__baseFontFamily:var(--RS__ar-baseFontFamily);
1905
2112
  }
1906
2113
 
1907
2114
  :lang(bn){
1908
- --RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;
1909
- --RS__lineHeightCompensation:1.067;
2115
+ --RS__baseFontFamily:var(--RS__bn-baseFontFamily);
2116
+ --RS__lineHeightCompensation:var(--RS__bn-lineHeightCompensation);
1910
2117
  }
1911
2118
 
1912
2119
  :lang(bo){
1913
- --RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif;
2120
+ --RS__baseFontFamily:var(--RS__bo-baseFontFamily);
1914
2121
  }
1915
2122
 
1916
2123
  :lang(chr){
1917
- --RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";
1918
- --RS__lineHeightCompensation:1.167;
2124
+ --RS__baseFontFamily:var(--RS__chr-baseFontFamily);
2125
+ --RS__lineHeightCompensation:var(--RS__chr-lineHeightCompensation);
1919
2126
  }
1920
2127
 
1921
2128
  :lang(fa){
1922
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
2129
+ --RS__baseFontFamily:var(--RS__fa-baseFontFamily);
1923
2130
  }
1924
2131
 
1925
2132
  :lang(gu){
1926
- --RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;
1927
- --RS__lineHeightCompensation:1.167;
2133
+ --RS__baseFontFamily:var(--RS__gu-baseFontFamily);
2134
+ --RS__lineHeightCompensation:var(--RS__gu-lineHeightCompensation);
1928
2135
  }
1929
2136
 
1930
2137
  :lang(he){
1931
- --RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;
1932
- --RS__lineHeightCompensation:1.1;
2138
+ --RS__baseFontFamily:var(--RS__he-baseFontFamily);
2139
+ --RS__lineHeightCompensation:var(--RS__he-lineHeightCompensation);
1933
2140
  }
1934
2141
 
1935
2142
  :lang(hi){
1936
- --RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;
1937
-
1938
- --RS__lineHeightCompensation:1.1;
2143
+ --RS__baseFontFamily:var(--RS__hi-baseFontFamily);
2144
+ --RS__lineHeightCompensation:var(--RS__hi-lineHeightCompensation);
1939
2145
  }
1940
2146
 
1941
2147
  :lang(hy){
1942
- --RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif;
2148
+ --RS__baseFontFamily:var(--RS__hy-baseFontFamily);
1943
2149
  }
1944
2150
 
1945
2151
  :lang(iu){
1946
- --RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif;
2152
+ --RS__baseFontFamily:var(--RS__iu-baseFontFamily);
1947
2153
  }
1948
2154
 
1949
2155
  :lang(ja){
1950
- --RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;
1951
- --RS__lineHeightCompensation:1.167;
1952
- --RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;
1953
- --RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;
1954
- --RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;
1955
- --RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif;
2156
+ --RS__baseFontFamily:var(--RS__ja-baseFontFamily);
2157
+ --RS__lineHeightCompensation:var(--RS__ja-lineHeightCompensation);
1956
2158
  }
1957
2159
 
1958
2160
  :lang(km){
1959
- --RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;
1960
- --RS__lineHeightCompensation:1.067;
2161
+ --RS__baseFontFamily:var(--RS__km-baseFontFamily);
2162
+ --RS__lineHeightCompensation:var(--RS__km-lineHeightCompensation);
1961
2163
  }
1962
2164
 
1963
2165
  :lang(kn){
1964
- --RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;
1965
- --RS__lineHeightCompensation:1.1;
2166
+ --RS__baseFontFamily:var(--RS__kn-baseFontFamily);
2167
+ --RS__lineHeightCompensation:var(--RS__kn-lineHeightCompensation);
1966
2168
  }
1967
2169
 
1968
2170
  :lang(ko){
1969
- --RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;
1970
- --RS__lineHeightCompensation:1.167;
2171
+ --RS__baseFontFamily:var(--RS__ko-baseFontFamily);
2172
+ --RS__lineHeightCompensation:var(--RS__ko-lineHeightCompensation);
1971
2173
  }
1972
2174
 
1973
2175
  :lang(lo){
1974
- --RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif;
2176
+ --RS__baseFontFamily:var(--RS__lo-baseFontFamily);
1975
2177
  }
1976
2178
 
1977
2179
  :lang(ml){
1978
- --RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;
1979
- --RS__lineHeightCompensation:1.067;
2180
+ --RS__baseFontFamily:var(--RS__ml-baseFontFamily);
2181
+ --RS__lineHeightCompensation:var(--RS__ml-lineHeightCompensation);
1980
2182
  }
1981
2183
 
1982
2184
  :lang(or){
1983
- --RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;
1984
- --RS__lineHeightCompensation:1.167;
2185
+ --RS__baseFontFamily:var(--RS__or-baseFontFamily);
2186
+ --RS__lineHeightCompensation:var(--RS__or-lineHeightCompensation);
1985
2187
  }
1986
2188
 
1987
2189
  :lang(pa){
1988
- --RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;
1989
- --RS__lineHeightCompensation:1.1;
2190
+ --RS__baseFontFamily:var(--RS__pa-baseFontFamily);
2191
+ --RS__lineHeightCompensation:var(--RS__pa-lineHeightCompensation);
1990
2192
  }
1991
2193
 
1992
2194
  :lang(si){
1993
- --RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;
1994
- --RS__lineHeightCompensation:1.167;
2195
+ --RS__baseFontFamily:var(--RS__si-baseFontFamily);
2196
+ --RS__lineHeightCompensation:var(--RS__si-lineHeightCompensation);
1995
2197
  }
1996
2198
 
1997
2199
  :lang(ta){
1998
- --RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;
1999
- --RS__lineHeightCompensation:1.067;
2200
+ --RS__baseFontFamily:var(--RS__ta-baseFontFamily);
2201
+ --RS__lineHeightCompensation:var(--RS__ta-lineHeightCompensation);
2000
2202
  }
2001
2203
 
2002
2204
  :lang(te){
2003
- --RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif;
2205
+ --RS__baseFontFamily:var(--RS__te-baseFontFamily);
2004
2206
  }
2005
2207
 
2006
2208
  :lang(th){
2007
- --RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;
2008
- --RS__lineHeightCompensation:1.067;
2209
+ --RS__baseFontFamily:var(--RS__th-baseFontFamily);
2210
+ --RS__lineHeightCompensation:var(--RS__th-lineHeightCompensation);
2009
2211
  }
2010
2212
 
2011
2213
  :lang(zh){
2012
- --RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;
2013
- --RS__lineHeightCompensation:1.167;
2214
+ --RS__baseFontFamily:var(--RS__zh-baseFontFamily);
2215
+ --RS__lineHeightCompensation:var(--RS__zh-lineHeightCompensation);
2216
+ }
2217
+
2218
+ :lang(zh-Hant){
2219
+ --RS__baseFontFamily:var(--RS__zh-Hant-baseFontFamily);
2220
+ --RS__lineHeightCompensation:var(--RS__zh-Hant-lineHeightCompensation);
2014
2221
  }
2015
2222
 
2016
- :lang(zh-Hant),
2017
2223
  :lang(zh-TW){
2018
- --RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
2019
- --RS__lineHeightCompensation:1.167;
2224
+ --RS__baseFontFamily:var(--RS__zh-TW-baseFontFamily);
2225
+ --RS__lineHeightCompensation:var(--RS__zh-TW-lineHeightCompensation);
2020
2226
  }
2021
2227
 
2022
2228
  :lang(zh-HK){
2023
- --RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
2024
- --RS__lineHeightCompensation:1.167;
2229
+ --RS__baseFontFamily:var(--RS__zh-HK-baseFontFamily);
2230
+ --RS__lineHeightCompensation:var(--RS__zh-HK-lineHeightCompensation);
2025
2231
  }
2026
2232
 
2027
2233
  body{
@@ -2218,8 +2424,8 @@ audio{
2218
2424
  table{
2219
2425
  max-width:var(--RS__maxMediaWidth);
2220
2426
  box-sizing:var(--RS__boxSizingTable);
2221
- }`},Symbol.toStringTag,{value:"Module"})),$r=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
2222
- * Readium CSS v.2.0.0
2427
+ }`},Symbol.toStringTag,{value:"Module"})),Jr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
2428
+ * Readium CSS v.2.0.4
2223
2429
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
2224
2430
  * Use of this source code is governed by a BSD-style license which is detailed in the
2225
2431
  * LICENSE file present in the project repository where this source code is maintained.
@@ -2394,8 +2600,8 @@ th{
2394
2600
  th, td{
2395
2601
  padding:4px;
2396
2602
  border:1px solid currentcolor;
2397
- }`},Symbol.toStringTag,{value:"Module"})),Xr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
2398
- * Readium CSS v.2.0.0
2603
+ }`},Symbol.toStringTag,{value:"Module"})),Zr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
2604
+ * Readium CSS v.2.0.4
2399
2605
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
2400
2606
  * Use of this source code is governed by a BSD-style license which is detailed in the
2401
2607
  * LICENSE file present in the project repository where this source code is maintained.
@@ -2669,7 +2875,7 @@ body{
2669
2875
  :root[style*="--USER__lineHeight"] p,
2670
2876
  :root[style*="--USER__lineHeight"] li,
2671
2877
  :root[style*="--USER__lineHeight"] div{
2672
- line-height:inherit;
2878
+ line-height:var(--USER__lineHeight) !important;
2673
2879
  }
2674
2880
 
2675
2881
  :root[style*="--USER__paraSpacing"] p{
@@ -2705,8 +2911,8 @@ body{
2705
2911
  :root[style*="--USER__letterSpacing"] div,
2706
2912
  :root[style*="--USER__letterSpacing"] dt,
2707
2913
  :root[style*="--USER__letterSpacing"] dd{
2708
- letter-spacing:var(--USER__letterSpacing);
2709
- font-variant:none;
2914
+ letter-spacing:var(--USER__letterSpacing) !important;
2915
+ font-variant:none !important;
2710
2916
  }
2711
2917
 
2712
2918
  :root[style*="readium-noRuby-on"] body rt,
@@ -2880,8 +3086,8 @@ body{
2880
3086
 
2881
3087
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
2882
3088
  -webkit-text-zoom:normal;
2883
- }`},Symbol.toStringTag,{value:"Module"})),Yr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
2884
- * Readium CSS v.2.0.0
3089
+ }`},Symbol.toStringTag,{value:"Module"})),Qr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3090
+ * Readium CSS v.2.0.4
2885
3091
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
2886
3092
  * Use of this source code is governed by a BSD-style license which is detailed in the
2887
3093
  * LICENSE file present in the project repository where this source code is maintained.
@@ -2914,6 +3120,14 @@ body{
2914
3120
 
2915
3121
  :root{
2916
3122
 
3123
+ --RS__sans-serif-ja-v:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDGothic', 'Yu Gothic', 'MSゴシック', 'MS Gothic', sans-serif;
3124
+
3125
+ --RS__serif-ja-v:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDMincho', 'Yu Mincho', 'MS明朝', 'MS Mincho', serif;
3126
+
3127
+ --RS__sans-serif-ja:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDPGothic', 'Yu Gothic', 'MS Pゴシック', 'MS PGothic', sans-serif;
3128
+
3129
+ --RS__serif-ja:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDPMincho', 'Yu Mincho', 'MS P明朝', 'MS PMincho', serif;
3130
+
2917
3131
  --RS__monospaceTf:ui-monospace, 'Andale Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
2918
3132
 
2919
3133
  --RS__humanistTf:Seravek, Calibri, 'Gill Sans Nova', Roboto, Ubuntu, 'DejaVu Sans', source-sans-pro, sans-serif;
@@ -2923,9 +3137,106 @@ body{
2923
3137
  --RS__modernTf:Athelas, Constantia, Charter, 'Bitstream Charter', Cambria, 'Georgia Pro', Georgia, serif;
2924
3138
 
2925
3139
  --RS__oldStyleTf:'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif;
2926
- --RS__baseFontFamily:var(--RS__oldStyleTf);
2927
- --RS__lineHeightCompensation:1;
2928
3140
 
3141
+ --RS__zh-HK-lineHeightCompensation:1.167;
3142
+
3143
+ --RS__zh-HK-baseFontFamily:'方體', 'PingFang HK', '方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
3144
+
3145
+ --RS__zh-TW-lineHeightCompensation:1.167;
3146
+
3147
+ --RS__zh-TW-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
3148
+
3149
+ --RS__zh-Hant-lineHeightCompensation:1.167;
3150
+
3151
+ --RS__zh-Hant-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
3152
+
3153
+ --RS__zh-lineHeightCompensation:1.167;
3154
+
3155
+ --RS__zh-baseFontFamily:'方体', 'PingFang SC', '黑体', 'Heiti SC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK SC', sans-serif;
3156
+
3157
+ --RS__th-lineHeightCompensation:1.067;
3158
+
3159
+ --RS__th-baseFontFamily:Thonburi, 'Leelawadee UI', 'Cordia New', Roboto, Noto, 'Noto Sans Thai', sans-serif;
3160
+
3161
+ --RS__te-baseFontFamily:'Kohinoor Telugu', 'Telugu Sangam MN', 'Nirmala UI', Gautami, Roboto, Noto, 'Noto Sans Telugu', sans-serif;
3162
+
3163
+ --RS__ta-lineHeightCompensation:1.067;
3164
+
3165
+ --RS__ta-baseFontFamily:'Tamil Sangam MN', 'Nirmala UI', Latha, Roboto, Noto, 'Noto Sans Tamil', sans-serif;
3166
+
3167
+ --RS__si-lineHeightCompensation:1.167;
3168
+
3169
+ --RS__si-baseFontFamily:'Sinhala Sangam MN', 'Nirmala UI', 'Iskoola Pota', Roboto, Noto, 'Noto Sans Sinhala', sans-serif;
3170
+
3171
+ --RS__pa-lineHeightCompensation:1.1;
3172
+
3173
+ --RS__pa-baseFontFamily:'Gurmukhi MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Gurmukhi', sans-serif;
3174
+
3175
+ --RS__or-lineHeightCompensation:1.167;
3176
+
3177
+ --RS__or-baseFontFamily:'Oriya Sangam MN', 'Nirmala UI', Kalinga, Roboto, Noto, 'Noto Sans Oriya', sans-serif;
3178
+
3179
+ --RS__ml-lineHeightCompensation:1.067;
3180
+
3181
+ --RS__ml-baseFontFamily:'Malayalam Sangam MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Malayalam', sans-serif;
3182
+
3183
+ --RS__lo-baseFontFamily:'Lao Sangam MN', 'Leelawadee UI', 'Lao UI', Roboto, Noto, 'Noto Sans Lao', sans-serif;
3184
+
3185
+ --RS__ko-lineHeightCompensation:1.167;
3186
+
3187
+ --RS__ko-baseFontFamily:'Nanum Gothic', 'Apple SD Gothic Neo', 'Malgun Gothic', Roboto, Noto, 'Noto Sans CJK KR', sans-serif;
3188
+
3189
+ --RS__kn-lineHeightCompensation:1.1;
3190
+
3191
+ --RS__kn-baseFontFamily:'Kannada Sangam MN', 'Nirmala UI', Tunga, Roboto, Noto, 'Noto Sans Kannada', sans-serif;
3192
+
3193
+ --RS__km-lineHeightCompensation:1.067;
3194
+
3195
+ --RS__km-baseFontFamily:'Khmer Sangam MN', 'Leelawadee UI', 'Khmer UI', Roboto, Noto, 'Noto Sans Khmer', sans-serif;
3196
+
3197
+ --RS__ja-lineHeightCompensation:1.167;
3198
+
3199
+ --RS__ja-baseFontFamily:YuGothic, 'Hiragino Maru Gothic ProN', 'Hiragino Sans', 'Yu Gothic UI', 'Meiryo UI', 'MS Gothic', Roboto, Noto, 'Noto Sans CJK JP', sans-serif;
3200
+
3201
+ --RS__iu-baseFontFamily:'Euphemia UCAS', Euphemia, Roboto, Noto, 'Noto Sans Canadian Aboriginal', sans-serif;
3202
+
3203
+ --RS__hy-baseFontFamily:Mshtakan, Sylfaen, Roboto, Noto, 'Noto Serif Armenian', serif;
3204
+
3205
+ --RS__hi-lineHeightCompensation:1.1;
3206
+
3207
+ --RS__hi-baseFontFamily:'Kohinoor Devanagari', 'Devanagari Sangam MN', Kokila, 'Nirmala UI', Roboto, Noto, 'Noto Sans Devanagari', sans-serif;
3208
+
3209
+ --RS__he-lineHeightCompensation:1.1;
3210
+
3211
+ --RS__he-baseFontFamily:'New Peninim MT', 'Arial Hebrew', Gisha, 'Times New Roman', Roboto, Noto, 'Noto Sans Hebrew', sans-serif;
3212
+
3213
+ --RS__gu-lineHeightCompensation:1.167;
3214
+
3215
+ --RS__gu-baseFontFamily:'Gujarati Sangam MN', 'Nirmala UI', Shruti, Roboto, Noto, 'Noto Sans Gujarati', sans-serif;
3216
+
3217
+ --RS__fa-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
3218
+
3219
+ --RS__chr-lineHeightCompensation:1.167;
3220
+
3221
+ --RS__chr-baseFontFamily:'Plantagenet Cherokee', Roboto, Noto, 'Noto Sans Cherokee';
3222
+
3223
+ --RS__bo-baseFontFamily:Kailasa, 'Microsoft Himalaya', Roboto, Noto, 'Noto Sans Tibetan', sans-serif;
3224
+
3225
+ --RS__bn-lineHeightCompensation:1.067;
3226
+
3227
+ --RS__bn-baseFontFamily:'Kohinoor Bangla', 'Bangla Sangam MN', Vrinda, Roboto, Noto, 'Noto Sans Bengali', sans-serif;
3228
+
3229
+ --RS__ar-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
3230
+
3231
+ --RS__am-lineHeightCompensation:1.167;
3232
+
3233
+ --RS__am-baseFontFamily:Kefa, Nyala, Roboto, Noto, 'Noto Sans Ethiopic', serif;
3234
+
3235
+ --RS__default-lineHeightCompensation:1;
3236
+
3237
+ --RS__default-baseFontFamily:var(--RS__oldStyleTf);
3238
+ --RS__baseFontFamily:var(--RS__default-baseFontFamily);
3239
+ --RS__lineHeightCompensation:var(--RS__default-lineHeightCompensation);
2929
3240
  --RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));
2930
3241
 
2931
3242
  --RS__selectionTextColor:inherit;
@@ -2979,132 +3290,131 @@ math{
2979
3290
  }
2980
3291
 
2981
3292
  :lang(am){
2982
- --RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;
2983
- --RS__lineHeightCompensation:1.167;
3293
+ --RS__baseFontFamily:var(--RS__am-baseFontFamily);
3294
+ --RS__lineHeightCompensation:var(--RS__am-lineHeightCompensation);
2984
3295
  }
2985
3296
 
2986
3297
  :lang(ar){
2987
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
3298
+ --RS__baseFontFamily:var(--RS__ar-baseFontFamily);
2988
3299
  }
2989
3300
 
2990
3301
  :lang(bn){
2991
- --RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;
2992
- --RS__lineHeightCompensation:1.067;
3302
+ --RS__baseFontFamily:var(--RS__bn-baseFontFamily);
3303
+ --RS__lineHeightCompensation:var(--RS__bn-lineHeightCompensation);
2993
3304
  }
2994
3305
 
2995
3306
  :lang(bo){
2996
- --RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif;
3307
+ --RS__baseFontFamily:var(--RS__bo-baseFontFamily);
2997
3308
  }
2998
3309
 
2999
3310
  :lang(chr){
3000
- --RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";
3001
- --RS__lineHeightCompensation:1.167;
3311
+ --RS__baseFontFamily:var(--RS__chr-baseFontFamily);
3312
+ --RS__lineHeightCompensation:var(--RS__chr-lineHeightCompensation);
3002
3313
  }
3003
3314
 
3004
3315
  :lang(fa){
3005
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
3316
+ --RS__baseFontFamily:var(--RS__fa-baseFontFamily);
3006
3317
  }
3007
3318
 
3008
3319
  :lang(gu){
3009
- --RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;
3010
- --RS__lineHeightCompensation:1.167;
3320
+ --RS__baseFontFamily:var(--RS__gu-baseFontFamily);
3321
+ --RS__lineHeightCompensation:var(--RS__gu-lineHeightCompensation);
3011
3322
  }
3012
3323
 
3013
3324
  :lang(he){
3014
- --RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;
3015
- --RS__lineHeightCompensation:1.1;
3325
+ --RS__baseFontFamily:var(--RS__he-baseFontFamily);
3326
+ --RS__lineHeightCompensation:var(--RS__he-lineHeightCompensation);
3016
3327
  }
3017
3328
 
3018
3329
  :lang(hi){
3019
- --RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;
3020
-
3021
- --RS__lineHeightCompensation:1.1;
3330
+ --RS__baseFontFamily:var(--RS__hi-baseFontFamily);
3331
+ --RS__lineHeightCompensation:var(--RS__hi-lineHeightCompensation);
3022
3332
  }
3023
3333
 
3024
3334
  :lang(hy){
3025
- --RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif;
3335
+ --RS__baseFontFamily:var(--RS__hy-baseFontFamily);
3026
3336
  }
3027
3337
 
3028
3338
  :lang(iu){
3029
- --RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif;
3339
+ --RS__baseFontFamily:var(--RS__iu-baseFontFamily);
3030
3340
  }
3031
3341
 
3032
3342
  :lang(ja){
3033
- --RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;
3034
- --RS__lineHeightCompensation:1.167;
3035
- --RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;
3036
- --RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;
3037
- --RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;
3038
- --RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif;
3343
+ --RS__baseFontFamily:var(--RS__ja-baseFontFamily);
3344
+ --RS__lineHeightCompensation:var(--RS__ja-lineHeightCompensation);
3039
3345
  }
3040
3346
 
3041
3347
  :lang(km){
3042
- --RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;
3043
- --RS__lineHeightCompensation:1.067;
3348
+ --RS__baseFontFamily:var(--RS__km-baseFontFamily);
3349
+ --RS__lineHeightCompensation:var(--RS__km-lineHeightCompensation);
3044
3350
  }
3045
3351
 
3046
3352
  :lang(kn){
3047
- --RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;
3048
- --RS__lineHeightCompensation:1.1;
3353
+ --RS__baseFontFamily:var(--RS__kn-baseFontFamily);
3354
+ --RS__lineHeightCompensation:var(--RS__kn-lineHeightCompensation);
3049
3355
  }
3050
3356
 
3051
3357
  :lang(ko){
3052
- --RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;
3053
- --RS__lineHeightCompensation:1.167;
3358
+ --RS__baseFontFamily:var(--RS__ko-baseFontFamily);
3359
+ --RS__lineHeightCompensation:var(--RS__ko-lineHeightCompensation);
3054
3360
  }
3055
3361
 
3056
3362
  :lang(lo){
3057
- --RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif;
3363
+ --RS__baseFontFamily:var(--RS__lo-baseFontFamily);
3058
3364
  }
3059
3365
 
3060
3366
  :lang(ml){
3061
- --RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;
3062
- --RS__lineHeightCompensation:1.067;
3367
+ --RS__baseFontFamily:var(--RS__ml-baseFontFamily);
3368
+ --RS__lineHeightCompensation:var(--RS__ml-lineHeightCompensation);
3063
3369
  }
3064
3370
 
3065
3371
  :lang(or){
3066
- --RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;
3067
- --RS__lineHeightCompensation:1.167;
3372
+ --RS__baseFontFamily:var(--RS__or-baseFontFamily);
3373
+ --RS__lineHeightCompensation:var(--RS__or-lineHeightCompensation);
3068
3374
  }
3069
3375
 
3070
3376
  :lang(pa){
3071
- --RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;
3072
- --RS__lineHeightCompensation:1.1;
3377
+ --RS__baseFontFamily:var(--RS__pa-baseFontFamily);
3378
+ --RS__lineHeightCompensation:var(--RS__pa-lineHeightCompensation);
3073
3379
  }
3074
3380
 
3075
3381
  :lang(si){
3076
- --RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;
3077
- --RS__lineHeightCompensation:1.167;
3382
+ --RS__baseFontFamily:var(--RS__si-baseFontFamily);
3383
+ --RS__lineHeightCompensation:var(--RS__si-lineHeightCompensation);
3078
3384
  }
3079
3385
 
3080
3386
  :lang(ta){
3081
- --RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;
3082
- --RS__lineHeightCompensation:1.067;
3387
+ --RS__baseFontFamily:var(--RS__ta-baseFontFamily);
3388
+ --RS__lineHeightCompensation:var(--RS__ta-lineHeightCompensation);
3083
3389
  }
3084
3390
 
3085
3391
  :lang(te){
3086
- --RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif;
3392
+ --RS__baseFontFamily:var(--RS__te-baseFontFamily);
3087
3393
  }
3088
3394
 
3089
3395
  :lang(th){
3090
- --RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;
3091
- --RS__lineHeightCompensation:1.067;
3396
+ --RS__baseFontFamily:var(--RS__th-baseFontFamily);
3397
+ --RS__lineHeightCompensation:var(--RS__th-lineHeightCompensation);
3092
3398
  }
3093
3399
 
3094
3400
  :lang(zh){
3095
- --RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;
3096
- --RS__lineHeightCompensation:1.167;
3401
+ --RS__baseFontFamily:var(--RS__zh-baseFontFamily);
3402
+ --RS__lineHeightCompensation:var(--RS__zh-lineHeightCompensation);
3403
+ }
3404
+
3405
+ :lang(zh-Hant){
3406
+ --RS__baseFontFamily:var(--RS__zh-Hant-baseFontFamily);
3407
+ --RS__lineHeightCompensation:var(--RS__zh-Hant-lineHeightCompensation);
3097
3408
  }
3098
3409
 
3099
- :lang(zh-Hant),
3100
3410
  :lang(zh-TW){
3101
- --RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
3102
- --RS__lineHeightCompensation:1.167;
3411
+ --RS__baseFontFamily:var(--RS__zh-TW-baseFontFamily);
3412
+ --RS__lineHeightCompensation:var(--RS__zh-TW-lineHeightCompensation);
3103
3413
  }
3104
3414
 
3105
3415
  :lang(zh-HK){
3106
- --RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
3107
- --RS__lineHeightCompensation:1.167;
3416
+ --RS__baseFontFamily:var(--RS__zh-HK-baseFontFamily);
3417
+ --RS__lineHeightCompensation:var(--RS__zh-HK-lineHeightCompensation);
3108
3418
  }
3109
3419
 
3110
3420
  body{
@@ -3302,8 +3612,8 @@ audio{
3302
3612
  table{
3303
3613
  max-height:var(--RS__maxMediaWidth);
3304
3614
  box-sizing:var(--RS__boxSizingTable);
3305
- }`},Symbol.toStringTag,{value:"Module"})),qr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3306
- * Readium CSS v.2.0.0
3615
+ }`},Symbol.toStringTag,{value:"Module"})),ea=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3616
+ * Readium CSS v.2.0.4
3307
3617
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
3308
3618
  * Use of this source code is governed by a BSD-style license which is detailed in the
3309
3619
  * LICENSE file present in the project repository where this source code is maintained.
@@ -3481,8 +3791,8 @@ th{
3481
3791
  th, td{
3482
3792
  padding:4px;
3483
3793
  border:1px solid currentcolor;
3484
- }`},Symbol.toStringTag,{value:"Module"})),Kr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3485
- * Readium CSS v.2.0.0
3794
+ }`},Symbol.toStringTag,{value:"Module"})),ta=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3795
+ * Readium CSS v.2.0.4
3486
3796
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
3487
3797
  * Use of this source code is governed by a BSD-style license which is detailed in the
3488
3798
  * LICENSE file present in the project repository where this source code is maintained.
@@ -3741,7 +4051,7 @@ body{
3741
4051
  :root[style*="--USER__lineHeight"] p,
3742
4052
  :root[style*="--USER__lineHeight"] li,
3743
4053
  :root[style*="--USER__lineHeight"] div{
3744
- line-height:inherit;
4054
+ line-height:var(--USER__lineHeight) !important;
3745
4055
  }
3746
4056
 
3747
4057
  :root[style*="--USER__paraSpacing"] p{
@@ -3777,8 +4087,8 @@ body{
3777
4087
  :root[style*="--USER__letterSpacing"] div,
3778
4088
  :root[style*="--USER__letterSpacing"] dt,
3779
4089
  :root[style*="--USER__letterSpacing"] dd{
3780
- letter-spacing:var(--USER__letterSpacing);
3781
- font-variant:none;
4090
+ letter-spacing:var(--USER__letterSpacing) !important;
4091
+ font-variant:none !important;
3782
4092
  }
3783
4093
 
3784
4094
  :root[style*="readium-noRuby-on"] body rt,
@@ -3952,8 +4262,8 @@ body{
3952
4262
 
3953
4263
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
3954
4264
  -webkit-text-zoom:normal;
3955
- }`},Symbol.toStringTag,{value:"Module"})),Zr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
3956
- * Readium CSS v.2.0.0
4265
+ }`},Symbol.toStringTag,{value:"Module"})),na=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
4266
+ * Readium CSS v.2.0.4
3957
4267
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
3958
4268
  * Use of this source code is governed by a BSD-style license which is detailed in the
3959
4269
  * LICENSE file present in the project repository where this source code is maintained.
@@ -3986,6 +4296,14 @@ body{
3986
4296
 
3987
4297
  :root{
3988
4298
 
4299
+ --RS__sans-serif-ja-v:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDGothic', 'Yu Gothic', 'MSゴシック', 'MS Gothic', sans-serif;
4300
+
4301
+ --RS__serif-ja-v:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDMincho', 'Yu Mincho', 'MS明朝', 'MS Mincho', serif;
4302
+
4303
+ --RS__sans-serif-ja:'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Hiragino Kaku Gothic Pro', 'ヒラギノ角ゴ W3', 'YuGothic', 'Yu Gothic Medium', 'BIZ UDPGothic', 'Yu Gothic', 'MS Pゴシック', 'MS PGothic', sans-serif;
4304
+
4305
+ --RS__serif-ja:'Hiragino Mincho ProN', 'Hiragino Mincho Pro', 'YuMincho', 'BIZ UDPMincho', 'Yu Mincho', 'MS P明朝', 'MS PMincho', serif;
4306
+
3989
4307
  --RS__monospaceTf:ui-monospace, 'Andale Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
3990
4308
 
3991
4309
  --RS__humanistTf:Seravek, Calibri, 'Gill Sans Nova', Roboto, Ubuntu, 'DejaVu Sans', source-sans-pro, sans-serif;
@@ -3995,9 +4313,106 @@ body{
3995
4313
  --RS__modernTf:Athelas, Constantia, Charter, 'Bitstream Charter', Cambria, 'Georgia Pro', Georgia, serif;
3996
4314
 
3997
4315
  --RS__oldStyleTf:'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif;
3998
- --RS__baseFontFamily:var(--RS__oldStyleTf);
3999
- --RS__lineHeightCompensation:1;
4000
4316
 
4317
+ --RS__zh-HK-lineHeightCompensation:1.167;
4318
+
4319
+ --RS__zh-HK-baseFontFamily:'方體', 'PingFang HK', '方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
4320
+
4321
+ --RS__zh-TW-lineHeightCompensation:1.167;
4322
+
4323
+ --RS__zh-TW-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
4324
+
4325
+ --RS__zh-Hant-lineHeightCompensation:1.167;
4326
+
4327
+ --RS__zh-Hant-baseFontFamily:'方體', 'PingFang TC', '黑體', 'Heiti TC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK TC', sans-serif;
4328
+
4329
+ --RS__zh-lineHeightCompensation:1.167;
4330
+
4331
+ --RS__zh-baseFontFamily:'方体', 'PingFang SC', '黑体', 'Heiti SC', 'Microsoft JhengHei UI', 'Microsoft JhengHei', Roboto, Noto, 'Noto Sans CJK SC', sans-serif;
4332
+
4333
+ --RS__th-lineHeightCompensation:1.067;
4334
+
4335
+ --RS__th-baseFontFamily:Thonburi, 'Leelawadee UI', 'Cordia New', Roboto, Noto, 'Noto Sans Thai', sans-serif;
4336
+
4337
+ --RS__te-baseFontFamily:'Kohinoor Telugu', 'Telugu Sangam MN', 'Nirmala UI', Gautami, Roboto, Noto, 'Noto Sans Telugu', sans-serif;
4338
+
4339
+ --RS__ta-lineHeightCompensation:1.067;
4340
+
4341
+ --RS__ta-baseFontFamily:'Tamil Sangam MN', 'Nirmala UI', Latha, Roboto, Noto, 'Noto Sans Tamil', sans-serif;
4342
+
4343
+ --RS__si-lineHeightCompensation:1.167;
4344
+
4345
+ --RS__si-baseFontFamily:'Sinhala Sangam MN', 'Nirmala UI', 'Iskoola Pota', Roboto, Noto, 'Noto Sans Sinhala', sans-serif;
4346
+
4347
+ --RS__pa-lineHeightCompensation:1.1;
4348
+
4349
+ --RS__pa-baseFontFamily:'Gurmukhi MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Gurmukhi', sans-serif;
4350
+
4351
+ --RS__or-lineHeightCompensation:1.167;
4352
+
4353
+ --RS__or-baseFontFamily:'Oriya Sangam MN', 'Nirmala UI', Kalinga, Roboto, Noto, 'Noto Sans Oriya', sans-serif;
4354
+
4355
+ --RS__ml-lineHeightCompensation:1.067;
4356
+
4357
+ --RS__ml-baseFontFamily:'Malayalam Sangam MN', 'Nirmala UI', Kartika, Roboto, Noto, 'Noto Sans Malayalam', sans-serif;
4358
+
4359
+ --RS__lo-baseFontFamily:'Lao Sangam MN', 'Leelawadee UI', 'Lao UI', Roboto, Noto, 'Noto Sans Lao', sans-serif;
4360
+
4361
+ --RS__ko-lineHeightCompensation:1.167;
4362
+
4363
+ --RS__ko-baseFontFamily:'Nanum Gothic', 'Apple SD Gothic Neo', 'Malgun Gothic', Roboto, Noto, 'Noto Sans CJK KR', sans-serif;
4364
+
4365
+ --RS__kn-lineHeightCompensation:1.1;
4366
+
4367
+ --RS__kn-baseFontFamily:'Kannada Sangam MN', 'Nirmala UI', Tunga, Roboto, Noto, 'Noto Sans Kannada', sans-serif;
4368
+
4369
+ --RS__km-lineHeightCompensation:1.067;
4370
+
4371
+ --RS__km-baseFontFamily:'Khmer Sangam MN', 'Leelawadee UI', 'Khmer UI', Roboto, Noto, 'Noto Sans Khmer', sans-serif;
4372
+
4373
+ --RS__ja-lineHeightCompensation:1.167;
4374
+
4375
+ --RS__ja-baseFontFamily:YuGothic, 'Hiragino Maru Gothic ProN', 'Hiragino Sans', 'Yu Gothic UI', 'Meiryo UI', 'MS Gothic', Roboto, Noto, 'Noto Sans CJK JP', sans-serif;
4376
+
4377
+ --RS__iu-baseFontFamily:'Euphemia UCAS', Euphemia, Roboto, Noto, 'Noto Sans Canadian Aboriginal', sans-serif;
4378
+
4379
+ --RS__hy-baseFontFamily:Mshtakan, Sylfaen, Roboto, Noto, 'Noto Serif Armenian', serif;
4380
+
4381
+ --RS__hi-lineHeightCompensation:1.1;
4382
+
4383
+ --RS__hi-baseFontFamily:'Kohinoor Devanagari', 'Devanagari Sangam MN', Kokila, 'Nirmala UI', Roboto, Noto, 'Noto Sans Devanagari', sans-serif;
4384
+
4385
+ --RS__he-lineHeightCompensation:1.1;
4386
+
4387
+ --RS__he-baseFontFamily:'New Peninim MT', 'Arial Hebrew', Gisha, 'Times New Roman', Roboto, Noto, 'Noto Sans Hebrew', sans-serif;
4388
+
4389
+ --RS__gu-lineHeightCompensation:1.167;
4390
+
4391
+ --RS__gu-baseFontFamily:'Gujarati Sangam MN', 'Nirmala UI', Shruti, Roboto, Noto, 'Noto Sans Gujarati', sans-serif;
4392
+
4393
+ --RS__fa-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
4394
+
4395
+ --RS__chr-lineHeightCompensation:1.167;
4396
+
4397
+ --RS__chr-baseFontFamily:'Plantagenet Cherokee', Roboto, Noto, 'Noto Sans Cherokee';
4398
+
4399
+ --RS__bo-baseFontFamily:Kailasa, 'Microsoft Himalaya', Roboto, Noto, 'Noto Sans Tibetan', sans-serif;
4400
+
4401
+ --RS__bn-lineHeightCompensation:1.067;
4402
+
4403
+ --RS__bn-baseFontFamily:'Kohinoor Bangla', 'Bangla Sangam MN', Vrinda, Roboto, Noto, 'Noto Sans Bengali', sans-serif;
4404
+
4405
+ --RS__ar-baseFontFamily:'Geeza Pro', 'Arabic Typesetting', Roboto, Noto, 'Noto Naskh Arabic', 'Times New Roman', serif;
4406
+
4407
+ --RS__am-lineHeightCompensation:1.167;
4408
+
4409
+ --RS__am-baseFontFamily:Kefa, Nyala, Roboto, Noto, 'Noto Sans Ethiopic', serif;
4410
+
4411
+ --RS__default-lineHeightCompensation:1;
4412
+
4413
+ --RS__default-baseFontFamily:var(--RS__oldStyleTf);
4414
+ --RS__baseFontFamily:var(--RS__default-baseFontFamily);
4415
+ --RS__lineHeightCompensation:var(--RS__default-lineHeightCompensation);
4001
4416
  --RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));
4002
4417
 
4003
4418
  --RS__selectionTextColor:inherit;
@@ -4051,132 +4466,131 @@ math{
4051
4466
  }
4052
4467
 
4053
4468
  :lang(am){
4054
- --RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;
4055
- --RS__lineHeightCompensation:1.167;
4469
+ --RS__baseFontFamily:var(--RS__am-baseFontFamily);
4470
+ --RS__lineHeightCompensation:var(--RS__am-lineHeightCompensation);
4056
4471
  }
4057
4472
 
4058
4473
  :lang(ar){
4059
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
4474
+ --RS__baseFontFamily:var(--RS__ar-baseFontFamily);
4060
4475
  }
4061
4476
 
4062
4477
  :lang(bn){
4063
- --RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;
4064
- --RS__lineHeightCompensation:1.067;
4478
+ --RS__baseFontFamily:var(--RS__bn-baseFontFamily);
4479
+ --RS__lineHeightCompensation:var(--RS__bn-lineHeightCompensation);
4065
4480
  }
4066
4481
 
4067
4482
  :lang(bo){
4068
- --RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif;
4483
+ --RS__baseFontFamily:var(--RS__bo-baseFontFamily);
4069
4484
  }
4070
4485
 
4071
4486
  :lang(chr){
4072
- --RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";
4073
- --RS__lineHeightCompensation:1.167;
4487
+ --RS__baseFontFamily:var(--RS__chr-baseFontFamily);
4488
+ --RS__lineHeightCompensation:var(--RS__chr-lineHeightCompensation);
4074
4489
  }
4075
4490
 
4076
4491
  :lang(fa){
4077
- --RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif;
4492
+ --RS__baseFontFamily:var(--RS__fa-baseFontFamily);
4078
4493
  }
4079
4494
 
4080
4495
  :lang(gu){
4081
- --RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;
4082
- --RS__lineHeightCompensation:1.167;
4496
+ --RS__baseFontFamily:var(--RS__gu-baseFontFamily);
4497
+ --RS__lineHeightCompensation:var(--RS__gu-lineHeightCompensation);
4083
4498
  }
4084
4499
 
4085
4500
  :lang(he){
4086
- --RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;
4087
- --RS__lineHeightCompensation:1.1;
4501
+ --RS__baseFontFamily:var(--RS__he-baseFontFamily);
4502
+ --RS__lineHeightCompensation:var(--RS__he-lineHeightCompensation);
4088
4503
  }
4089
4504
 
4090
4505
  :lang(hi){
4091
- --RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;
4092
-
4093
- --RS__lineHeightCompensation:1.1;
4506
+ --RS__baseFontFamily:var(--RS__hi-baseFontFamily);
4507
+ --RS__lineHeightCompensation:var(--RS__hi-lineHeightCompensation);
4094
4508
  }
4095
4509
 
4096
4510
  :lang(hy){
4097
- --RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif;
4511
+ --RS__baseFontFamily:var(--RS__hy-baseFontFamily);
4098
4512
  }
4099
4513
 
4100
4514
  :lang(iu){
4101
- --RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif;
4515
+ --RS__baseFontFamily:var(--RS__iu-baseFontFamily);
4102
4516
  }
4103
4517
 
4104
4518
  :lang(ja){
4105
- --RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;
4106
- --RS__lineHeightCompensation:1.167;
4107
- --RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;
4108
- --RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;
4109
- --RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;
4110
- --RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif;
4519
+ --RS__baseFontFamily:var(--RS__ja-baseFontFamily);
4520
+ --RS__lineHeightCompensation:var(--RS__ja-lineHeightCompensation);
4111
4521
  }
4112
4522
 
4113
4523
  :lang(km){
4114
- --RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;
4115
- --RS__lineHeightCompensation:1.067;
4524
+ --RS__baseFontFamily:var(--RS__km-baseFontFamily);
4525
+ --RS__lineHeightCompensation:var(--RS__km-lineHeightCompensation);
4116
4526
  }
4117
4527
 
4118
4528
  :lang(kn){
4119
- --RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;
4120
- --RS__lineHeightCompensation:1.1;
4529
+ --RS__baseFontFamily:var(--RS__kn-baseFontFamily);
4530
+ --RS__lineHeightCompensation:var(--RS__kn-lineHeightCompensation);
4121
4531
  }
4122
4532
 
4123
4533
  :lang(ko){
4124
- --RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;
4125
- --RS__lineHeightCompensation:1.167;
4534
+ --RS__baseFontFamily:var(--RS__ko-baseFontFamily);
4535
+ --RS__lineHeightCompensation:var(--RS__ko-lineHeightCompensation);
4126
4536
  }
4127
4537
 
4128
4538
  :lang(lo){
4129
- --RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif;
4539
+ --RS__baseFontFamily:var(--RS__lo-baseFontFamily);
4130
4540
  }
4131
4541
 
4132
4542
  :lang(ml){
4133
- --RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;
4134
- --RS__lineHeightCompensation:1.067;
4543
+ --RS__baseFontFamily:var(--RS__ml-baseFontFamily);
4544
+ --RS__lineHeightCompensation:var(--RS__ml-lineHeightCompensation);
4135
4545
  }
4136
4546
 
4137
4547
  :lang(or){
4138
- --RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;
4139
- --RS__lineHeightCompensation:1.167;
4548
+ --RS__baseFontFamily:var(--RS__or-baseFontFamily);
4549
+ --RS__lineHeightCompensation:var(--RS__or-lineHeightCompensation);
4140
4550
  }
4141
4551
 
4142
4552
  :lang(pa){
4143
- --RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;
4144
- --RS__lineHeightCompensation:1.1;
4553
+ --RS__baseFontFamily:var(--RS__pa-baseFontFamily);
4554
+ --RS__lineHeightCompensation:var(--RS__pa-lineHeightCompensation);
4145
4555
  }
4146
4556
 
4147
4557
  :lang(si){
4148
- --RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;
4149
- --RS__lineHeightCompensation:1.167;
4558
+ --RS__baseFontFamily:var(--RS__si-baseFontFamily);
4559
+ --RS__lineHeightCompensation:var(--RS__si-lineHeightCompensation);
4150
4560
  }
4151
4561
 
4152
4562
  :lang(ta){
4153
- --RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;
4154
- --RS__lineHeightCompensation:1.067;
4563
+ --RS__baseFontFamily:var(--RS__ta-baseFontFamily);
4564
+ --RS__lineHeightCompensation:var(--RS__ta-lineHeightCompensation);
4155
4565
  }
4156
4566
 
4157
4567
  :lang(te){
4158
- --RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif;
4568
+ --RS__baseFontFamily:var(--RS__te-baseFontFamily);
4159
4569
  }
4160
4570
 
4161
4571
  :lang(th){
4162
- --RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;
4163
- --RS__lineHeightCompensation:1.067;
4572
+ --RS__baseFontFamily:var(--RS__th-baseFontFamily);
4573
+ --RS__lineHeightCompensation:var(--RS__th-lineHeightCompensation);
4164
4574
  }
4165
4575
 
4166
4576
  :lang(zh){
4167
- --RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;
4168
- --RS__lineHeightCompensation:1.167;
4577
+ --RS__baseFontFamily:var(--RS__zh-baseFontFamily);
4578
+ --RS__lineHeightCompensation:var(--RS__zh-lineHeightCompensation);
4579
+ }
4580
+
4581
+ :lang(zh-Hant){
4582
+ --RS__baseFontFamily:var(--RS__zh-Hant-baseFontFamily);
4583
+ --RS__lineHeightCompensation:var(--RS__zh-Hant-lineHeightCompensation);
4169
4584
  }
4170
4585
 
4171
- :lang(zh-Hant),
4172
4586
  :lang(zh-TW){
4173
- --RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
4174
- --RS__lineHeightCompensation:1.167;
4587
+ --RS__baseFontFamily:var(--RS__zh-TW-baseFontFamily);
4588
+ --RS__lineHeightCompensation:var(--RS__zh-TW-lineHeightCompensation);
4175
4589
  }
4176
4590
 
4177
4591
  :lang(zh-HK){
4178
- --RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;
4179
- --RS__lineHeightCompensation:1.167;
4592
+ --RS__baseFontFamily:var(--RS__zh-HK-baseFontFamily);
4593
+ --RS__lineHeightCompensation:var(--RS__zh-HK-lineHeightCompensation);
4180
4594
  }
4181
4595
 
4182
4596
  body{
@@ -4373,8 +4787,8 @@ audio{
4373
4787
  table{
4374
4788
  max-width:var(--RS__maxMediaWidth);
4375
4789
  box-sizing:var(--RS__boxSizingTable);
4376
- }`},Symbol.toStringTag,{value:"Module"})),Jr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
4377
- * Readium CSS v.2.0.0
4790
+ }`},Symbol.toStringTag,{value:"Module"})),ia=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
4791
+ * Readium CSS v.2.0.4
4378
4792
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
4379
4793
  * Use of this source code is governed by a BSD-style license which is detailed in the
4380
4794
  * LICENSE file present in the project repository where this source code is maintained.
@@ -4531,8 +4945,8 @@ th{
4531
4945
  th, td{
4532
4946
  padding:4px;
4533
4947
  border:1px solid currentcolor;
4534
- }`},Symbol.toStringTag,{value:"Module"})),Qr=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
4535
- * Readium CSS v.2.0.0
4948
+ }`},Symbol.toStringTag,{value:"Module"})),oa=Object.freeze(Object.defineProperty({__proto__:null,default:`/*!
4949
+ * Readium CSS v.2.0.4
4536
4950
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
4537
4951
  * Use of this source code is governed by a BSD-style license which is detailed in the
4538
4952
  * LICENSE file present in the project repository where this source code is maintained.
@@ -4780,11 +5194,11 @@ body{
4780
5194
  :root[style*="--USER__bodyHyphens"] li,
4781
5195
  :root[style*="--USER__bodyHyphens"] div,
4782
5196
  :root[style*="--USER__bodyHyphens"] dd{
4783
- -webkit-hyphens:inherit;
4784
- -moz-hyphens:inherit;
4785
- -ms-hyphens:inherit;
4786
- -epub-hyphens:inherit;
4787
- hyphens:inherit;
5197
+ -webkit-hyphens:var(--USER__bodyHyphens) !important;
5198
+ -moz-hyphens:var(--USER__bodyHyphens) !important;
5199
+ -ms-hyphens:var(--USER__bodyHyphens) !important;
5200
+ -epub-hyphens:var(--USER__bodyHyphens) !important;
5201
+ hyphens:var(--USER__bodyHyphens) !important;
4788
5202
  }
4789
5203
 
4790
5204
  :root[style*="--USER__fontFamily"]{
@@ -4875,7 +5289,7 @@ body{
4875
5289
  :root[style*="--USER__lineHeight"] p,
4876
5290
  :root[style*="--USER__lineHeight"] li,
4877
5291
  :root[style*="--USER__lineHeight"] div{
4878
- line-height:inherit;
5292
+ line-height:var(--USER__lineHeight) !important;
4879
5293
  }
4880
5294
 
4881
5295
  :root[style*="--USER__paraSpacing"] p{
@@ -4895,8 +5309,7 @@ body{
4895
5309
  text-indent:var(--USER__paraIndent) !important;
4896
5310
  }
4897
5311
 
4898
- :root[style*="--USER__paraIndent"] p *,
4899
- :root[style*="--USER__paraIndent"] p:first-letter{
5312
+ :root[style*="--USER__paraIndent"] p *{
4900
5313
  text-indent:0 !important;
4901
5314
  }
4902
5315
 
@@ -4911,7 +5324,7 @@ body{
4911
5324
  :root[style*="--USER__wordSpacing"] div,
4912
5325
  :root[style*="--USER__wordSpacing"] dt,
4913
5326
  :root[style*="--USER__wordSpacing"] dd{
4914
- word-spacing:var(--USER__wordSpacing);
5327
+ word-spacing:var(--USER__wordSpacing) !important;
4915
5328
  }
4916
5329
 
4917
5330
  :root[style*="--USER__letterSpacing"] h1,
@@ -4925,8 +5338,8 @@ body{
4925
5338
  :root[style*="--USER__letterSpacing"] div,
4926
5339
  :root[style*="--USER__letterSpacing"] dt,
4927
5340
  :root[style*="--USER__letterSpacing"] dd{
4928
- letter-spacing:var(--USER__letterSpacing);
4929
- font-variant:none;
5341
+ letter-spacing:var(--USER__letterSpacing) !important;
5342
+ font-variant:none !important;
4930
5343
  }
4931
5344
 
4932
5345
  :root[style*="--USER__ligatures"]{
@@ -5120,7 +5533,7 @@ body{
5120
5533
 
5121
5534
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
5122
5535
  -webkit-text-zoom:normal;
5123
- }`},Symbol.toStringTag,{value:"Module"})),ea=Object.freeze(Object.defineProperty({__proto__:null,default:`/* Readium CSS
5536
+ }`},Symbol.toStringTag,{value:"Module"})),ra=Object.freeze(Object.defineProperty({__proto__:null,default:`/* Readium CSS
5124
5537
  EBPAJ Fonts Patch module
5125
5538
 
5126
5539
  A stylesheet improving EBPAJ @font-face declarations to cover all platforms
@@ -5198,4 +5611,4 @@ body{
5198
5611
  local("YuGothic-Medium"), local("YuGothic"), /* 游ゴシック体(macOS) */
5199
5612
  local("Yu Gothic Medium"), local("Yu Gothic"), /* 游ゴシック(Windows) "Yu Gothic" is a fallback. */
5200
5613
  local("BIZ UDGothic"); /* BIZ UDゴシック */
5201
- }`},Symbol.toStringTag,{value:"Module"}));S.AudioDefaults=Xi,S.AudioNavigator=Mr,S.AudioPreferences=Ye,S.AudioPreferencesEditor=mn,S.AudioSettings=un,S.BooleanPreference=A,S.EnumPreference=Jt,S.EpubDefaults=ji,S.EpubNavigator=hn,S.EpubPreferences=ke,S.EpubPreferencesEditor=sn,S.EpubSettings=ln,S.ExperimentalWebPubNavigator=yr,S.FXLCoordinator=Mi,S.FXLFrameManager=Ai,S.FXLFramePoolManager=Bi,S.FXLPeripherals=Ii,S.FXLSpreader=Di,S.FrameComms=ve,S.FrameManager=rn,S.FramePoolManager=Oi,S.HorizontalThird=Ui,S.Injector=en,S.LineLengths=we,S.MediaNavigator=ai,S.Navigator=Vt,S.Orientation=gt,S.Preference=T,S.Properties=Ge,S.RSProperties=Gi,S.RangePreference=E,S.ReadiumCSS=Vi,S.Spread=ft,S.TextAlignment=Z,S.UserProperties=cn,S.VerticalThird=Ti,S.VisualNavigator=$t,S.WebAudioEngine=$i,S.WebPubBlobBuilder=si,S.WebPubCSS=fi,S.WebPubDefaults=bi,S.WebPubFrameManager=ui,S.WebPubFramePoolManager=mi,S.WebPubNavigator=Ci,S.WebPubPreferences=Pe,S.WebPubPreferencesEditor=Qt,S.WebPubSettings=Zt,S.WebRSProperties=gi,S.WebUserProperties=qt,S.ensureBoolean=P,S.ensureEnumValue=Ve,S.ensureExperiment=Kt,S.ensureFilter=he,S.ensureLessThanOrEqual=yi,S.ensureMoreThanOrEqual=Si,S.ensureNonNegative=v,S.ensureString=I,S.ensureValueInRange=M,S.experiments=ut,S.filterRangeConfig=le,S.fontSizeRangeConfig=Te,S.fontWeightRangeConfig=ee,S.fontWidthRangeConfig=Me,S.getScriptMode=se,S.letterSpacingRangeConfig=Fe,S.lineHeightRangeConfig=Ne,S.lineLengthRangeConfig=ce,S.paragraphIndentRangeConfig=Ie,S.paragraphSpacingRangeConfig=De,S.playbackRateRangeConfig=je,S.sML=q,S.sMLWithRequest=O,S.skipIntervalRangeConfig=te,S.volumeRangeConfig=Be,S.withFallback=mt,S.wordSpacingRangeConfig=He,S.zoomRangeConfig=We,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})}));
5614
+ }`},Symbol.toStringTag,{value:"Module"}));_.AudioDefaults=Ki,_.AudioNavigator=Dr,_.AudioPreferences=Xe,_.AudioPreferencesEditor=mn,_.AudioSettings=un,_.BooleanPreference=O,_.EnumPreference=Zt,_.EpubDefaults=ji,_.EpubNavigator=hn,_.EpubPreferences=Ce,_.EpubPreferencesEditor=sn,_.EpubSettings=ln,_.ExperimentalWebPubNavigator=wr,_.FXLCoordinator=Ti,_.FXLFrameManager=Oi,_.FXLFramePoolManager=Bi,_.FXLPeripherals=Ii,_.FXLSpreader=Hi,_.FrameComms=ve,_.FrameManager=rn,_.FramePoolManager=Li,_.HorizontalThird=Ai,_.Injector=en,_.LineLengths=we,_.MediaNavigator=ai,_.Navigator=Vt,_.Orientation=gt,_.Preference=U,_.Properties=Ge,_.RSProperties=Gi,_.RangePreference=k,_.ReadiumCSS=Vi,_.Spread=ft,_.TextAlignment=J,_.UserProperties=cn,_.VerticalThird=Ui,_.VisualNavigator=$t,_.WebAudioEngine=$i,_.WebPubBlobBuilder=si,_.WebPubCSS=fi,_.WebPubDefaults=Si,_.WebPubFrameManager=ui,_.WebPubFramePoolManager=mi,_.WebPubNavigator=Ei,_.WebPubPreferences=Re,_.WebPubPreferencesEditor=Qt,_.WebPubSettings=Jt,_.WebRSProperties=gi,_.WebUserProperties=Yt,_.ensureBoolean=R,_.ensureEnumValue=Ve,_.ensureExperiment=qt,_.ensureFilter=he,_.ensureLessThanOrEqual=yi,_.ensureMoreThanOrEqual=_i,_.ensureNonNegative=v,_.ensureString=I,_.ensureValueInRange=T,_.experiments=ut,_.filterRangeConfig=le,_.fontSizeRangeConfig=Ue,_.fontWeightRangeConfig=ee,_.fontWidthRangeConfig=Te,_.getScriptMode=se,_.i18n=rr,_.letterSpacingRangeConfig=Ne,_.lineHeightRangeConfig=Me,_.lineLengthRangeConfig=ce,_.paragraphIndentRangeConfig=Ie,_.paragraphSpacingRangeConfig=He,_.playbackRateRangeConfig=je,_.sML=Y,_.sMLWithRequest=L,_.settings=or,_.skipIntervalRangeConfig=te,_.volumeRangeConfig=Be,_.withFallback=mt,_.wordSpacingRangeConfig=De,_.zoomRangeConfig=We,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})}));