@readium/navigator 2.4.0-beta.8 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1307 -1253
- package/dist/index.umd.cjs +196 -133
- package/package.json +2 -2
- package/src/audio/AudioNavigator.ts +178 -52
- package/src/audio/AudioPoolManager.ts +27 -14
- package/src/audio/engine/AudioEngine.ts +4 -3
- package/src/audio/engine/PreservePitchProcessor.js +166 -101
- package/src/audio/engine/PreservePitchWorklet.ts +2 -17
- package/src/audio/engine/WebAudioEngine.ts +138 -160
- package/src/audio/engine/index.ts +2 -2
- package/src/audio/index.ts +3 -4
- package/src/audio/preferences/AudioDefaults.ts +2 -2
- package/src/audio/preferences/AudioPreferences.ts +11 -11
- package/src/audio/preferences/AudioPreferencesEditor.ts +13 -13
- package/src/audio/preferences/AudioSettings.ts +3 -3
- package/src/audio/preferences/index.ts +4 -4
- package/src/audio/protection/AudioNavigatorProtector.ts +4 -4
- package/src/css/index.ts +1 -1
- package/src/epub/EpubNavigator.ts +52 -52
- package/src/epub/css/Properties.ts +15 -15
- package/src/epub/css/ReadiumCSS.ts +43 -43
- package/src/epub/css/index.ts +2 -2
- package/src/epub/frame/FrameBlobBuilder.ts +10 -11
- package/src/epub/frame/FrameComms.ts +1 -1
- package/src/epub/frame/FrameManager.ts +9 -9
- package/src/epub/frame/FramePoolManager.ts +13 -13
- package/src/epub/frame/index.ts +4 -4
- package/src/epub/fxl/FXLCoordinator.ts +3 -3
- package/src/epub/fxl/FXLFrameManager.ts +8 -8
- package/src/epub/fxl/FXLFramePoolManager.ts +13 -13
- package/src/epub/fxl/FXLPeripherals.ts +4 -4
- package/src/epub/fxl/index.ts +5 -5
- package/src/epub/index.ts +5 -5
- package/src/epub/preferences/EpubDefaults.ts +23 -23
- package/src/epub/preferences/EpubPreferences.ts +16 -16
- package/src/epub/preferences/EpubPreferencesEditor.ts +53 -53
- package/src/epub/preferences/EpubSettings.ts +101 -101
- package/src/epub/preferences/index.ts +4 -4
- package/src/helpers/index.ts +2 -2
- package/src/index.ts +8 -9
- package/src/injection/Injector.ts +42 -42
- package/src/injection/epubInjectables.ts +8 -8
- package/src/injection/index.ts +2 -2
- package/src/injection/webpubInjectables.ts +1 -1
- package/src/preferences/Configurable.ts +2 -2
- package/src/preferences/PreferencesEditor.ts +2 -2
- package/src/preferences/guards.ts +2 -2
- package/src/preferences/index.ts +5 -5
- package/src/protection/CopyProtector.ts +5 -1
- package/src/protection/DevToolsDetector.ts +16 -16
- package/src/protection/DragAndDropProtector.ts +14 -1
- package/src/protection/NavigatorProtector.ts +6 -6
- package/src/webpub/WebPubBlobBuilder.ts +1 -1
- package/src/webpub/WebPubFrameManager.ts +8 -8
- package/src/webpub/WebPubFramePoolManager.ts +7 -7
- package/src/webpub/WebPubNavigator.ts +27 -27
- package/src/webpub/css/Properties.ts +3 -3
- package/src/webpub/css/WebPubCSS.ts +11 -11
- package/src/webpub/css/index.ts +2 -2
- package/src/webpub/index.ts +6 -6
- package/src/webpub/preferences/WebPubDefaults.ts +12 -12
- package/src/webpub/preferences/WebPubPreferences.ts +8 -8
- package/src/webpub/preferences/WebPubPreferencesEditor.ts +31 -31
- package/src/webpub/preferences/WebPubSettings.ts +45 -45
- package/src/webpub/preferences/index.ts +4 -4
- package/types/src/audio/AudioNavigator.d.ts +39 -9
- package/types/src/audio/AudioPoolManager.d.ts +7 -4
- package/types/src/audio/engine/AudioEngine.d.ts +4 -3
- package/types/src/audio/engine/PreservePitchWorklet.d.ts +1 -4
- package/types/src/audio/engine/WebAudioEngine.d.ts +15 -9
- package/types/src/audio/engine/index.d.ts +2 -2
- package/types/src/audio/index.d.ts +3 -4
- package/types/src/audio/preferences/AudioPreferences.d.ts +9 -9
- package/types/src/audio/preferences/AudioPreferencesEditor.d.ts +4 -4
- package/types/src/audio/preferences/AudioSettings.d.ts +3 -3
- package/types/src/audio/preferences/index.d.ts +4 -4
- package/types/src/audio/protection/AudioNavigatorProtector.d.ts +2 -2
- package/types/src/css/index.d.ts +1 -1
- package/types/src/epub/EpubNavigator.d.ts +11 -11
- package/types/src/epub/css/Properties.d.ts +2 -2
- package/types/src/epub/css/ReadiumCSS.d.ts +3 -3
- package/types/src/epub/css/index.d.ts +2 -2
- package/types/src/epub/frame/FrameBlobBuilder.d.ts +1 -1
- package/types/src/epub/frame/FrameComms.d.ts +1 -1
- package/types/src/epub/frame/FrameManager.d.ts +2 -2
- package/types/src/epub/frame/FramePoolManager.d.ts +3 -3
- package/types/src/epub/frame/index.d.ts +4 -4
- package/types/src/epub/fxl/FXLFrameManager.d.ts +3 -3
- package/types/src/epub/fxl/FXLFramePoolManager.d.ts +5 -5
- package/types/src/epub/fxl/FXLPeripherals.d.ts +2 -2
- package/types/src/epub/fxl/index.d.ts +5 -5
- package/types/src/epub/index.d.ts +5 -5
- package/types/src/epub/preferences/EpubDefaults.d.ts +1 -1
- package/types/src/epub/preferences/EpubPreferences.d.ts +2 -2
- package/types/src/epub/preferences/EpubPreferencesEditor.d.ts +5 -5
- package/types/src/epub/preferences/EpubSettings.d.ts +4 -4
- package/types/src/epub/preferences/index.d.ts +4 -4
- package/types/src/helpers/index.d.ts +2 -2
- package/types/src/index.d.ts +8 -9
- package/types/src/injection/Injector.d.ts +1 -1
- package/types/src/injection/epubInjectables.d.ts +1 -1
- package/types/src/injection/index.d.ts +2 -2
- package/types/src/preferences/Configurable.d.ts +1 -1
- package/types/src/preferences/PreferencesEditor.d.ts +1 -1
- package/types/src/preferences/guards.d.ts +1 -1
- package/types/src/preferences/index.d.ts +5 -5
- package/types/src/protection/CopyProtector.d.ts +1 -0
- package/types/src/protection/DragAndDropProtector.d.ts +2 -0
- package/types/src/protection/NavigatorProtector.d.ts +1 -1
- package/types/src/webpub/WebPubBlobBuilder.d.ts +1 -1
- package/types/src/webpub/WebPubFrameManager.d.ts +2 -2
- package/types/src/webpub/WebPubFramePoolManager.d.ts +3 -3
- package/types/src/webpub/WebPubNavigator.d.ts +10 -10
- package/types/src/webpub/css/Properties.d.ts +2 -2
- package/types/src/webpub/css/WebPubCSS.d.ts +2 -2
- package/types/src/webpub/css/index.d.ts +2 -2
- package/types/src/webpub/index.d.ts +6 -6
- package/types/src/webpub/preferences/WebPubDefaults.d.ts +1 -1
- package/types/src/webpub/preferences/WebPubPreferences.d.ts +2 -2
- package/types/src/webpub/preferences/WebPubPreferencesEditor.d.ts +5 -5
- package/types/src/webpub/preferences/WebPubSettings.d.ts +4 -4
- package/types/src/webpub/preferences/index.d.ts +4 -4
- package/src/Timeline.ts +0 -58
- package/src/audio/AudioTimeline.ts +0 -156
- package/types/src/Timeline.d.ts +0 -48
- package/types/src/audio/AudioTimeline.d.ts +0 -34
package/dist/index.umd.cjs
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
(function(y,pe){typeof exports=="object"&&typeof module<"u"?pe(exports):typeof define=="function"&&define.amd?define(["exports"],pe):(y=typeof globalThis<"u"?globalThis:y||self,pe(y.navigator={}))})(this,(function(y){"use strict";var re;const P=class P{constructor(e){this.uri=e}static deserialize(e){if(!(!e||typeof e!="string"))return new P(e)}serialize(){return this.uri}get isWCAGLevelA(){return this===P.EPUB_A11Y_10_WCAG_20_A||this===P.EPUB_A11Y_11_WCAG_20_A||this===P.EPUB_A11Y_11_WCAG_21_A||this===P.EPUB_A11Y_11_WCAG_22_A}get isWCAGLevelAA(){return this===P.EPUB_A11Y_10_WCAG_20_AA||this===P.EPUB_A11Y_11_WCAG_20_AA||this===P.EPUB_A11Y_11_WCAG_21_AA||this===P.EPUB_A11Y_11_WCAG_22_AA}get isWCAGLevelAAA(){return this===P.EPUB_A11Y_10_WCAG_20_AAA||this===P.EPUB_A11Y_11_WCAG_20_AAA||this===P.EPUB_A11Y_11_WCAG_21_AAA||this===P.EPUB_A11Y_11_WCAG_22_AAA}};P.EPUB_A11Y_10_WCAG_20_A=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"),P.EPUB_A11Y_10_WCAG_20_AA=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"),P.EPUB_A11Y_10_WCAG_20_AAA=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"),P.EPUB_A11Y_11_WCAG_20_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"),P.EPUB_A11Y_11_WCAG_20_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"),P.EPUB_A11Y_11_WCAG_20_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"),P.EPUB_A11Y_11_WCAG_21_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"),P.EPUB_A11Y_11_WCAG_21_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"),P.EPUB_A11Y_11_WCAG_21_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"),P.EPUB_A11Y_11_WCAG_22_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"),P.EPUB_A11Y_11_WCAG_22_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"),P.EPUB_A11Y_11_WCAG_22_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");let pe=P;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.AUDITORY=new x("auditory"),x.CHART_ON_VISUAL=new x("chartOnVisual"),x.CHEM_ON_VISUAL=new x("chemOnVisual"),x.COLOR_DEPENDENT=new x("colorDependent"),x.DIAGRAM_ON_VISUAL=new x("diagramOnVisual"),x.MATH_ON_VISUAL=new x("mathOnVisual"),x.MUSIC_ON_VISUAL=new x("musicOnVisual"),x.TACTILE=new x("tactile"),x.TEXT_ON_VISUAL=new x("textOnVisual"),x.TEXTUAL=new x("textual"),x.VISUAL=new x("visual");let ai=x;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(i=>D.VALID_MODES.has(i.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(i=>i?D.VALID_MODES.has(i.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 li=D;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.ANNOTATIONS=new f("annotations"),f.ARIA=new f("ARIA"),f.INDEX=new f("index"),f.PAGE_BREAK_MARKERS=new f("pageBreakMarkers"),f.PAGE_NAVIGATION=new f("pageNavigation"),f.PRINT_PAGE_NUMBERS=new f("printPageNumbers"),f.READING_ORDER=new f("readingOrder"),f.STRUCTURAL_NAVIGATION=new f("structuralNavigation"),f.TABLE_OF_CONTENTS=new f("tableOfContents"),f.TAGGED_PDF=new f("taggedPDF"),f.ALTERNATIVE_TEXT=new f("alternativeText"),f.AUDIO_DESCRIPTION=new f("audioDescription"),f.CAPTIONS=new f("captions"),f.CLOSED_CAPTIONS=new f("closedCaptions"),f.DESCRIBED_MATH=new f("describedMath"),f.LONG_DESCRIPTION=new f("longDescription"),f.OPEN_CAPTIONS=new f("openCaptions"),f.SIGN_LANGUAGE=new f("signLanguage"),f.TRANSCRIPT=new f("transcript"),f.DISPLAY_TRANSFORMABILITY=new f("displayTransformability"),f.SYNCHRONIZED_AUDIO_TEXT=new f("synchronizedAudioText"),f.TIMING_CONTROL=new f("timingControl"),f.UNLOCKED=new f("unlocked"),f.CHEM_ML=new f("ChemML"),f.LATEX=new f("latex"),f.LATEX_CHEMISTRY=new f("latex-chemistry"),f.MATH_ML=new f("MathML"),f.MATH_ML_CHEMISTRY=new f("MathML-chemistry"),f.TTS_MARKUP=new f("ttsMarkup"),f.HIGH_CONTRAST_AUDIO=new f("highContrastAudio"),f.HIGH_CONTRAST_DISPLAY=new f("highContrastDisplay"),f.LARGE_PRINT=new f("largePrint"),f.BRAILLE=new f("braille"),f.TACTILE_GRAPHIC=new f("tactileGraphic"),f.TACTILE_OBJECT=new f("tactileObject"),f.FULL_RUBY_ANNOTATIONS=new f("fullRubyAnnotations"),f.HORIZONTAL_WRITING=new f("horizontalWriting"),f.RUBY_ANNOTATIONS=new f("rubyAnnotations"),f.VERTICAL_WRITING=new f("verticalWriting"),f.WITH_ADDITIONAL_WORD_SEGMENTATION=new f("withAdditionalWordSegmentation"),f.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new f("withoutAdditionalWordSegmentation");let $e=f;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.FLASHING=new L("flashing"),L.NO_FLASHING_HAZARD=new L("noFlashingHazard"),L.UNKNOWN_FLASHING_HAZARD=new L("unknownFlashingHazard"),L.MOTION_SIMULATION=new L("motionSimulation"),L.NO_MOTION_SIMULATION_HAZARD=new L("noMotionSimulationHazard"),L.UNKNOWN_MOTION_SIMULATION_HAZARD=new L("unknownMotionSimulationHazard"),L.SOUND=new L("sound"),L.NO_SOUND_HAZARD=new L("noSoundHazard"),L.UNKNOWN_SOUND_HAZARD=new L("unknownSoundHazard"),L.UNKNOWN=new L("unknown"),L.NONE=new L("none");let ci=L;const R=class R{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new R(e)}serialize(){return this.value}};R.NONE=new R("none"),R.DOCUMENTED=new R("documented"),R.LEGAL=new R("legal"),R.TEMPORARY=new R("temporary"),R.TECHNICAL=new R("technical"),R.EAA_DISPROPORTIONATE_BURDEN=new R("eaa-disproportionate-burden"),R.EAA_FUNDAMENTAL_ALTERATION=new R("eaa-fundamental-alteration"),R.EAA_MICROENTERPRISE=new R("eaa-microenterprise"),R.EAA_TECHNICAL_IMPOSSIBILITY=new R("eaa-technical-impossibility"),R.EAA_TEMPORARY=new R("eaa-temporary");let hi=R;const di=["en","ar","da","fr","it","pt_PT","sv"],Zn={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"}}`)},ui={fr:()=>Promise.resolve().then(()=>Ro),ar:()=>Promise.resolve().then(()=>Ao),da:()=>Promise.resolve().then(()=>Oo),it:()=>Promise.resolve().then(()=>To),pt_PT:()=>Promise.resolve().then(()=>zo),sv:()=>Promise.resolve().then(()=>Mo)},pi=Zn?.publication?.metadata?.accessibility?.["display-guide"]||{};class me{constructor(){this.currentLocaleCode="en",this.locale=pi,this.loadedLocales={},this.loadedLocales.en=pi}static getInstance(){return me.instance||(me.instance=new me),me.instance}async loadLocale(e){if(!di.includes(e))return console.warn(`Locale '${e}' is not enabled`),!1;if(e in this.loadedLocales)return!0;try{if(!(e in ui))return console.warn(`Locale file not found for: ${e}`),!1;const n=(await ui[e]()).default?.publication?.metadata?.accessibility?.["display-guide"];return n?(this.loadedLocales[e]=n,!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 di}getNestedValue(e,t){const i=t.split(".");let n=e;for(const r of i){if(n==null)return;n=n[r]}return n}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:""})}}me.getInstance();var v=(o=>(o.reflowable="reflowable",o.fixed="fixed",o.scrolled="scrolled",o))(v||{});class mt{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 mt({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=(o=>(o.left="left",o.right="right",o.center="center",o))(X||{});let $=class si{constructor(e){this.otherProperties=e}get page(){return this.otherProperties.page}static deserialize(e){if(e)return new si(e)}serialize(){return this.otherProperties}add(e){const t=Object.assign({},this.otherProperties);for(const i in e)t[i]=e[i];return new si(t)}};Object.defineProperty($.prototype,"encryption",{get:function(){return mt.deserialize(this.otherProperties.encrypted)}});function Qn(o){return o&&Array.isArray(o)?o:void 0}function mi(o){return o&&typeof o=="string"?[o]:Qn(o)}function gi(o){return typeof o=="string"?new Date(o):void 0}function Ye(o){return isNaN(o)?void 0:o}function V(o){return Ye(o)!==void 0&&Math.sign(o)>=0?o:void 0}function er(o){const e=new Array;return o.forEach(t=>e.push(t)),e}class g{constructor(e){let t,i,n=e.mediaType.replace(/\s/g,"").split(";");const r=n[0].split("/");if(r.length===2){if(t=r[0].toLowerCase().trim(),i=r[1].toLowerCase().trim(),t.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let m=1;m<n.length;m++){const b=n[m].split("=");if(b.length===2){const d=b[0].toLocaleLowerCase(),p=d==="charset"?b[1].toUpperCase():b[1];s[d]=p}}const a={},l=Object.keys(s);l.sort((m,b)=>m.localeCompare(b)),l.forEach(m=>a[m]=s[m]);let c="";for(const m in a){const b=a[m];c+=`;${m}=${b}`}const h=`${t}/${i}${c}`,u=a.encoding;this.string=h,this.type=t,this.subtype=i,this.parameters=a,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 i=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),n=new Set(Object.entries(t.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(i.values()))if(!n.has(r))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 fi{constructor(e){this.uri=e,this.parameters=this.getParameters(e)}getParameters(e){const t=/\{\??([^}]+)\}/g,i=e.match(t);return i?new Set(i.join(",").replace(t,"$1").split(",").map(n=>n.trim())):new Set}expand(e){const t=n=>n.split(",").map(r=>{const s=e[r];return s?encodeURIComponent(s):""}).join(","),i=n=>"?"+n.split(",").map(r=>{const s=r.split("=")[0],a=e[s];return a?`${s}=${encodeURIComponent(a)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...n)=>n[1]?i(n[2]):t(n[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=Ye(e.progression),i=Ye(e.totalProgression),n=Ye(e.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(e).forEach(([a,l])=>{s.has(a)||r.set(a,l)}),new k({fragments:mi(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:n!==void 0&&n>0?n:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,i)=>e[i]=t),e}}class se{constructor(e){this.after=e.after,this.before=e.before,this.highlight=e.highlight}static deserialize(e){if(e)return new se({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 k({}),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:k.deserialize(e.locations),text:se.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 k({...this.locations,...e})})}}class j{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 j({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:$.deserialize(e.properties),height:V(e.height),width:V(e.width),size:V(e.size),duration:V(e.duration),bitrate:V(e.bitrate),languages:mi(e.language),alternates:qe.deserialize(e.alternate),children:qe.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=er(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 i=e||"/";return i.startsWith("/")&&(i="file://"+i),new URL(t,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new fi(this.href).parameters:new Set}expandTemplate(e){return new j({href:new fi(this.href).expand(e),templated:!1})}addProperties(e){const t=j.deserialize(this.serialize());return t.properties=t.properties?t.properties?.add(e):new $(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 k({fragments:e.length>1&&e[1]!==void 0?[e[1]]:[]})})}}class qe{constructor(e){this.items=e}static deserialize(e){if(e&&Array.isArray(e))return new qe(e.map(t=>j.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(e=>e.serialize())}findWithRel(e){const t=i=>i.rels&&i.rels.has(e);return this.items.find(t)}filterByRel(e){const t=i=>i.rels&&i.rels.has(e);return this.items.filter(t)}findWithHref(e){const t=i=>i.href===e;return this.items.find(t)}findIndexWithHref(e){const t=i=>i.href===e;return this.items.findIndex(t)}findWithMediaType(e){const t=i=>i.mediaType.matches(e);return this.items.find(t)}filterByMediaType(e){const t=i=>i.mediaType.matches(e);return this.items.filter(t)}filterByMediaTypes(e){const t=i=>{for(const n of e)if(i.mediaType.matches(n))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 i of e)return t.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(e))}filterLinksHasType(){return this.items.filter(e=>e.type)}}var yi=(o=>(o.EPUB="https://readium.org/webpub-manifest/profiles/epub",o.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",o.DIVINA="https://readium.org/webpub-manifest/profiles/divina",o.PDF="https://readium.org/webpub-manifest/profiles/pdf",o))(yi||{}),U=(o=>(o.ltr="ltr",o.rtl="rtl",o))(U||{});$.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class Ke{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=V(e.textNodeIndex);if(t===void 0)return;let i=V(e.charOffset);return i===void 0&&(i=V(e.offset)),new Ke({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:i})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}}class gt{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=Ke.deserialize(e.start);if(t)return new gt({start:t,end:Ke.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 gt.deserialize(this.otherLocations?.get("domRange"))},k.prototype.fragmentParameters=function(){return new Map(this.fragments.map(o=>o.startsWith("#")?o.slice(1):o).join("&").split("&").filter(o=>!o.startsWith("#")).map(o=>o.split("=")).filter(o=>o.length===2).map(o=>[o[0].trim().toLowerCase(),o[1].trim()]))},k.prototype.htmlId=function(){if(!this.fragments.length)return;let o=this.fragments.find(e=>e.length&&!e.includes("="));if(!o){const e=this.fragmentParameters();e.has("id")?o=e.get("id"):e.has("name")&&(o=e.get("name"))}return o?.startsWith("#")?o.slice(1):o},k.prototype.page=function(){const o=parseInt(this.fragmentParameters().get("page"));if(!isNaN(o)&&o>=0)return o},k.prototype.time=function(){const o=parseInt(this.fragmentParameters().get("t"));if(!isNaN(o))return o},k.prototype.space=function(){const o=this.fragmentParameters();if(!o.has("xywh"))return;const e=o.get("xywh").split(",").map(t=>parseInt(t));if(e.length===4&&!e.some(isNaN))return e};class ft{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 i=V(e.value);if(i!==void 0)return new ft({currency:t,value:i})}serialize(){return{currency:this.currency,value:this.value}}}class xe{constructor(e){this.type=e.type,this.children=e.children}static deserialize(e){if(e&&e.type)return new xe({type:e.type,children:xe.deserializeArray(e.children)})}static deserializeArray(e){if(Array.isArray(e))return e.map(t=>xe.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 yt{constructor(e){this.total=e.total,this.position=e.position}static deserialize(e){if(e)return new yt({total:V(e.total),position:V(e.position)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.position!==void 0&&(e.position=this.position),e}}class bt{constructor(e){this.total=e.total,this.available=e.available}static deserialize(e){if(e)return new bt({total:V(e.total),available:V(e.available)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.available!==void 0&&(e.available=this.available),e}}class vt{constructor(e){this.state=e.state,this.since=e.since,this.until=e.until}static deserialize(e){if(e&&e.state)return new vt({state:e.state,since:gi(e.since),until:gi(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}}$.prototype.getNumberOfItems=function(){return V(this.otherProperties.numberOfItems)},$.prototype.getPrice=function(){return ft.deserialize(this.otherProperties.price)},$.prototype.getIndirectAcquisitions=function(){const o=this.otherProperties.indirectAcquisition;if(o&&Array.isArray(o))return o.map(e=>xe.deserialize(e)).filter(e=>e!==void 0)},$.prototype.getHolds=function(){return yt.deserialize(this.otherProperties.holds)},$.prototype.getCopies=function(){return bt.deserialize(this.otherProperties.copies)},$.prototype.getAvailability=function(){return vt.deserialize(this.otherProperties.availability)},$.prototype.getAuthenticate=function(){return j.deserialize(this.otherProperties.authenticate)};const tr="CssSelectorGenerator";function bi(o="unknown problem",...e){console.warn(`${tr}: ${o}`,...e)}function ir(o){return o instanceof RegExp}function nr(o){return o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function rr(o){const e=o.map(t=>{if(ir(t))return i=>t.test(i);if(typeof t=="function")return i=>{const n=t(i);return typeof n!="boolean"?(bi("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):n};if(typeof t=="string"){const i=new RegExp("^"+nr(t)+"$");return n=>i.test(n)}return bi("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1});return t=>e.some(i=>i(t))}rr(["class","id","ng-*"]);const or=Math.pow(2,32),vi=()=>Math.round(Math.random()*or).toString(36),St=()=>`${Math.round(performance.now())}-${vi()}-${vi()}`,ge=1;class sr{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(i=>this.send("log",i)),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(i=>i.cb(e.data,n=>{this.send("_ack",n,e.id)}))}register(e,t,i){Array.isArray(e)||(e=[e]),e.forEach(n=>{const r=this.registrar.get(n);if(r&&r.length>=0){if(r.find(a=>a.module===t))throw new Error(`Trying to register another callback for combination of event ${n} and module ${t}`);r.push({cb:i,module:t}),this.registrar.set(n,r)}else this.registrar.set(n,[{cb:i,module:t}])})}unregister(e,t){Array.isArray(e)||(e=[e]),e.forEach(i=>{const n=this.registrar.get(i);!n||n.length===0||n.splice(n.findIndex(r=>r.module===t),1)})}unregisterAll(e){this.registrar.forEach((t,i)=>this.registrar.set(i,t.filter(n=>n.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,i=void 0,n=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const r={_readium:ge,_channel:this.channelId,id:i??St(),key:e,data:t};try{this.destination.postMessage(r,{targetOrigin:this.origin,transfer:n})}catch(s){if(n.length>0)throw s;this.destination.postMessage(r,this.origin,n)}}}class fe{}function Si(o){return o.split("").reverse().join("")}function ar(o,e,t){const i=Si(e);return t.map(n=>{const r=Math.max(0,n.end-e.length-n.errors),s=Si(o.slice(r,n.end));return{start:wi(s,i,n.errors).reduce((l,c)=>n.end-c.end<l?n.end-c.end:l,n.end),end:n.end,errors:n.errors}})}function _t(o){return(o|-o)>>31&1}function _i(o,e,t,i){let n=o.P[t],r=o.M[t];const s=i>>>31,a=e[t]|s,l=a|r,c=(a&n)+n^n|a;let h=r|~(c|n),u=n&c;const m=_t(h&o.lastRowMask[t])-_t(u&o.lastRowMask[t]);return h<<=1,u<<=1,u|=s,h|=_t(i)-s,n=u|~(l|h),r=h&l,o.P[t]=n,o.M[t]=r,m}function wi(o,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const i=[],n=32,r=Math.ceil(e.length/n)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(e.length-1)%n;const a=new Uint32Array(r+1),l=new Map,c=[];for(let m=0;m<256;m++)c.push(a);for(let m=0;m<e.length;m+=1){const b=e.charCodeAt(m);if(l.has(b))continue;const d=new Uint32Array(r+1);l.set(b,d),b<c.length&&(c[b]=d);for(let p=0;p<=r;p+=1){d[p]=0;for(let S=0;S<n;S+=1){const w=p*n+S;if(w>=e.length)continue;e.charCodeAt(w)===b&&(d[p]|=1<<S)}}}let h=Math.max(0,Math.ceil(t/n)-1);const u=new Uint32Array(r+1);for(let m=0;m<=h;m+=1)u[m]=(m+1)*n;u[r]=e.length;for(let m=0;m<=h;m+=1)s.P[m]=-1,s.M[m]=0;for(let m=0;m<o.length;m+=1){const b=o.charCodeAt(m);let d;b<c.length?d=c[b]:(d=l.get(b),typeof d>"u"&&(d=a));let p=0;for(let S=0;S<=h;S+=1)p=_i(s,d,S,p),u[S]+=p;if(u[h]-p<=t&&h<r&&(d[h+1]&1||p<0)){h+=1,s.P[h]=-1,s.M[h]=0;let S;if(h===r){const w=e.length%n;S=w===0?n:w}else S=n;u[h]=u[h-1]+S-p+_i(s,d,h,p)}else for(;h>0&&u[h]>=t+n;)h-=1;h===r&&u[h]<=t&&(u[h]<t&&i.splice(0,i.length),i.push({start:-1,end:m+1,errors:u[h]}),t=u[h])}return i}function lr(o,e,t){const i=wi(o,e,t);return ar(o,e,i)}function Pi(o,e,t){let i=0;const n=[];for(;i!==-1;)i=o.indexOf(e,i),i!==-1&&(n.push({start:i,end:i+e.length,errors:0}),i+=1);return n.length>0?n:lr(o,e,t)}function Ei(o,e){return e.length===0||o.length===0?0:1-Pi(o,e,e.length)[0].errors/e.length}function cr(o,e,t={}){if(e.length===0)return null;const i=Math.min(256,e.length/2),n=Pi(o,e,i);if(n.length===0)return null;const r=a=>{const m=1-a.errors/e.length,b=t.prefix?Ei(o.slice(Math.max(0,a.start-t.prefix.length),a.start),t.prefix):1,d=t.suffix?Ei(o.slice(a.end,a.end+t.suffix.length),t.suffix):1;let p=1;return typeof t.hint=="number"&&(p=1-Math.abs(a.start-t.hint)/o.length),(50*m+20*b+20*d+2*p)/92},s=n.map(a=>({start:a.start,end:a.end,score:r(a)}));return s.sort((a,l)=>l.score-a.score),s[0]}function wt(o,e,t){const i=t===1?e:e-1;if(o.charAt(i).trim()!=="")return e;let n,r;if(t===2?(n=o.substring(0,e),r=n.trimEnd()):(n=o.substring(e),r=n.trimStart()),!r.length)return-1;const s=n.length-r.length;return t===2?e-s:e+s}function ki(o,e){const t=o.commonAncestorContainer.ownerDocument.createNodeIterator(o.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=e===1?o.startContainer:o.endContainer,n=e===1?o.endContainer:o.startContainer;let r=t.nextNode();for(;r&&r!==i;)r=t.nextNode();e===2&&(r=t.previousNode());let s=-1;const a=()=>{if(r=e===1?t.nextNode():t.previousNode(),r){const l=r.textContent,c=e===1?0:l.length;s=wt(l,c,e)}};for(;r&&s===-1&&r!==n;)a();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function hr(o){if(!o.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(o.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(o.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=o.cloneRange();let t=!1,i=!1;const n={start:wt(o.startContainer.textContent,o.startOffset,1),end:wt(o.endContainer.textContent,o.endOffset,2)};if(n.start>=0&&(e.setStart(o.startContainer,n.start),t=!0),n.end>0&&(e.setEnd(o.endContainer,n.end),i=!0),t&&i)return e;if(!t){const{node:r,offset:s}=ki(e,1);r&&s>=0&&e.setStart(r,s)}if(!i){const{node:r,offset:s}=ki(e,2);r&&s>0&&e.setEnd(r,s)}return e}function Ci(o){switch(o.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return o.textContent?.length??0;default:return 0}}function xi(o){let e=o.previousSibling,t=0;for(;e;)t+=Ci(e),e=e.previousSibling;return t}function Li(o,...e){let t=e.shift();const i=o.ownerDocument.createNodeIterator(o,NodeFilter.SHOW_TEXT),n=[];let r=i.nextNode(),s,a=0;for(;t!==void 0&&r;)s=r,a+s.data.length>t?(n.push({node:s,offset:t-a}),t=e.shift()):(r=i.nextNode(),a+=s.data.length);for(;t!==void 0&&s&&a===t;)n.push({node:s,offset:s.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return n}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,i=this.offset;for(;t!==e;)i+=xi(t),t=t.parentElement;return new q(t,i)}resolve(e={}){try{return Li(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const n=e.direction===1,r=n?i.nextNode():i.previousNode();if(!r)throw t;return{node:r,offset:n?0:r.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 i=xi(e)+t;return new q(e.parentElement,i)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let n=0;n<t;n++)i+=Ci(e.childNodes[n]);return new q(e,i)}default:throw new Error("Point is not in an element or text node")}}}class ie{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new ie(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]=Li(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const i=new Range;return i.setStart(e.node,e.offset),i.setEnd(t.node,t.offset),i}static fromRange(e){const t=q.fromPoint(e.startContainer,e.startOffset),i=q.fromPoint(e.endContainer,e.endOffset);return new ie(t,i)}static fromOffsets(e,t,i){return new ie(new q(e,t),new q(e,i))}static trimmedRange(e){return hr(ie.fromRange(e).toRange())}}class Je{constructor(e,t,i){this.root=e,this.start=t,this.end=i}static fromRange(e,t){const i=ie.fromRange(t).relativeTo(e);return new Je(e,i.start.offset,i.end.offset)}static fromSelector(e,t){return new Je(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return ie.fromOffsets(this.root,this.start,this.end).toRange()}}class Ze{constructor(e,t,i={}){this.root=e,this.exact=t,this.context=i}static fromRange(e,t){const i=e.textContent,n=ie.fromRange(t).relativeTo(e),r=n.start.offset,s=n.end.offset,a=32;return new Ze(e,i.slice(r,s),{prefix:i.slice(Math.max(0,r-a),r),suffix:i.slice(s,Math.min(i.length,s+a))})}static fromSelector(e,t){const{prefix:i,suffix:n}=t;return new Ze(e,t.exact,{prefix:i,suffix:n})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const t=this.root.textContent,i=cr(t,this.exact,{...this.context,hint:e.hint});if(!i)throw new Error("Quote not found");return new Je(this.root,i.start,i.end)}}function dr(o){const e=o.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Qe(o,e){try{const t=e.locations,i=e.text;if(i&&i.highlight){let n;t&&t.getCssSelector()&&(n=o.querySelector(t.getCssSelector())),n||(n=o.body);const r=new Ze(n,i.highlight,{prefix:i.before,suffix:i.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(t){let n=null;if(!n&&t.getCssSelector()&&(n=o.querySelector(t.getCssSelector())),!n&&t.fragments){for(const r of t.fragments)if(n=o.getElementById(r),n)break}if(n){const r=o.createRange();return n.childNodes.length===0||dr(n)?(r.selectNode(n),r):(r.setStartBefore(n),r.setEndAfter(n),r)}}}catch(t){console.error(t)}return null}function ur(o,e){let t=o.getClientRects();t.length||o.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(t=o.commonAncestorContainer.getClientRects());const i=1,n=[];for(const c of t)n.push({bottom:c.bottom,height:c.height,left:c.left,right:c.right,top:c.top,width:c.width});const r=Ri(n,i),s=mr(r,i),a=Ai(s),l=4;for(let c=a.length-1;c>=0;c--){const h=a[c];if(!(h.width*h.height>l))if(a.length>1)a.splice(c,1);else break}return a}function Ri(o,e,t){for(let i=0;i<o.length;i++)for(let n=i+1;n<o.length;n++){const r=o[i],s=o[n];if(r===s)continue;const a=G(r.top,s.top,e)&&G(r.bottom,s.bottom,e),l=G(r.left,s.left,e)&&G(r.right,s.right,e);if(a&&!l&&Ti(r,s,e)){const u=o.filter(b=>b!==r&&b!==s),m=pr(r,s);return u.push(m),Ri(u,e)}}return o}function pr(o,e){const t=Math.min(o.left,e.left),i=Math.max(o.right,e.right),n=Math.min(o.top,e.top),r=Math.max(o.bottom,e.bottom);return{bottom:r,height:r-n,left:t,right:i,top:n,width:i-t}}function mr(o,e){const t=new Set(o);for(const i of o){if(!(i.width>1&&i.height>1)){t.delete(i);continue}for(const r of o)if(i!==r&&t.has(r)&&gr(r,i,e)){t.delete(i);break}}return Array.from(t)}function gr(o,e,t){return et(o,e.left,e.top,t)&&et(o,e.right,e.top,t)&&et(o,e.left,e.bottom,t)&&et(o,e.right,e.bottom,t)}function et(o,e,t,i){return(o.left<e||G(o.left,e,i))&&(o.right>e||G(o.right,e,i))&&(o.top<t||G(o.top,t,i))&&(o.bottom>t||G(o.bottom,t,i))}function Ai(o){for(let e=0;e<o.length;e++)for(let t=e+1;t<o.length;t++){const i=o[e],n=o[t];if(i!==n&&Ti(i,n,-1)){let r=[],s;const a=Oi(i,n);if(a.length===1)r=a,s=i;else{const c=Oi(n,i);a.length<c.length?(r=a,s=i):(r=c,s=n)}const l=o.filter(c=>c!==s);return Array.prototype.push.apply(l,r),Ai(l)}}return o}function Oi(o,e){const t=fr(e,o);if(t.height===0||t.width===0)return[o];const i=[];{const n={bottom:o.bottom,height:0,left:o.left,right:t.left,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:t.top,height:0,left:t.left,right:t.right,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:o.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:o.bottom,height:0,left:t.right,right:o.right,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}return i}function fr(o,e){const t=Math.max(o.left,e.left),i=Math.min(o.right,e.right),n=Math.max(o.top,e.top),r=Math.min(o.bottom,e.bottom);return{bottom:r,height:Math.max(0,r-n),left:t,right:i,top:n,width:Math.max(0,i-t)}}function Ti(o,e,t){return(o.left<e.right||t>=0&&G(o.left,e.right,t))&&(e.left<o.right||t>=0&&G(e.left,o.right,t))&&(o.top<e.bottom||t>=0&&G(o.top,e.bottom,t))&&(e.top<o.bottom||t>=0&&G(e.top,o.bottom,t))}function G(o,e,t){return Math.abs(o-e)<=t}function Pt(o){const e={},t=o.document.documentElement.style;for(const i in o.document.documentElement.style)Object.hasOwn(t,i)&&!Number.isNaN(Number.parseInt(i))&&(e[t[i]]=t.getPropertyValue(t[i]));return e}function zi(o,e){const t=Pt(o);Object.keys(t).forEach(i=>{e.hasOwnProperty(i)||tt(o,i)}),Object.entries(e).forEach(([i,n])=>{t[i]!==n&&Le(o,i,n)})}function Et(o,e){return o.document.documentElement.style.getPropertyValue(e)}function Le(o,e,t){o.document.documentElement.style.setProperty(e,t)}function tt(o,e){o.document.documentElement.style.removeProperty(e)}let it=null,kt=null,Re=0;const ye={r:255,g:255,b:255,a:1},be=new Map,yr=()=>{if(!it)if(typeof OffscreenCanvas<"u")it=new OffscreenCanvas(5,5),kt=it.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const o=document.createElement("canvas");o.width=5,o.height=5,it=o,kt=o.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return kt},br=o=>{if(!o)return!0;const e=o.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(n=>e.includes(n))},nt=(o,e)=>{console.warn(`[Decorator] Could not parse color: "${o}". ${e} Falling back to ${JSON.stringify(ye)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},Ct=(o,e=null)=>{const t=e?`${o}|${e}`:o,i=be.get(t);if(i!==void 0)return i??ye;if(br(o))return nt(o,"Unsupported color format or special value."),be.set(t,null),ye;const n=yr();if(!n)return nt(o,"Could not get canvas context."),be.set(t,null),ye;try{Re===0&&n.clearRect(0,0,5,5);const r=Re%5,s=Math.floor(Re/5);n.clearRect(r,s,1,1),e&&(n.fillStyle=e,n.fillRect(r,s,1,1)),n.fillStyle=o,n.fillRect(r,s,1,1);const a=n.getImageData(r,s,1,1);Re=(Re+1)%25;const[l,c,h,u]=a.data;if(u===0)return nt(o,"Fully transparent color."),be.set(t,null),ye;const m={r:l,g:c,b:h,a:u/255};return be.set(t,m),m}catch(r){return nt(o,`Error: ${r instanceof Error?r.message:String(r)}`),be.set(t,null),ye}},xt=o=>{const e=o/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},Mi=o=>{const e=xt(o.r),t=xt(o.g),i=xt(o.b);return .2126*e+.7152*t+.0722*i},Ii=(o,e)=>{const t=typeof o=="string"?Ct(o):o,i=typeof e=="string"?Ct(e):e,n=Mi(t),r=Mi(i),s=Math.max(n,r),a=Math.min(n,r);return(s+.05)/(a+.05)},Lt=(o,e=null)=>{const t=Ct(o,e),i=Ii(t,{r:255,g:255,b:255,a:1}),n=Ii(t,{r:0,g:0,b:0,a:1});return i>n},vr=(o,e=null)=>Lt(o,e)?"white":"black",Ni="#FFFF00",Sr=()=>"Highlight"in window,Fi=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class _r{constructor(e,t,i,n){this.wnd=e,this.comms=t,this.id=i,this.name=n,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,Sr()&&(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++}`,i=Qe(this.wnd.document,e.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",e);return}const n=i.commonAncestorContainer;n.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(Fi.includes(n.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),i.cloneContents().querySelector(Fi.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(n.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0));const r={decoration:e,id:t,range:i};this.items.push(r),this.layout(r),this.renderLayout([r])}remove(e){const t=this.items.findIndex(n=>n.decoration.id===e);if(t<0)return;const i=this.items[t];this.items.splice(t,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(i.range),this.notTextFlag?.delete(i.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,i]=this.requireContainer(!0);i.add(e.range);const n=Et(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"),r=e.decoration?.style?.tint??Ni;t.innerHTML=`
|
|
1
|
+
(function(y,ue){typeof exports=="object"&&typeof module<"u"?ue(exports):typeof define=="function"&&define.amd?define(["exports"],ue):(y=typeof globalThis<"u"?globalThis:y||self,ue(y.navigator={}))})(this,(function(y){"use strict";var ne;const P=class P{constructor(e){this.uri=e}static deserialize(e){if(!(!e||typeof e!="string"))return new P(e)}serialize(){return this.uri}get isWCAGLevelA(){return this===P.EPUB_A11Y_10_WCAG_20_A||this===P.EPUB_A11Y_11_WCAG_20_A||this===P.EPUB_A11Y_11_WCAG_21_A||this===P.EPUB_A11Y_11_WCAG_22_A}get isWCAGLevelAA(){return this===P.EPUB_A11Y_10_WCAG_20_AA||this===P.EPUB_A11Y_11_WCAG_20_AA||this===P.EPUB_A11Y_11_WCAG_21_AA||this===P.EPUB_A11Y_11_WCAG_22_AA}get isWCAGLevelAAA(){return this===P.EPUB_A11Y_10_WCAG_20_AAA||this===P.EPUB_A11Y_11_WCAG_20_AAA||this===P.EPUB_A11Y_11_WCAG_21_AAA||this===P.EPUB_A11Y_11_WCAG_22_AAA}};P.EPUB_A11Y_10_WCAG_20_A=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"),P.EPUB_A11Y_10_WCAG_20_AA=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"),P.EPUB_A11Y_10_WCAG_20_AAA=new P("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"),P.EPUB_A11Y_11_WCAG_20_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"),P.EPUB_A11Y_11_WCAG_20_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"),P.EPUB_A11Y_11_WCAG_20_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"),P.EPUB_A11Y_11_WCAG_21_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"),P.EPUB_A11Y_11_WCAG_21_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"),P.EPUB_A11Y_11_WCAG_21_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"),P.EPUB_A11Y_11_WCAG_22_A=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"),P.EPUB_A11Y_11_WCAG_22_AA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"),P.EPUB_A11Y_11_WCAG_22_AAA=new P("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");let ue=P;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.AUDITORY=new x("auditory"),x.CHART_ON_VISUAL=new x("chartOnVisual"),x.CHEM_ON_VISUAL=new x("chemOnVisual"),x.COLOR_DEPENDENT=new x("colorDependent"),x.DIAGRAM_ON_VISUAL=new x("diagramOnVisual"),x.MATH_ON_VISUAL=new x("mathOnVisual"),x.MUSIC_ON_VISUAL=new x("musicOnVisual"),x.TACTILE=new x("tactile"),x.TEXT_ON_VISUAL=new x("textOnVisual"),x.TEXTUAL=new x("textual"),x.VISUAL=new x("visual");let si=x;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(i=>D.VALID_MODES.has(i.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(i=>i?D.VALID_MODES.has(i.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 ai=D;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.ANNOTATIONS=new f("annotations"),f.ARIA=new f("ARIA"),f.INDEX=new f("index"),f.PAGE_BREAK_MARKERS=new f("pageBreakMarkers"),f.PAGE_NAVIGATION=new f("pageNavigation"),f.PRINT_PAGE_NUMBERS=new f("printPageNumbers"),f.READING_ORDER=new f("readingOrder"),f.STRUCTURAL_NAVIGATION=new f("structuralNavigation"),f.TABLE_OF_CONTENTS=new f("tableOfContents"),f.TAGGED_PDF=new f("taggedPDF"),f.ALTERNATIVE_TEXT=new f("alternativeText"),f.AUDIO_DESCRIPTION=new f("audioDescription"),f.CAPTIONS=new f("captions"),f.CLOSED_CAPTIONS=new f("closedCaptions"),f.DESCRIBED_MATH=new f("describedMath"),f.LONG_DESCRIPTION=new f("longDescription"),f.OPEN_CAPTIONS=new f("openCaptions"),f.SIGN_LANGUAGE=new f("signLanguage"),f.TRANSCRIPT=new f("transcript"),f.DISPLAY_TRANSFORMABILITY=new f("displayTransformability"),f.SYNCHRONIZED_AUDIO_TEXT=new f("synchronizedAudioText"),f.TIMING_CONTROL=new f("timingControl"),f.UNLOCKED=new f("unlocked"),f.CHEM_ML=new f("ChemML"),f.LATEX=new f("latex"),f.LATEX_CHEMISTRY=new f("latex-chemistry"),f.MATH_ML=new f("MathML"),f.MATH_ML_CHEMISTRY=new f("MathML-chemistry"),f.TTS_MARKUP=new f("ttsMarkup"),f.HIGH_CONTRAST_AUDIO=new f("highContrastAudio"),f.HIGH_CONTRAST_DISPLAY=new f("highContrastDisplay"),f.LARGE_PRINT=new f("largePrint"),f.BRAILLE=new f("braille"),f.TACTILE_GRAPHIC=new f("tactileGraphic"),f.TACTILE_OBJECT=new f("tactileObject"),f.FULL_RUBY_ANNOTATIONS=new f("fullRubyAnnotations"),f.HORIZONTAL_WRITING=new f("horizontalWriting"),f.RUBY_ANNOTATIONS=new f("rubyAnnotations"),f.VERTICAL_WRITING=new f("verticalWriting"),f.WITH_ADDITIONAL_WORD_SEGMENTATION=new f("withAdditionalWordSegmentation"),f.WITHOUT_ADDITIONAL_WORD_SEGMENTATION=new f("withoutAdditionalWordSegmentation");let $e=f;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.FLASHING=new L("flashing"),L.NO_FLASHING_HAZARD=new L("noFlashingHazard"),L.UNKNOWN_FLASHING_HAZARD=new L("unknownFlashingHazard"),L.MOTION_SIMULATION=new L("motionSimulation"),L.NO_MOTION_SIMULATION_HAZARD=new L("noMotionSimulationHazard"),L.UNKNOWN_MOTION_SIMULATION_HAZARD=new L("unknownMotionSimulationHazard"),L.SOUND=new L("sound"),L.NO_SOUND_HAZARD=new L("noSoundHazard"),L.UNKNOWN_SOUND_HAZARD=new L("unknownSoundHazard"),L.UNKNOWN=new L("unknown"),L.NONE=new L("none");let li=L;const R=class R{constructor(e){this.value=e}static deserialize(e){if(!(!e||typeof e!="string"))return new R(e)}serialize(){return this.value}};R.NONE=new R("none"),R.DOCUMENTED=new R("documented"),R.LEGAL=new R("legal"),R.TEMPORARY=new R("temporary"),R.TECHNICAL=new R("technical"),R.EAA_DISPROPORTIONATE_BURDEN=new R("eaa-disproportionate-burden"),R.EAA_FUNDAMENTAL_ALTERATION=new R("eaa-fundamental-alteration"),R.EAA_MICROENTERPRISE=new R("eaa-microenterprise"),R.EAA_TECHNICAL_IMPOSSIBILITY=new R("eaa-technical-impossibility"),R.EAA_TEMPORARY=new R("eaa-temporary");let ci=R;const hi=["en","ar","da","fr","it","pt_PT","sv"],Kn={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"}}`)},di={fr:()=>Promise.resolve().then(()=>xo),ar:()=>Promise.resolve().then(()=>Lo),da:()=>Promise.resolve().then(()=>Ro),it:()=>Promise.resolve().then(()=>Ao),pt_PT:()=>Promise.resolve().then(()=>Oo),sv:()=>Promise.resolve().then(()=>To)},ui=Kn?.publication?.metadata?.accessibility?.["display-guide"]||{};class pe{constructor(){this.currentLocaleCode="en",this.locale=ui,this.loadedLocales={},this.loadedLocales.en=ui}static getInstance(){return pe.instance||(pe.instance=new pe),pe.instance}async loadLocale(e){if(!hi.includes(e))return console.warn(`Locale '${e}' is not enabled`),!1;if(e in this.loadedLocales)return!0;try{if(!(e in di))return console.warn(`Locale file not found for: ${e}`),!1;const n=(await di[e]()).default?.publication?.metadata?.accessibility?.["display-guide"];return n?(this.loadedLocales[e]=n,!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 hi}getNestedValue(e,t){const i=t.split(".");let n=e;for(const r of i){if(n==null)return;n=n[r]}return n}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 v=(o=>(o.reflowable="reflowable",o.fixed="fixed",o.scrolled="scrolled",o))(v||{});class pt{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 pt({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 $=(o=>(o.left="left",o.right="right",o.center="center",o))($||{});let X=class oi{constructor(e){this.otherProperties=e}get page(){return this.otherProperties.page}static deserialize(e){if(e)return new oi(e)}serialize(){return this.otherProperties}add(e){const t=Object.assign({},this.otherProperties);for(const i in e)t[i]=e[i];return new oi(t)}};Object.defineProperty(X.prototype,"encryption",{get:function(){return pt.deserialize(this.otherProperties.encrypted)}});function Jn(o){return o&&Array.isArray(o)?o:void 0}function pi(o){return o&&typeof o=="string"?[o]:Jn(o)}function mi(o){return typeof o=="string"?new Date(o):void 0}function Xe(o){return isNaN(o)?void 0:o}function V(o){return Xe(o)!==void 0&&Math.sign(o)>=0?o:void 0}function Zn(o){const e=new Array;return o.forEach(t=>e.push(t)),e}class g{constructor(e){let t,i,n=e.mediaType.replace(/\s/g,"").split(";");const r=n[0].split("/");if(r.length===2){if(t=r[0].toLowerCase().trim(),i=r[1].toLowerCase().trim(),t.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let m=1;m<n.length;m++){const b=n[m].split("=");if(b.length===2){const d=b[0].toLocaleLowerCase(),p=d==="charset"?b[1].toUpperCase():b[1];s[d]=p}}const a={},l=Object.keys(s);l.sort((m,b)=>m.localeCompare(b)),l.forEach(m=>a[m]=s[m]);let c="";for(const m in a){const b=a[m];c+=`;${m}=${b}`}const h=`${t}/${i}${c}`,u=a.encoding;this.string=h,this.type=t,this.subtype=i,this.parameters=a,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 i=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),n=new Set(Object.entries(t.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(i.values()))if(!n.has(r))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 gi{constructor(e){this.uri=e,this.parameters=this.getParameters(e)}getParameters(e){const t=/\{\??([^}]+)\}/g,i=e.match(t);return i?new Set(i.join(",").replace(t,"$1").split(",").map(n=>n.trim())):new Set}expand(e){const t=n=>n.split(",").map(r=>{const s=e[r];return s?encodeURIComponent(s):""}).join(","),i=n=>"?"+n.split(",").map(r=>{const s=r.split("=")[0],a=e[s];return a?`${s}=${encodeURIComponent(a)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...n)=>n[1]?i(n[2]):t(n[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=Xe(e.progression),i=Xe(e.totalProgression),n=Xe(e.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(e).forEach(([a,l])=>{s.has(a)||r.set(a,l)}),new k({fragments:pi(e.fragments||e.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:n!==void 0&&n>0?n:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const e={};return this.fragments&&(e.fragments=this.fragments),this.progression!==void 0&&(e.progression=this.progression),this.totalProgression!==void 0&&(e.totalProgression=this.totalProgression),this.position!==void 0&&(e.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,i)=>e[i]=t),e}}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 j{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 j({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:V(e.height),width:V(e.width),size:V(e.size),duration:V(e.duration),bitrate:V(e.bitrate),languages:pi(e.language),alternates:qe.deserialize(e.alternate),children:qe.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=Zn(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 i=e||"/";return i.startsWith("/")&&(i="file://"+i),new URL(t,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new gi(this.href).parameters:new Set}expandTemplate(e){return new j({href:new gi(this.href).expand(e),templated:!1})}addProperties(e){const t=j.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 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 qe{constructor(e){this.items=e}static deserialize(e){if(e&&Array.isArray(e))return new qe(e.map(t=>j.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(e=>e.serialize())}findWithRel(e){const t=i=>i.rels&&i.rels.has(e);return this.items.find(t)}filterByRel(e){const t=i=>i.rels&&i.rels.has(e);return this.items.filter(t)}findWithHref(e){const t=i=>i.href===e;return this.items.find(t)}findIndexWithHref(e){const t=i=>i.href===e;return this.items.findIndex(t)}findWithMediaType(e){const t=i=>i.mediaType.matches(e);return this.items.find(t)}filterByMediaType(e){const t=i=>i.mediaType.matches(e);return this.items.filter(t)}filterByMediaTypes(e){const t=i=>{for(const n of e)if(i.mediaType.matches(n))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 i of e)return t.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(e))}filterLinksHasType(){return this.items.filter(e=>e.type)}}var fi=(o=>(o.EPUB="https://readium.org/webpub-manifest/profiles/epub",o.AUDIOBOOK="https://readium.org/webpub-manifest/profiles/audiobook",o.DIVINA="https://readium.org/webpub-manifest/profiles/divina",o.PDF="https://readium.org/webpub-manifest/profiles/pdf",o))(fi||{}),U=(o=>(o.ltr="ltr",o.rtl="rtl",o))(U||{});X.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])};class Ye{constructor(e){this.cssSelector=e.cssSelector,this.textNodeIndex=e.textNodeIndex,this.charOffset=e.charOffset}static deserialize(e){if(!(e&&e.cssSelector))return;let t=V(e.textNodeIndex);if(t===void 0)return;let i=V(e.charOffset);return i===void 0&&(i=V(e.offset)),new Ye({cssSelector:e.cssSelector,textNodeIndex:t,charOffset:i})}serialize(){const e={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(e.charOffset=this.charOffset),e}}class mt{constructor(e){this.start=e.start,this.end=e.end}static deserialize(e){if(!e)return;let t=Ye.deserialize(e.start);if(t)return new mt({start:t,end:Ye.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 mt.deserialize(this.otherLocations?.get("domRange"))},k.prototype.fragmentParameters=function(){return new Map(this.fragments.map(o=>o.startsWith("#")?o.slice(1):o).join("&").split("&").filter(o=>!o.startsWith("#")).map(o=>o.split("=")).filter(o=>o.length===2).map(o=>[o[0].trim().toLowerCase(),o[1].trim()]))},k.prototype.htmlId=function(){if(!this.fragments.length)return;let o=this.fragments.find(e=>e.length&&!e.includes("="));if(!o){const e=this.fragmentParameters();e.has("id")?o=e.get("id"):e.has("name")&&(o=e.get("name"))}return o?.startsWith("#")?o.slice(1):o},k.prototype.page=function(){const o=parseInt(this.fragmentParameters().get("page"));if(!isNaN(o)&&o>=0)return o},k.prototype.time=function(){const o=parseInt(this.fragmentParameters().get("t"));if(!isNaN(o))return o},k.prototype.space=function(){const o=this.fragmentParameters();if(!o.has("xywh"))return;const e=o.get("xywh").split(",").map(t=>parseInt(t));if(e.length===4&&!e.some(isNaN))return e};class gt{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 i=V(e.value);if(i!==void 0)return new gt({currency:t,value:i})}serialize(){return{currency:this.currency,value:this.value}}}class Ce{constructor(e){this.type=e.type,this.children=e.children}static deserialize(e){if(e&&e.type)return new Ce({type:e.type,children:Ce.deserializeArray(e.children)})}static deserializeArray(e){if(Array.isArray(e))return e.map(t=>Ce.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 ft{constructor(e){this.total=e.total,this.position=e.position}static deserialize(e){if(e)return new ft({total:V(e.total),position:V(e.position)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.position!==void 0&&(e.position=this.position),e}}class yt{constructor(e){this.total=e.total,this.available=e.available}static deserialize(e){if(e)return new yt({total:V(e.total),available:V(e.available)})}serialize(){const e={};return this.total!==void 0&&(e.total=this.total),this.available!==void 0&&(e.available=this.available),e}}class bt{constructor(e){this.state=e.state,this.since=e.since,this.until=e.until}static deserialize(e){if(e&&e.state)return new bt({state:e.state,since:mi(e.since),until:mi(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 V(this.otherProperties.numberOfItems)},X.prototype.getPrice=function(){return gt.deserialize(this.otherProperties.price)},X.prototype.getIndirectAcquisitions=function(){const o=this.otherProperties.indirectAcquisition;if(o&&Array.isArray(o))return o.map(e=>Ce.deserialize(e)).filter(e=>e!==void 0)},X.prototype.getHolds=function(){return ft.deserialize(this.otherProperties.holds)},X.prototype.getCopies=function(){return yt.deserialize(this.otherProperties.copies)},X.prototype.getAvailability=function(){return bt.deserialize(this.otherProperties.availability)},X.prototype.getAuthenticate=function(){return j.deserialize(this.otherProperties.authenticate)};const Qn="CssSelectorGenerator";function yi(o="unknown problem",...e){console.warn(`${Qn}: ${o}`,...e)}function er(o){return o instanceof RegExp}function tr(o){return o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function ir(o){const e=o.map(t=>{if(er(t))return i=>t.test(i);if(typeof t=="function")return i=>{const n=t(i);return typeof n!="boolean"?(yi("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):n};if(typeof t=="string"){const i=new RegExp("^"+tr(t)+"$");return n=>i.test(n)}return yi("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1});return t=>e.some(i=>i(t))}ir(["class","id","ng-*"]);const nr=Math.pow(2,32),bi=()=>Math.round(Math.random()*nr).toString(36),vt=()=>`${Math.round(performance.now())}-${bi()}-${bi()}`,me=1;class rr{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!==me){t._readium>me?this.send("error",`received comms version ${t._readium} higher than ${me}`):this.send("error",`received comms version ${t._readium} lower than ${me}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(i=>this.send("log",i)),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(i=>i.cb(e.data,n=>{this.send("_ack",n,e.id)}))}register(e,t,i){Array.isArray(e)||(e=[e]),e.forEach(n=>{const r=this.registrar.get(n);if(r&&r.length>=0){if(r.find(a=>a.module===t))throw new Error(`Trying to register another callback for combination of event ${n} and module ${t}`);r.push({cb:i,module:t}),this.registrar.set(n,r)}else this.registrar.set(n,[{cb:i,module:t}])})}unregister(e,t){Array.isArray(e)||(e=[e]),e.forEach(i=>{const n=this.registrar.get(i);!n||n.length===0||n.splice(n.findIndex(r=>r.module===t),1)})}unregisterAll(e){this.registrar.forEach((t,i)=>this.registrar.set(i,t.filter(n=>n.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,i=void 0,n=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const r={_readium:me,_channel:this.channelId,id:i??vt(),key:e,data:t};try{this.destination.postMessage(r,{targetOrigin:this.origin,transfer:n})}catch(s){if(n.length>0)throw s;this.destination.postMessage(r,this.origin,n)}}}class ge{}function vi(o){return o.split("").reverse().join("")}function or(o,e,t){const i=vi(e);return t.map(n=>{const r=Math.max(0,n.end-e.length-n.errors),s=vi(o.slice(r,n.end));return{start:_i(s,i,n.errors).reduce((l,c)=>n.end-c.end<l?n.end-c.end:l,n.end),end:n.end,errors:n.errors}})}function St(o){return(o|-o)>>31&1}function Si(o,e,t,i){let n=o.P[t],r=o.M[t];const s=i>>>31,a=e[t]|s,l=a|r,c=(a&n)+n^n|a;let h=r|~(c|n),u=n&c;const m=St(h&o.lastRowMask[t])-St(u&o.lastRowMask[t]);return h<<=1,u<<=1,u|=s,h|=St(i)-s,n=u|~(l|h),r=h&l,o.P[t]=n,o.M[t]=r,m}function _i(o,e,t){if(e.length===0)return[];t=Math.min(t,e.length);const i=[],n=32,r=Math.ceil(e.length/n)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(e.length-1)%n;const a=new Uint32Array(r+1),l=new Map,c=[];for(let m=0;m<256;m++)c.push(a);for(let m=0;m<e.length;m+=1){const b=e.charCodeAt(m);if(l.has(b))continue;const d=new Uint32Array(r+1);l.set(b,d),b<c.length&&(c[b]=d);for(let p=0;p<=r;p+=1){d[p]=0;for(let S=0;S<n;S+=1){const w=p*n+S;if(w>=e.length)continue;e.charCodeAt(w)===b&&(d[p]|=1<<S)}}}let h=Math.max(0,Math.ceil(t/n)-1);const u=new Uint32Array(r+1);for(let m=0;m<=h;m+=1)u[m]=(m+1)*n;u[r]=e.length;for(let m=0;m<=h;m+=1)s.P[m]=-1,s.M[m]=0;for(let m=0;m<o.length;m+=1){const b=o.charCodeAt(m);let d;b<c.length?d=c[b]:(d=l.get(b),typeof d>"u"&&(d=a));let p=0;for(let S=0;S<=h;S+=1)p=Si(s,d,S,p),u[S]+=p;if(u[h]-p<=t&&h<r&&(d[h+1]&1||p<0)){h+=1,s.P[h]=-1,s.M[h]=0;let S;if(h===r){const w=e.length%n;S=w===0?n:w}else S=n;u[h]=u[h-1]+S-p+Si(s,d,h,p)}else for(;h>0&&u[h]>=t+n;)h-=1;h===r&&u[h]<=t&&(u[h]<t&&i.splice(0,i.length),i.push({start:-1,end:m+1,errors:u[h]}),t=u[h])}return i}function sr(o,e,t){const i=_i(o,e,t);return or(o,e,i)}function wi(o,e,t){let i=0;const n=[];for(;i!==-1;)i=o.indexOf(e,i),i!==-1&&(n.push({start:i,end:i+e.length,errors:0}),i+=1);return n.length>0?n:sr(o,e,t)}function Pi(o,e){return e.length===0||o.length===0?0:1-wi(o,e,e.length)[0].errors/e.length}function ar(o,e,t={}){if(e.length===0)return null;const i=Math.min(256,e.length/2),n=wi(o,e,i);if(n.length===0)return null;const r=a=>{const m=1-a.errors/e.length,b=t.prefix?Pi(o.slice(Math.max(0,a.start-t.prefix.length),a.start),t.prefix):1,d=t.suffix?Pi(o.slice(a.end,a.end+t.suffix.length),t.suffix):1;let p=1;return typeof t.hint=="number"&&(p=1-Math.abs(a.start-t.hint)/o.length),(50*m+20*b+20*d+2*p)/92},s=n.map(a=>({start:a.start,end:a.end,score:r(a)}));return s.sort((a,l)=>l.score-a.score),s[0]}function _t(o,e,t){const i=t===1?e:e-1;if(o.charAt(i).trim()!=="")return e;let n,r;if(t===2?(n=o.substring(0,e),r=n.trimEnd()):(n=o.substring(e),r=n.trimStart()),!r.length)return-1;const s=n.length-r.length;return t===2?e-s:e+s}function Ei(o,e){const t=o.commonAncestorContainer.ownerDocument.createNodeIterator(o.commonAncestorContainer,NodeFilter.SHOW_TEXT),i=e===1?o.startContainer:o.endContainer,n=e===1?o.endContainer:o.startContainer;let r=t.nextNode();for(;r&&r!==i;)r=t.nextNode();e===2&&(r=t.previousNode());let s=-1;const a=()=>{if(r=e===1?t.nextNode():t.previousNode(),r){const l=r.textContent,c=e===1?0:l.length;s=_t(l,c,e)}};for(;r&&s===-1&&r!==n;)a();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function lr(o){if(!o.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(o.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(o.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const e=o.cloneRange();let t=!1,i=!1;const n={start:_t(o.startContainer.textContent,o.startOffset,1),end:_t(o.endContainer.textContent,o.endOffset,2)};if(n.start>=0&&(e.setStart(o.startContainer,n.start),t=!0),n.end>0&&(e.setEnd(o.endContainer,n.end),i=!0),t&&i)return e;if(!t){const{node:r,offset:s}=Ei(e,1);r&&s>=0&&e.setStart(r,s)}if(!i){const{node:r,offset:s}=Ei(e,2);r&&s>0&&e.setEnd(r,s)}return e}function ki(o){switch(o.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return o.textContent?.length??0;default:return 0}}function Ci(o){let e=o.previousSibling,t=0;for(;e;)t+=ki(e),e=e.previousSibling;return t}function xi(o,...e){let t=e.shift();const i=o.ownerDocument.createNodeIterator(o,NodeFilter.SHOW_TEXT),n=[];let r=i.nextNode(),s,a=0;for(;t!==void 0&&r;)s=r,a+s.data.length>t?(n.push({node:s,offset:t-a}),t=e.shift()):(r=i.nextNode(),a+=s.data.length);for(;t!==void 0&&s&&a===t;)n.push({node:s,offset:s.data.length}),t=e.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return n}class Y{constructor(e,t){if(t<0)throw new Error("Offset is invalid");this.element=e,this.offset=t}relativeTo(e){if(!e.contains(this.element))throw new Error("Parent is not an ancestor of current element");let t=this.element,i=this.offset;for(;t!==e;)i+=Ci(t),t=t.parentElement;return new Y(t,i)}resolve(e={}){try{return xi(this.element,this.offset)[0]}catch(t){if(this.offset===0&&e.direction!==void 0){const i=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);i.currentNode=this.element;const n=e.direction===1,r=n?i.nextNode():i.previousNode();if(!r)throw t;return{node:r,offset:n?0:r.data.length}}else throw t}}static fromCharOffset(e,t){switch(e.nodeType){case Node.TEXT_NODE:return Y.fromPoint(e,t);case Node.ELEMENT_NODE:return new Y(e,t);default:throw new Error("Node is not an element or text node")}}static fromPoint(e,t){switch(e.nodeType){case Node.TEXT_NODE:{if(t<0||t>e.data.length)throw new Error("Text node offset is out of range");if(!e.parentElement)throw new Error("Text node has no parent");const i=Ci(e)+t;return new Y(e.parentElement,i)}case Node.ELEMENT_NODE:{if(t<0||t>e.childNodes.length)throw new Error("Child node offset is out of range");let i=0;for(let n=0;n<t;n++)i+=ki(e.childNodes[n]);return new Y(e,i)}default:throw new Error("Point is not in an element or text node")}}}class ie{constructor(e,t){this.start=e,this.end=t}relativeTo(e){return new ie(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]=xi(this.start.element,this.start.offset,this.end.offset):(e=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const i=new Range;return i.setStart(e.node,e.offset),i.setEnd(t.node,t.offset),i}static fromRange(e){const t=Y.fromPoint(e.startContainer,e.startOffset),i=Y.fromPoint(e.endContainer,e.endOffset);return new ie(t,i)}static fromOffsets(e,t,i){return new ie(new Y(e,t),new Y(e,i))}static trimmedRange(e){return lr(ie.fromRange(e).toRange())}}class Ke{constructor(e,t,i){this.root=e,this.start=t,this.end=i}static fromRange(e,t){const i=ie.fromRange(t).relativeTo(e);return new Ke(e,i.start.offset,i.end.offset)}static fromSelector(e,t){return new Ke(e,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return ie.fromOffsets(this.root,this.start,this.end).toRange()}}class Je{constructor(e,t,i={}){this.root=e,this.exact=t,this.context=i}static fromRange(e,t){const i=e.textContent,n=ie.fromRange(t).relativeTo(e),r=n.start.offset,s=n.end.offset,a=32;return new Je(e,i.slice(r,s),{prefix:i.slice(Math.max(0,r-a),r),suffix:i.slice(s,Math.min(i.length,s+a))})}static fromSelector(e,t){const{prefix:i,suffix:n}=t;return new Je(e,t.exact,{prefix:i,suffix:n})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(e={}){return this.toPositionAnchor(e).toRange()}toPositionAnchor(e={}){const t=this.root.textContent,i=ar(t,this.exact,{...this.context,hint:e.hint});if(!i)throw new Error("Quote not found");return new Ke(this.root,i.start,i.end)}}function cr(o){const e=o.tagName.toUpperCase();return e==="IMG"||e==="VIDEO"||e==="AUDIO"||e==="IFRAME"||e==="OBJECT"||e==="EMBED"||e==="CANVAS"}function Ze(o,e){try{const t=e.locations,i=e.text;if(i&&i.highlight){let n;t&&t.getCssSelector()&&(n=o.querySelector(t.getCssSelector())),n||(n=o.body);const r=new Je(n,i.highlight,{prefix:i.before,suffix:i.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(t){let n=null;if(!n&&t.getCssSelector()&&(n=o.querySelector(t.getCssSelector())),!n&&t.fragments){for(const r of t.fragments)if(n=o.getElementById(r),n)break}if(n){const r=o.createRange();return n.childNodes.length===0||cr(n)?(r.selectNode(n),r):(r.setStartBefore(n),r.setEndAfter(n),r)}}}catch(t){console.error(t)}return null}function hr(o,e){let t=o.getClientRects();t.length||o.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(t=o.commonAncestorContainer.getClientRects());const i=1,n=[];for(const c of t)n.push({bottom:c.bottom,height:c.height,left:c.left,right:c.right,top:c.top,width:c.width});const r=Li(n,i),s=ur(r,i),a=Ri(s),l=4;for(let c=a.length-1;c>=0;c--){const h=a[c];if(!(h.width*h.height>l))if(a.length>1)a.splice(c,1);else break}return a}function Li(o,e,t){for(let i=0;i<o.length;i++)for(let n=i+1;n<o.length;n++){const r=o[i],s=o[n];if(r===s)continue;const a=G(r.top,s.top,e)&&G(r.bottom,s.bottom,e),l=G(r.left,s.left,e)&&G(r.right,s.right,e);if(a&&!l&&Oi(r,s,e)){const u=o.filter(b=>b!==r&&b!==s),m=dr(r,s);return u.push(m),Li(u,e)}}return o}function dr(o,e){const t=Math.min(o.left,e.left),i=Math.max(o.right,e.right),n=Math.min(o.top,e.top),r=Math.max(o.bottom,e.bottom);return{bottom:r,height:r-n,left:t,right:i,top:n,width:i-t}}function ur(o,e){const t=new Set(o);for(const i of o){if(!(i.width>1&&i.height>1)){t.delete(i);continue}for(const r of o)if(i!==r&&t.has(r)&&pr(r,i,e)){t.delete(i);break}}return Array.from(t)}function pr(o,e,t){return Qe(o,e.left,e.top,t)&&Qe(o,e.right,e.top,t)&&Qe(o,e.left,e.bottom,t)&&Qe(o,e.right,e.bottom,t)}function Qe(o,e,t,i){return(o.left<e||G(o.left,e,i))&&(o.right>e||G(o.right,e,i))&&(o.top<t||G(o.top,t,i))&&(o.bottom>t||G(o.bottom,t,i))}function Ri(o){for(let e=0;e<o.length;e++)for(let t=e+1;t<o.length;t++){const i=o[e],n=o[t];if(i!==n&&Oi(i,n,-1)){let r=[],s;const a=Ai(i,n);if(a.length===1)r=a,s=i;else{const c=Ai(n,i);a.length<c.length?(r=a,s=i):(r=c,s=n)}const l=o.filter(c=>c!==s);return Array.prototype.push.apply(l,r),Ri(l)}}return o}function Ai(o,e){const t=mr(e,o);if(t.height===0||t.width===0)return[o];const i=[];{const n={bottom:o.bottom,height:0,left:o.left,right:t.left,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:t.top,height:0,left:t.left,right:t.right,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:o.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}{const n={bottom:o.bottom,height:0,left:t.right,right:o.right,top:o.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&i.push(n)}return i}function mr(o,e){const t=Math.max(o.left,e.left),i=Math.min(o.right,e.right),n=Math.max(o.top,e.top),r=Math.min(o.bottom,e.bottom);return{bottom:r,height:Math.max(0,r-n),left:t,right:i,top:n,width:Math.max(0,i-t)}}function Oi(o,e,t){return(o.left<e.right||t>=0&&G(o.left,e.right,t))&&(e.left<o.right||t>=0&&G(e.left,o.right,t))&&(o.top<e.bottom||t>=0&&G(o.top,e.bottom,t))&&(e.top<o.bottom||t>=0&&G(e.top,o.bottom,t))}function G(o,e,t){return Math.abs(o-e)<=t}function wt(o){const e={},t=o.document.documentElement.style;for(const i in o.document.documentElement.style)Object.hasOwn(t,i)&&!Number.isNaN(Number.parseInt(i))&&(e[t[i]]=t.getPropertyValue(t[i]));return e}function Ti(o,e){const t=wt(o);Object.keys(t).forEach(i=>{e.hasOwnProperty(i)||et(o,i)}),Object.entries(e).forEach(([i,n])=>{t[i]!==n&&xe(o,i,n)})}function Pt(o,e){return o.document.documentElement.style.getPropertyValue(e)}function xe(o,e,t){o.document.documentElement.style.setProperty(e,t)}function et(o,e){o.document.documentElement.style.removeProperty(e)}let tt=null,Et=null,Le=0;const fe={r:255,g:255,b:255,a:1},ye=new Map,gr=()=>{if(!tt)if(typeof OffscreenCanvas<"u")tt=new OffscreenCanvas(5,5),Et=tt.getContext("2d",{willReadFrequently:!0,desynchronized:!0});else{const o=document.createElement("canvas");o.width=5,o.height=5,tt=o,Et=o.getContext("2d",{willReadFrequently:!0,desynchronized:!0})}return Et},fr=o=>{if(!o)return!0;const e=o.trim().toLowerCase();return e.startsWith("var(")||["transparent","currentcolor","inherit","initial","revert","unset","revert-layer"].includes(e)?!0:["linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"].some(n=>e.includes(n))},it=(o,e)=>{console.warn(`[Decorator] Could not parse color: "${o}". ${e} Falling back to ${JSON.stringify(fe)} to compute contrast. Please use a CSS color value that can be computed to RGB(A).`)},kt=(o,e=null)=>{const t=e?`${o}|${e}`:o,i=ye.get(t);if(i!==void 0)return i??fe;if(fr(o))return it(o,"Unsupported color format or special value."),ye.set(t,null),fe;const n=gr();if(!n)return it(o,"Could not get canvas context."),ye.set(t,null),fe;try{Le===0&&n.clearRect(0,0,5,5);const r=Le%5,s=Math.floor(Le/5);n.clearRect(r,s,1,1),e&&(n.fillStyle=e,n.fillRect(r,s,1,1)),n.fillStyle=o,n.fillRect(r,s,1,1);const a=n.getImageData(r,s,1,1);Le=(Le+1)%25;const[l,c,h,u]=a.data;if(u===0)return it(o,"Fully transparent color."),ye.set(t,null),fe;const m={r:l,g:c,b:h,a:u/255};return ye.set(t,m),m}catch(r){return it(o,`Error: ${r instanceof Error?r.message:String(r)}`),ye.set(t,null),fe}},Ct=o=>{const e=o/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)},zi=o=>{const e=Ct(o.r),t=Ct(o.g),i=Ct(o.b);return .2126*e+.7152*t+.0722*i},Mi=(o,e)=>{const t=typeof o=="string"?kt(o):o,i=typeof e=="string"?kt(e):e,n=zi(t),r=zi(i),s=Math.max(n,r),a=Math.min(n,r);return(s+.05)/(a+.05)},xt=(o,e=null)=>{const t=kt(o,e),i=Mi(t,{r:255,g:255,b:255,a:1}),n=Mi(t,{r:0,g:0,b:0,a:1});return i>n},yr=(o,e=null)=>xt(o,e)?"white":"black",Ii="#FFFF00",br=()=>"Highlight"in window,Fi=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class vr{constructor(e,t,i,n){this.wnd=e,this.comms=t,this.id=i,this.name=n,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,br()&&(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++}`,i=Ze(this.wnd.document,e.locator);if(!i){this.comms.log("Can't locate DOM range for decoration",e);return}const n=i.commonAncestorContainer;n.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(Fi.includes(n.nodeName.toUpperCase())&&this.notTextFlag?.set(t,!0),i.cloneContents().querySelector(Fi.join(", ").toLowerCase())&&this.notTextFlag?.set(t,!0),(n.textContent?.trim()||"").length===0&&this.notTextFlag?.set(t,!0));const r={decoration:e,id:t,range:i};this.items.push(r),this.layout(r),this.renderLayout([r])}remove(e){const t=this.items.findIndex(n=>n.decoration.id===e);if(t<0)return;const i=this.items[t];this.items.splice(t,1),i.clickableElements=void 0,i.container&&(i.container.remove(),i.container=void 0),this.experimentalHighlights&&!this.notTextFlag?.has(i.id)&&this.wnd.CSS.highlights.get(this.id)?.delete(i.range),this.notTextFlag?.delete(i.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,i]=this.requireContainer(!0);i.add(e.range);const n=Pt(this.wnd,"--USER__backgroundColor")||this.wnd.getComputedStyle(this.wnd.document.documentElement).getPropertyValue("background-color"),r=e.decoration?.style?.tint??Ii;t.innerHTML=`
|
|
2
2
|
::highlight(${this.id}) {
|
|
3
|
-
color: ${
|
|
3
|
+
color: ${yr(r,n)};
|
|
4
4
|
background-color: ${r};
|
|
5
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 i=this.wnd.innerWidth,n=parseInt(getComputedStyle(this.wnd.document.documentElement).getPropertyValue("column-count")),r=i/(n||1),s=this.wnd.document.scrollingElement,a=s.scrollLeft,l=s.scrollTop,c=(d,p,S)=>{if(d.style.position="absolute",e.decoration?.style?.width==="viewport"){d.style.width=`${i}px`,d.style.height=`${p.height}px`;let w=Math.floor(p.left/i)*i;d.style.left=`${w+a}px`,d.style.top=`${p.top+l}px`}else if(e.decoration?.style?.width==="bounds")d.style.width=`${S.width}px`,d.style.height=`${p.height}px`,d.style.left=`${S.left+a}px`,d.style.top=`${p.top+l}px`;else if(e.decoration?.style?.width==="page"){d.style.width=`${r}px`,d.style.height=`${p.height}px`;let w=Math.floor(p.left/r)*r;d.style.left=`${w+a}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+a}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
|
-
data-readium="true"
|
|
7
|
+
data-readium="true"
|
|
8
8
|
class="readium-highlight"
|
|
9
|
-
style="${[`background-color: ${e.decoration?.style?.tint??
|
|
9
|
+
style="${[`background-color: ${e.decoration?.style?.tint??Ii} !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 b=u.content.firstElementChild;if(e.decoration?.style?.layout==="bounds"){const d=b.cloneNode(!0);d.style.setProperty("pointer-events","none"),c(d,h,h),t.append(d)}else{let d=
|
|
12
|
+
`.trim();const b=u.content.firstElementChild;if(e.decoration?.style?.layout==="bounds"){const d=b.cloneNode(!0);d.style.setProperty("pointer-events","none"),c(d,h,h),t.append(d)}else{let d=hr(e.range);d=d.sort((p,S)=>p.top<S.top?-1:p.top>S.top?1:0);for(let p of d){const S=b.cloneNode(!0);S.style.setProperty("pointer-events","none"),c(S,p,h),t.append(S)}}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(i=>!this.experimentalHighlights||!!this.notTextFlag?.has(i.id)),!e||e.length===0)return;this.requireContainer().append(...e.map(i=>i.container).filter(i=>!!i))})}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 i;return this.wnd.CSS.highlights.has(this.id)?i=this.wnd.CSS.highlights.get(this.id):(i=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,i)),[t,i]}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 Pt(this.wnd,"--USER__appearance")==="readium-night-on"||xt(Pt(this.wnd,"--USER__backgroundColor"))||xt(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 Ve=class Ve extends ge{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 i=e.match(new RegExp(`${t}:\\s*([^;]+)`));return i?i[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",Ve.moduleName,(i,n)=>{const r=i;r.decoration&&r.decoration.locator&&(r.decoration.locator=F.deserialize(r.decoration.locator)),this.groups.has(r.group)||this.groups.set(r.group,new vr(e,t,`readium-decoration-${this.lastGroupId++}`,r.group));const s=this.groups.get(r.group);switch(r.action){case"add":s?.add(r.decoration);break;case"remove":s?.remove(r.decoration.id);break;case"clear":s?.clear();break;case"update":s?.update(r.decoration);break}n(!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(i=>{i.some(r=>{if(r.type==="attributes"&&r.attributeName==="style"){const s=r.target,a=r.oldValue,l=s.getAttribute("style"),c=this.extractCustomProperty(a,"--USER__appearance"),h=this.extractCustomProperty(l,"--USER__appearance"),u=this.extractCustomProperty(a,"--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(Ve.moduleName),this.resizeObserver.disconnect(),this.backgroundObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}};Ve.moduleName="decorator";let Lt=Ve;const Ni="readium-snapper-style",je=class je extends ge{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 i=e.document.createElement("style");return i.dataset.readium="true",i.id=
|
|
16
|
+
}`}mount(e,t){const i=e.document.createElement("style");return i.dataset.readium="true",i.id=Ni,i.textContent=this.buildStyles(),e.document.head.appendChild(i),t.register("protect",je.moduleName,(n,r)=>{this.protected=!0,i.textContent=this.buildStyles(),r(!0)}),t.register("unprotect",je.moduleName,(n,r)=>{this.protected=!1,i.textContent=this.buildStyles(),r(!0)}),t.log("Snapper Mounted"),!0}unmount(e,t){return e.document.getElementById(Ni)?.remove(),t.log("Snapper Unmounted"),!0}};je.moduleName="snapper";let Re=je;function se(o){return o.document.body.dir.toLowerCase()==="rtl"}function Ui(o){return parseInt(o.getComputedStyle(o.document.documentElement).getPropertyValue("column-count"))}function Di(o){const e=getComputedStyle(o),t=parseFloat(e.paddingTop||"0"),i=parseFloat(e.paddingBottom||"0");return o.clientHeight-t-i}function Wi(o){const e=Ui(o);if(!e)return!1;const t=o.document.querySelectorAll("div[id^='readium-virtual-page']");for(const c of t)c.remove();const i=t.length,n=o.document.scrollingElement.scrollWidth,r=o.visualViewport.width,a=Math.round(n/r*e)%e,l=e===1||a===0?0:e-a;if(l>0)for(let c=0;c<l;c++){const h=o.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=Di(o.document.documentElement)+"px"),h.innerHTML="​",o.document.body.appendChild(h)}return i!==l}function Hi(o){const e=o.document.createElement("style");e.appendChild(o.document.createTextNode("*{}")),o.document.body.appendChild(e),o.document.body.removeChild(e)}function Sr(o){return o<.5?2*o*o:-1+(4-2*o)*o}function I(o){const e=o.getSelection();e&&e.removeAllRanges()}const _r=["a","audio","button","canvas","details","input","label","option","select","submit","textarea","video"];function Bi(o){return _r.indexOf(o.nodeName.toLowerCase())!==-1||o.hasAttribute("contenteditable")&&o.getAttribute("contenteditable")?.toLowerCase()!=="false"?o:o.parentElement?Bi(o.parentElement):null}function Rt(o,e){const t=Vi(o,o.document.body,e),i=o._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",i]])}),text:new oe({highlight:t.textContent||void 0})})}function Vi(o,e,t){for(var i=0;i<e.children.length;i++){const n=e.children[i];if(!Er(n)&&wr(o,n,t))return Pr(o,n)?n:Vi(o,n,t)}return e}function wr(o,e,t){if(e===document.body||e===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const i=e.getBoundingClientRect();return t?i.bottom>0&&i.top<o.innerHeight:i.right>0&&i.left<o.innerWidth}function Pr(o,e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=o.innerHeight&&t.right<=o.innerWidth}function Er(o){const e=getComputedStyle(o);if(e){const t=e.getPropertyValue("display");if(t!="block"&&t!="list-item"||e.getPropertyValue("opacity")==="0")return!0}return!1}const kr={maxVelocity:200,minVariance:.01,historySize:20,minDirectionChanges:.2,maxConsistentScrolls:15},ji={maxVelocity:200,minVariance:1e-5,historySize:100,minDirectionChanges:.1,maxConsistentScrolls:20},Gi={maxSelectionsPerSecond:500,minVariance:50,historySize:20},Cr={enabled:!0,maxSelectionPercent:.1,minThreshold:100,absoluteMaxChars:5e3,historySize:20};class At{constructor(e={}){this.history=[],this.consistentScrollCount=0,this.options={...kr,...e}}analyze(e,t,i){if(i<=0)return!1;const n=Math.abs(t)/i,r=Date.now();if(this.history.push({timestamp:r,direction:e,velocity:n,distance:Math.abs(t)}),this.history=this.history.filter(p=>r-p.timestamp<2e3).slice(-(this.options.historySize||20)),this.history.length<3)return!1;if(n>this.options.maxVelocity)return this.resetAfterDetection(),!0;const s=this.history.map(p=>p.velocity),a=this.history.map(p=>p.distance),l=s.reduce((p,S)=>p+S,0)/s.length,c=a.reduce((p,S)=>p+S,0)/a.length,h=s.reduce((p,S)=>p+Math.pow(S-l,2),0)/s.length,u=a.reduce((p,S)=>p+Math.pow(S-c,2),0)/a.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,b=this.history[0].direction;for(let p=1;p<this.history.length;p++)this.history[p].direction!==b&&(m++,b=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 $i="readium-column-snapper-style",xr=200,W=class W extends Re{constructor(){super(...arguments),this.isSnapProtectionEnabled=!1,this.patternAnalyzer=null,this.lastTurnTime=0,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(){return this.doc().scrollLeft>0?this.doc().scrollLeft:this.alreadyScrollLeft}snapOffset(e){const t=e+(se(this.wnd)?-1:1);return t-t%this.wnd.innerWidth}reportProgress(){const e=this.wnd.scrollX,t=this.cachedScrollWidth,i=Math.max(0,Math.min(1,e/t)),n=Math.max(0,Math.min(1,(e+this.wnd.innerWidth)/t));this.comms.send("progress",{start:i,end:n})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const e=this.doc();e.classList.add(se(this.wnd)?"readium-bounce-l":"readium-bounce-r");const t=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{e.classList.remove("readium-bounce-l"),e.classList.remove("readium-bounce-r"),this.shakeTimeout=0,this.doc().scrollLeft=t},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 i=this.wnd.scrollX>0?this.wnd.scrollX:this.alreadyScrollLeft,n=this.doc(),r=this.dragOffset(),s=Ui(this.wnd),a=Math.min(Math.max(0,i),this.cachedScrollWidth),l=se(this.wnd)?-1:1,c=l*(this.wnd.innerWidth/3)*(l*r>0?2:1),h=this.snapOffset(a+c),u=h>this.scrollOffset()?"right":"left";if(this.checkSuspiciousSnap(u,Math.abs(h-this.scrollOffset())),e&&h!==this.scrollOffset()){this.snappingCancelled=!1;const m=(S,w,z,re)=>z>re?w:S+(w-S)*Sr(z/re),b=xr*s;let d;const p=S=>{if(this.snappingCancelled)return;d||(d=S);const w=S-d,z=m(this.overscroll,0,w,b),re=m(i,h,w,b);n.scrollLeft=re,this.overscroll!==0&&(n.style.transform=`translate3d(${-z}px, 0px, 0px)`),w<b?this.wnd.requestAnimationFrame(p):(this.clearTouches(),n.style.removeProperty("transform"),n.scrollLeft=h,t||this.reportProgress())};this.wnd.requestAnimationFrame(p)}else n.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{n.scrollLeft=h,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(),i=this.scrollOffset();this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),t>5&&this.comms.send("no_more",void 0),t<-5&&this.comms.send("no_less",void 0)):i<5&&t<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):this.cachedScrollWidth-i-this.wnd.innerWidth<5&&t>5&&(this.alreadyScrollLeft=this.cachedScrollWidth,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,I(this.wnd)),this.endingX=e.touches[0].clientX;const t=this.dragOffset(),i=this.alreadyScrollLeft+t;i<0?(this.overscroll=i,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):i+this.wnd.innerWidth>this.cachedScrollWidth?(this.overscroll=i,this.doc().style.transform=`translate3d(${-i}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=this.alreadyScrollLeft+t)}enableSnapProtection(){this.patternAnalyzer||(this.patternAnalyzer=new At({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 i=Date.now(),n=i-(this.lastTurnTime||i);this.lastTurnTime=i,this.patternAnalyzer.analyze(e,t,n)&&this.comms?.send("content_protection",{type:"suspicious_snapping",timestamp:Date.now(),event:null})}mount(e,t){if(this.wnd=e,this.comms=t,!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const i=e.document.createElement("style");i.dataset.readium="true",i.id=$i,i.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);}
|
|
@@ -43,19 +43,19 @@
|
|
|
43
43
|
* {
|
|
44
44
|
scrollbar-width: none; /* for Firefox */
|
|
45
45
|
}
|
|
46
|
-
|
|
46
|
+
|
|
47
47
|
body::-webkit-scrollbar {
|
|
48
48
|
display: none; /* for Chrome, Safari, and Opera */
|
|
49
49
|
}
|
|
50
|
-
`,e.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{e.requestAnimationFrame(()=>{e&&
|
|
50
|
+
`,e.document.head.appendChild(i),this.resizeObserver=new ResizeObserver(()=>{e.requestAnimationFrame(()=>{e&&Wi(e)}),this.onWidthChange()}),this.resizeObserver.observe(e.document.body),this.mutationObserver=new MutationObserver(r=>{for(const s of r)if(s.target===this.wnd.document.documentElement){const a=s.oldValue,l=s.target.getAttribute("style"),c=/transform\s*:\s*([^;]+)/,h=a?.match(c),u=l?.match(c);(!h&&!u||h&&!u||h&&u&&h[1]!==u[1])&&(e.requestAnimationFrame(()=>{e&&Wi(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",W.moduleName,(r,s)=>{this.enableSnapProtection(),s(!0)});const n=r=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(r),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",W.moduleName,(r,s)=>{const a=r;if(a<0||a>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 l=this.cachedScrollWidth,c=se(e)?-1:1,h=l*a*c;this.doc().scrollLeft=this.snapOffset(h),this.reportProgress(),I(this.wnd),s(!0)})}),t.register("go_id",W.moduleName,(r,s)=>{const a=e.document.getElementById(r);if(!a){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(a.getBoundingClientRect().left+e.scrollX),this.reportProgress(),I(this.wnd),s(!0)})}),t.register("go_text",W.moduleName,(r,s)=>{let a;Array.isArray(r)&&(r.length>1&&(a=r[1]),r=r[0]);const l=oe.deserialize(r),c=Ze(this.wnd.document,new F({href:e.location.href,type:"text/html",text:l,locations:a?new k({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!c){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(c.getBoundingClientRect().left+e.scrollX),this.reportProgress(),I(this.wnd),s(!0)})}),t.register("go_end",W.moduleName,(r,s)=>{const a=se(e)?-1:1;this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const l=this.cachedScrollWidth*a;if(this.doc().scrollLeft===l)return s(!1);this.doc().scrollLeft=this.snapOffset(l),this.reportProgress(),I(this.wnd),s(!0)})}),t.register("go_start",W.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return s(!1);this.doc().scrollLeft=0,this.reportProgress(),I(this.wnd),s(!0)})}),t.register("go_prev",W.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=e.scrollX-e.innerWidth,l=se(e)?-(this.cachedScrollWidth-e.innerWidth):0,c=n(Math.max(a,l));c&&(this.reportProgress(),I(this.wnd),this.checkSuspiciousSnap("left",this.wnd.innerWidth)),s(c)})}),t.register("go_next",W.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=e.scrollX+e.innerWidth,l=se(e)?0:this.cachedScrollWidth-e.innerWidth,c=n(Math.min(a,l));c&&(this.reportProgress(),I(this.wnd),this.checkSuspiciousSnap("right",this.wnd.innerWidth)),s(c)})}),t.register("unfocus",W.moduleName,(r,s)=>{this.snappingCancelled=!0,I(this.wnd),s(!0)}),t.register("shake",W.moduleName,(r,s)=>{this.shake(),s(!0)}),t.register("focus",W.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),s(!0)})}),t.register("first_visible_locator",W.moduleName,(r,s)=>{const a=Rt(e,!1);this.comms.send("first_visible_locator",a.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(W.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($i)?.remove(),t.log("ColumnSnapper Unmounted"),super.unmount(e,t)}};W.moduleName="column_snapper";let Ot=W;const Xi="readium-scroll-snapper-style",H=class H extends Re{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,i=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(i)>5){const n=Date.now(),r=n-(this.lastScrollTime||n);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(i>0?"down":"up",Math.abs(i),r)){const a=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:i,scrollDirection:i>0?"down":"up",targetElement:a})}this.lastScrollTime=n}this.comms.send("scroll",i),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,i=this.wnd.innerHeight,n=Math.max(0,Math.min(1,e/t)),r=Math.max(0,Math.min(1,(e+i)/t));this.comms.send("progress",{start:n,end:r})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new At(ji),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 i=e.document.createElement("style");return i.dataset.readium="true",i.id=Xi,i.textContent=`
|
|
51
51
|
* {
|
|
52
52
|
scrollbar-width: none; /* for Firefox */
|
|
53
53
|
}
|
|
54
|
-
|
|
54
|
+
|
|
55
55
|
body::-webkit-scrollbar {
|
|
56
56
|
display: none; /* for Chrome, Safari, and Opera */
|
|
57
57
|
}
|
|
58
|
-
`,e.document.head.appendChild(i),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",H.moduleName,()=>{Bi(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",H.moduleName,(n,r)=>{const s=n;if(s<0||s>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_id",H.moduleName,(n,r)=>{const s=e.document.getElementById(n);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_text",H.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=se.deserialize(n),l=Qe(this.wnd.document,new N({href:e.location.href,type:"text/html",text:a,locations:s?new k({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!l){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_start",H.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",H.moduleName,(n,r)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return r(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),r(!0)}),t.register("unfocus",H.moduleName,(n,r)=>{I(this.wnd),r(!0)}),t.register("scroll_protection",H.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],H.moduleName,(n,r)=>r(!1)),t.register("focus",H.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",H.moduleName,(n,r)=>{const s=At(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(H.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Yi)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};H.moduleName="scroll_snapper";let zt=H;const B=class B extends Ae{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,i=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(i)>5){const n=Date.now(),r=n-(this.lastScrollTime||n);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(i>0?"down":"up",Math.abs(i),r)){const a=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:i,scrollDirection:i>0?"down":"up",targetElement:a})}this.lastScrollTime=n}this.comms.send("scroll",i),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,i=this.wnd.innerHeight,n=Math.max(0,Math.min(1,e/t)),r=Math.max(0,Math.min(1,(e+i)/t));this.comms.send("progress",{start:n,end:r})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new Ot(Gi),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,()=>{Bi(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",B.moduleName,(i,n)=>{const r=i;if(r<0||r>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*r,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_id",B.moduleName,(i,n)=>{const r=e.document.getElementById(i);if(!r){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=r.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_text",B.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=se.deserialize(i),a=Qe(this.wnd.document,new N({href:e.location.href,type:"text/html",text:s,locations:r?new k({otherLocations:new Map([["cssSelector",r]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_start",B.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",B.moduleName,(i,n)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return n(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),n(!0)}),t.register("unfocus",B.moduleName,(i,n)=>{I(this.wnd),n(!0)}),t.register("scroll_protection",B.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],B.moduleName,(i,n)=>n(!1)),t.register("focus",B.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",B.moduleName,(i,n)=>{const r=At(e,!0);t.send("first_visible_locator",r.serialize()),n(!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 Mt=B;class Ar{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(i=>e-i.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(n=>e-n.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((n,r)=>n.timestamp-r.timestamp).every((n,r,s)=>r===0?!0:n.length>s[r-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const n=t.toString().length,r=this.window.document.body.innerText.length,s=Date.now();if(this.cleanupOldHistory(s),n<this.options.minThreshold)return this.copyHistory.push({timestamp:s,length:n,wasBlocked:!1}),!0;const l=s-this.lastSelectionTime<100&&n>this.lastSelectionLength*1.5,c=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(s),u=n>c||l||h;return this.copyHistory.push({timestamp:s,length:n,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=n,this.lastSelectionTime=s,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class Or{constructor(e=Xi){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 i=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=i,this.lastSelectedText=t,!1;if(i-this.selectionStartTime<500)return!1;i-this.lastSelectionTime>1e3&&(this.lastSelectionTime=i),this.selectionStartTime===0&&(this.selectionStartTime=i),this.lastSelectedText=t;const r=this.analyzeSelectionPattern(e,i);return this.cleanup(i),r}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const i=e.getRangeAt(0),n=i.toString(),r=(t-this.selectionStartTime)/1e3;if(n.length/Math.max(1,r)>this.options.maxSelectionsPerSecond)return!0;const a=i.startOffset,l=Math.abs(a-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=a,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((i,n)=>i+n,0)/e.length;return e.reduce((i,n)=>i+Math.pow(n-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 qi{match(e,t){for(const i of t){const n=e.keyCode===i.keyCode,r=i.ctrl===void 0||e.ctrlKey===i.ctrl,s=i.shift===void 0||e.shiftKey===i.shift,a=i.alt===void 0||e.altKey===i.alt,l=i.meta===void 0||e.metaKey===i.meta;if(n&&r&&s&&a&&l)return!0}return!1}createKeyHandler(e,t){return i=>{this.match(i,e)&&(i.preventDefault(),i.stopPropagation(),t(i))}}createActivityEvent(e,t,i,n){let r;if(n){const s=n.getSelection(),a=s?.toString()||"",c=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];c&&a&&(r={text:a,x:c.x,y:c.y,width:c.width,height:c.height})}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:i,selectedText:r}}createKeyboardHandlers(e,t,i,n){const r=[];return t.forEach(s=>{r.push(...s.keyCombos.map(a=>({...a,handler:l=>{const c=s.type,h=this.createActivityEvent(l,c,e,n);i(h)}})))}),r}createUnifiedHandler(e,t,i,n){const r=this.createKeyboardHandlers(e,t,i,n);return s=>{for(const a of r)if(this.match(s,[a])){s.preventDefault(),s.stopPropagation(),a.handler(s);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 qi,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(),i=t?.toString()||"",r=(i?t?.getRangeAt(0)?.getClientRects():null)?.[0],s={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:r?{text:i,x:r.x,y:r.y,width:r.width,height:r.height}:void 0,selectionLength:i.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",s),!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 n=this.wnd.getSelection(),r=n?.toString()||"",a=(r&&n?.rangeCount?n.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:r.length,selectedText:{text:r,x:a?.x??0,y:a?.y??0,width:a?.width??0,height:a?.height??0},eventType:e?.type||"selectionchange",targetFrameSrc:this.wnd.location.href};this.comms?.send("content_protection",l)}}else this.currentSelection=null},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,i={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",i),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],s={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...r&&{selectedText:{text:i,x:r.x,y:r.y,width:r.width,height:r.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",s)}},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("drop",this.onDrop),this.isDragAndDropEnabled=!0)}removeDragAndDropPrevention(){!this.isDragAndDropEnabled||!this.wnd||(this.wnd.document.removeEventListener("dragstart",this.onDragStart),this.wnd.document.removeEventListener("drop",this.onDrop),this.isDragAndDropEnabled=!1)}enableKeyboardPeripherals(e=[]){this.disableKeyboardPeripherals();const t=i=>{this.comms?.send("keyboard_peripherals",i)};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=Lr,i=e?{...t,...e}:t;this.bulkCopyProtector=new Ar(this.wnd,i),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||Xi;this.selectionAnalyzer=new Or(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 n=t.getRangeAt(0)?.getClientRects();if(!n||n.length===0)return;const r=n[0],s={text:t.toString(),x:r.x,y:r.y,width:r.width,height:r.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const i=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*i,y:e.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Vi(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 i=e;if(!this.configApplied){if(this.configApplied=!0,i.monitorSelection){const n=typeof i.monitorSelection=="boolean"?void 0:i.monitorSelection;this.addSelectionMonitoring(n),this.comms?.log("Selection monitoring enabled")}typeof i.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...i.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):i.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),i.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),i.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",Ce.moduleName,(e,t)=>{const i=e;i&&i.length>0&&(this.enableKeyboardPeripherals(i),this.comms?.log(`Keyboard peripherals enabled: ${i.map(n=>n.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(i=>i()),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 It=Ce;const Xe=class Xe 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 i=t[1],n=t[2];e.removeEventListener(i.type,e._readium_eventBlocker,!0);const r=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});n?n.dispatchEvent(r):e.dispatchEvent(r);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 i=0;i<t.length;i++)t[i].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.4.0-beta.8",hasFeature:(n,r="")=>{switch(n){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(n=>{n.cancel(),this.allAnimations.add(n)}),t.register("activate",Xe.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",Xe.moduleName,(n,r)=>{this.pauseAllMedia(e),this.allAnimations.forEach(s=>s.pause()),r(!0)});const i=e.document.querySelectorAll("audio,video");for(let n=0;n<i.length;n++){const r=i[n];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.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(i=>i.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};Xe.moduleName="setup";let rt=Xe;const Ki="readium-viewport",ee=class ee extends rt{onViewportWidthChanged(e){const t=e.target;Le(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const i=e.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",Ki),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(i),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",ee.moduleName,(n,r)=>{Pt(e),r(!0)}),t.register("update_properties",ee.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,zi(e,n),r(!0)}),t.register("set_property",ee.moduleName,(n,r)=>{const s=n;Le(e,s[0],s[1]),r(!0)}),t.register("remove_property",ee.moduleName,(n,r)=>{tt(e,n),r(!0)}),t.register("activate",ee.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ee.moduleName),e.document.head.querySelector(`#${Ki}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};ee.moduleName="reflowable_setup";let Nt=ee;const Ji="readium-fixed-style",J=class J extends rt{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const i=e.document.createElement("style");return i.id=Ji,i.dataset.readium="true",i.textContent=`
|
|
58
|
+
`,e.document.head.appendChild(i),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",H.moduleName,()=>{Hi(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",H.moduleName,(n,r)=>{const s=n;if(s<0||s>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_id",H.moduleName,(n,r)=>{const s=e.document.getElementById(n);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_text",H.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=oe.deserialize(n),l=Ze(this.wnd.document,new F({href:e.location.href,type:"text/html",text:a,locations:s?new k({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!l){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=l.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),r(!0)})}),t.register("go_start",H.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",H.moduleName,(n,r)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return r(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),r(!0)}),t.register("unfocus",H.moduleName,(n,r)=>{I(this.wnd),r(!0)}),t.register("scroll_protection",H.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],H.moduleName,(n,r)=>r(!1)),t.register("focus",H.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",H.moduleName,(n,r)=>{const s=Rt(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(H.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Xi)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};H.moduleName="scroll_snapper";let Tt=H;const B=class B extends Re{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,i=t-this.lastScrollTop;if(this.lastScrollTop=t,this.isScrollProtectionEnabled&&Math.abs(i)>5){const n=Date.now(),r=n-(this.lastScrollTime||n);if(this.patternAnalyzer&&this.patternAnalyzer.analyze(i>0?"down":"up",Math.abs(i),r)){const a=e.target&&"tagName"in e.target?{tagName:e.target.tagName}:null;this.comms?.send("content_protection",{type:"suspicious_scrolling",timestamp:Date.now(),scrollDelta:i,scrollDirection:i>0?"down":"up",targetElement:a})}this.lastScrollTime=n}this.comms.send("scroll",i),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,i=this.wnd.innerHeight,n=Math.max(0,Math.min(1,e/t)),r=Math.max(0,Math.min(1,(e+i)/t));this.comms.send("progress",{start:n,end:r})}enableScrollProtection(){this.patternAnalyzer||(this.patternAnalyzer=new At(ji),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,()=>{Hi(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",B.moduleName,(i,n)=>{const r=i;if(r<0||r>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*r,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_id",B.moduleName,(i,n)=>{const r=e.document.getElementById(i);if(!r){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=r.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_text",B.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=oe.deserialize(i),a=Ze(this.wnd.document,new F({href:e.location.href,type:"text/html",text:s,locations:r?new k({otherLocations:new Map([["cssSelector",r]])}):void 0}));if(!a){n(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+e.scrollY-e.innerHeight/2,this.reportProgress(),I(this.wnd),n(!0)})}),t.register("go_start",B.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",B.moduleName,(i,n)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return n(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),n(!0)}),t.register("unfocus",B.moduleName,(i,n)=>{I(this.wnd),n(!0)}),t.register("scroll_protection",B.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],B.moduleName,(i,n)=>n(!1)),t.register("focus",B.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",B.moduleName,(i,n)=>{const r=Rt(e,!0);t.send("first_visible_locator",r.serialize()),n(!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 zt=B;class Lr{constructor(e,t){this.window=e,this.copyHistory=[],this.lastSelectionLength=0,this.lastSelectionTime=0,this.options=t}cleanupOldHistory(e){this.copyHistory=this.copyHistory.filter(i=>e-i.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(n=>e-n.timestamp<2e3).length>=3?!0:this.copyHistory.slice().sort((n,r)=>n.timestamp-r.timestamp).every((n,r,s)=>r===0?!0:n.length>s[r-1].length*1.5)}shouldAllowCopy(e){if(!this.options.enabled)return!0;const t=this.window.getSelection();if(!t)return!0;const n=t.toString().length,r=this.window.document.body.innerText.length,s=Date.now();if(this.cleanupOldHistory(s),n<this.options.minThreshold)return this.copyHistory.push({timestamp:s,length:n,wasBlocked:!1}),!0;const l=s-this.lastSelectionTime<100&&n>this.lastSelectionLength*1.5,c=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),h=this.isSuspiciousPattern(s),u=n>c||l||h;return this.copyHistory.push({timestamp:s,length:n,wasBlocked:u}),u?(e?.preventDefault(),!1):(this.lastSelectionLength=n,this.lastSelectionTime=s,!0)}destroy(){this.lastSelectionLength=0,this.lastSelectionTime=0,this.copyHistory=[],this.options.enabled=!1}}class Rr{constructor(e=Gi){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 i=Date.now();if(t.length<=50||t===this.lastSelectedText)return!1;if(this.selectionStartTime===0)return this.selectionStartTime=i,this.lastSelectedText=t,!1;if(i-this.selectionStartTime<500)return!1;i-this.lastSelectionTime>1e3&&(this.lastSelectionTime=i),this.selectionStartTime===0&&(this.selectionStartTime=i),this.lastSelectedText=t;const r=this.analyzeSelectionPattern(e,i);return this.cleanup(i),r}analyzeSelectionPattern(e,t){if(!e.rangeCount)return!1;const i=e.getRangeAt(0),n=i.toString(),r=(t-this.selectionStartTime)/1e3;if(n.length/Math.max(1,r)>this.options.maxSelectionsPerSecond)return!0;const a=i.startOffset,l=Math.abs(a-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=a,!1)}calculateVariance(e){if(e.length===0)return 0;const t=e.reduce((i,n)=>i+n,0)/e.length;return e.reduce((i,n)=>i+Math.pow(n-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 qi{match(e,t){for(const i of t){const n=e.keyCode===i.keyCode,r=i.ctrl===void 0||e.ctrlKey===i.ctrl,s=i.shift===void 0||e.shiftKey===i.shift,a=i.alt===void 0||e.altKey===i.alt,l=i.meta===void 0||e.metaKey===i.meta;if(n&&r&&s&&a&&l)return!0}return!1}createKeyHandler(e,t){return i=>{this.match(i,e)&&(i.preventDefault(),i.stopPropagation(),t(i))}}createActivityEvent(e,t,i,n){let r;if(n){const s=n.getSelection(),a=s?.toString()||"",c=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];c&&a&&(r={text:a,x:c.x,y:c.y,width:c.width,height:c.height})}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:i,selectedText:r}}createKeyboardHandlers(e,t,i,n){const r=[];return t.forEach(s=>{r.push(...s.keyCombos.map(a=>({...a,handler:l=>{const c=s.type,h=this.createActivityEvent(l,c,e,n);i(h)}})))}),r}createUnifiedHandler(e,t,i,n){const r=this.createKeyboardHandlers(e,t,i,n);return s=>{for(const a of r)if(this.match(s,[a])){s.preventDefault(),s.stopPropagation(),a.handler(s);return}}}}const ke=class ke extends ge{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 qi,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(),i=t?.toString()||"",r=(i?t?.getRangeAt(0)?.getClientRects():null)?.[0],s={type:"bulk_copy",timestamp:Date.now(),clipboardTypes:e.clipboardData?.types?[...e.clipboardData.types]:[],selectedText:r?{text:i,x:r.x,y:r.y,width:r.width,height:r.height}:void 0,selectionLength:i.length,targetFrameSrc:this.wnd.location.href};return this.comms?.send("content_protection",s),!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 n=this.wnd.getSelection(),r=n?.toString()||"",a=(r&&n?.rangeCount?n.getRangeAt(0)?.getClientRects():null)?.[0],l={type:"suspicious_selection",timestamp:Date.now(),selectionLength:r.length,selectedText:{text:r,x:a?.x??0,y:a?.y??0,width:a?.width??0,height:a?.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,i={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",i),!1}else return!0},this.onContext=e=>{if(this.isContextMenuEnabled){e.preventDefault();const t=this.wnd.getSelection(),i=t?.toString()||"",r=(i&&t?.rangeCount?t.getRangeAt(0)?.getClientRects():null)?.[0],s={timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,...r&&{selectedText:{text:i,x:r.x,y:r.y,width:r.width,height:r.height}},targetFrameSrc:this.wnd.location.href};this.comms?.send("context_menu",s)}},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=i=>{this.comms?.send("keyboard_peripherals",i)};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=Cr,i=e?{...t,...e}:t;this.bulkCopyProtector=new Lr(this.wnd,i),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||Gi;this.selectionAnalyzer=new Rr(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 n=t.getRangeAt(0)?.getClientRects();if(!n||n.length===0)return;const r=n[0],s={text:t.toString(),x:r.x,y:r.y,width:r.width,height:r.height,targetFrameSrc:this.wnd?.location?.href};this.comms.send("text_selected",s)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!t?.isCollapsed||!e.isPrimary)return;const i=this.wnd.devicePixelRatio;e.preventDefault(),this.comms.send(e.pointerType==="touch"?"tap":"click",{defaultPrevented:e.defaultPrevented,x:e.clientX*i,y:e.clientY*i,targetFrameSrc:this.wnd.location.href,targetElement:e.target.outerHTML,interactiveElement:Bi(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",ke.moduleName,(e,t)=>{const i=e;if(!this.configApplied){if(this.configApplied=!0,i.monitorSelection){const n=typeof i.monitorSelection=="boolean"?void 0:i.monitorSelection;this.addSelectionMonitoring(n),this.comms?.log("Selection monitoring enabled")}typeof i.protectCopy=="object"?(this.addBulkCopyProtection({enabled:!0,...i.protectCopy}),this.comms?.log("Copy protection enabled (limited)")):i.protectCopy===!0&&(this.addBulkCopyProtection({enabled:!0,maxSelectionPercent:0,minThreshold:0,absoluteMaxChars:0}),this.comms?.log("Copy protection enabled")),i.disableContextMenu&&(this.addContextMenuPrevention(),this.comms?.log("Context menu protection enabled")),i.disableDragAndDrop&&(this.addDragAndDropPrevention(),this.comms?.log("Drag and drop protection enabled"))}t(!0)}),this.comms?.register("keyboard_peripherals",ke.moduleName,(e,t)=>{const i=e;i&&i.length>0&&(this.enableKeyboardPeripherals(i),this.comms?.log(`Keyboard peripherals enabled: ${i.map(n=>n.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(i=>i()),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(ke.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};ke.moduleName="peripherals";let Mt=ke;const Ge=class Ge extends ge{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 i=t[1],n=t[2];e.removeEventListener(i.type,e._readium_eventBlocker,!0);const r=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});n?n.dispatchEvent(r):e.dispatchEvent(r);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 i=0;i<t.length;i++)t[i].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.4.0",hasFeature:(n,r="")=>{switch(n){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(n=>{n.cancel(),this.allAnimations.add(n)}),t.register("activate",Ge.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",Ge.moduleName,(n,r)=>{this.pauseAllMedia(e),this.allAnimations.forEach(s=>s.pause()),r(!0)});const i=e.document.querySelectorAll("audio,video");for(let n=0;n<i.length;n++){const r=i[n];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.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(i=>i.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};Ge.moduleName="setup";let nt=Ge;const Yi="readium-viewport",ee=class ee extends nt{onViewportWidthChanged(e){const t=e.target;xe(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(e,t){if(!super.mount(e,t))return!1;const i=e.document.createElement("meta");return i.dataset.readium="true",i.setAttribute("name","viewport"),i.setAttribute("id",Yi),i.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),e.document.head.appendChild(i),e.addEventListener("orientationchange",this.onViewportWidthChanged),e.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:e}),t.register("get_properties",ee.moduleName,(n,r)=>{wt(e),r(!0)}),t.register("update_properties",ee.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,Ti(e,n),r(!0)}),t.register("set_property",ee.moduleName,(n,r)=>{const s=n;xe(e,s[0],s[1]),r(!0)}),t.register("remove_property",ee.moduleName,(n,r)=>{et(e,n),r(!0)}),t.register("activate",ee.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(ee.moduleName),e.document.head.querySelector(`#${Yi}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};ee.moduleName="reflowable_setup";let It=ee;const Ki="readium-fixed-style",J=class J extends nt{mount(e,t){if(!super.mount(e,t))return!1;e.navigator.epubReadingSystem&&(e.navigator.epubReadingSystem.layoutStyle="paginated");const i=e.document.createElement("style");return i.id=Ki,i.dataset.readium="true",i.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(i),t.register("set_property",J.moduleName,(n,r)=>{const s=n;
|
|
70
|
+
}`,e.document.head.appendChild(i),t.register("set_property",J.moduleName,(n,r)=>{const s=n;xe(e,s[0],s[1]),r(!0)}),t.register("remove_property",J.moduleName,(n,r)=>{et(e,n),r(!0)}),t.register("first_visible_locator",J.moduleName,(n,r)=>r(!1)),t.register("unfocus",J.moduleName,(n,r)=>{I(e),r(!0)}),t.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],J.moduleName,(n,r)=>r(!0)),t.register("activate",J.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("FixedSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(J.moduleName),e.document.getElementById(Ki)?.remove(),t.log("FixedSetup Unmounted"),super.unmount(e,t)}};J.moduleName="fixed_setup";let Ft=J;const te=class te extends ge{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",te.moduleName,(i,n)=>{wt(e),n(!0)}),t.register("update_properties",te.moduleName,(i,n)=>{Ti(e,i),n(!0)}),t.register("set_property",te.moduleName,(i,n)=>{const r=i;xe(e,r[0],r[1]),n(!0)}),t.register("remove_property",te.moduleName,(i,n)=>{et(e,i),n(!0)}),t.register("activate",te.moduleName,(i,n)=>{n(!0)}),t.log("WebPubSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(te.moduleName),e.removeEventListener("error",this.wndOnErr),t.log("WebPubSetup Unmounted"),!0}};te.moduleName="webpub_setup";let Nt=te,Ar=(ne=class extends ge{constructor(){super(...arguments),this.styleElement=null,this.beforePrintHandler=null,this.configApplied=!1}setupPrintProtection(e,t){if(!t.disable)return;const i=e.document.createElement("style");i.textContent=`
|
|
71
71
|
@media print {
|
|
72
72
|
body * {
|
|
73
73
|
display: none !important;
|
|
@@ -81,9 +81,9 @@
|
|
|
81
81
|
transform: translateY(-50%);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
-
`,e.document.head.appendChild(i),this.styleElement=i,this.beforePrintHandler=n=>(n.preventDefault(),!1),e.addEventListener("beforeprint",this.beforePrintHandler)}registerPrintHandlers(){this.comms?.register("print_protection",
|
|
85
|
-
`:"";let s=e.documentElement.outerHTML;return n+s}}const Wr=1e4;class Se{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=St()}this.gc=setInterval(()=>{this.registry.forEach((i,n)=>{performance.now()-i.time>Wr&&(console.warn(n,"event for",i.key,"was never handled!"),this.registry.delete(n))})},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 i=this.registry.get(t.id);if(!i)return;this.registry.delete(t.id),i.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,i,n=!1,r=[]){const s=St();return i&&this.registry.set(s,{cb:i,time:performance.now(),key:e}),this.wnd.postMessage({_readium:ge,_channel:this.channelId,id:s,data:t,key:e,strict:n},"/",r),s}}const Hr={RS__oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif"},Br=16,tn=Hr.RS__oldStyleTf;class _e{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||Br,this._fontFace=e.fontFace||tn,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=_e.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||tn),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=_e.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 i=0;if(t&&t.length>=e){const n=t.match(/([\s]+)/gi);i=(n?n.length:0)*(e/t.length)}return i}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 i=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(t.font=`${this._baseFontSize}px ${e}`,this._sample&&this._sample.length>=this._optimalChars&&(i=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(i).width;{const n=this._letterSpacing*(this._optimalChars-1),r=this._wordSpacing*_e.approximateWordSpaces(this._optimalChars,this._sample);return t.measureText(i).width+n+r}}else return this.getLineLengthFallback()}}const nn=()=>typeof navigator>"u"?"":navigator.userAgent||"",rn=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class on{constructor(){const e=rn(),t=nn(),i=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],n=(r="")=>{if(!r)return[];const s=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(t)?i(t.replace(s,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(r.iOS=n("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?r.iOS=r.iPadOS=n("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=n():r.macOS=n("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?r.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(n("Windows(?: NT)?")):/Android \d/.test(t)?r.Android=n("Android"):/CrOS/.test(t)?r.ChromeOS=n():/X11;/.test(t)&&(r.Linux=n()),r))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(s=>{const a=r.platform,l=r.platformVersion;if(!(!a||!l)){if(/^i(OS|P(hone|od touch))$/.test(a))s.iOS=i(l);else if(/^iPad(OS)?$/.test(a))s.iOS=s.iPadOS=i(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i(l);else if(/^(Microsoft )?Windows$/.test(a))s.Windows=i(l);else if(/^(Google )?Android$/.test(a))s.Android=i(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))s.ChromeOS=i(l);else if(/^(Linux|Ubuntu|X11)$/.test(a))s.Linux=i(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,s)}})({})),this.UA=(r=>{let s=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});a["Google Chrome"]?(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Edge=a["Microsoft Edge"]):a.Opera&&(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Opera=a.Opera)}return s||(/ Gecko\/\d/.test(t)?(r.Gecko=n("rv"),/ Waterfox\/\d/.test(t)?r.Waterfox=n("Waterfox"):/ Firefox\/\d/.test(t)&&(r.Firefox=n("Firefox"))):/ Edge\/\d/.test(t)?(r.EdgeHTML=n("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(r.Blink=r.Chromium=(a=>a[0]?a:n("Chrome"))(n("Chromium")),/ EdgA?\/\d/.test(t)?r.Edge=(a=>a[0]?a:n("Edg"))(n("EdgA")):/ OPR\/\d/.test(t)?r.Opera=n("OPR"):/ Vivaldi\/\d/.test(t)?r.Vivaldi=n("Vivaldi"):/ Silk\/\d/.test(t)?r.Silk=n("Silk"):/ UCBrowser\/\d/.test(t)?r.UCBrowser=n("UCBrowser"):/ Phoebe\/\d/.test(t)?r.Phoebe=n("Phoebe"):r.Chrome=(a=>a[0]?a:r.Chromium)(n("Chrome"))):/ AppleWebKit\/\d/.test(t)?(r.WebKit=n("AppleWebKit"),/ CriOS \d/.test(t)?r.Chrome=n("CriOS"):/ FxiOS \d/.test(t)?r.Firefox=n("FxiOS"):/ EdgiOS\/\d/.test(t)?r.Edge=n("EdgiOS"):/ Version\/\d/.test(t)&&(r.Safari=n("Version"))):/ Trident\/\d/.test(t)&&(r.Trident=n("Trident"),r.InternetExplorer=(a=>a[0]?a:n("MSIE"))(n("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(r.Facebook=n("FBAV")),/ Line\/\d/.test(t)&&(r.LINE=n("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,s)=>{for(const a in s)s[a]&&r.push(a);return r},[])}}}class Vr extends on{get iOSRequest(){const e=rn(),t=nn();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 on,A=new Vr;class sn{constructor(e,t={},i=[]){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=[...i]}async load(e=[]){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ve(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new ve(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async 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,i=>{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 Se(this.frame.contentWindow,this.source),new Promise((t,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{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,n):n()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new Se(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 an{constructor(e,t,i,n={},r=[]){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=i,this.contentProtectionConfig=n,this.keyboardPeripheralsConfig=[...r]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i){const n=e.readingOrder.items;let r=n.findIndex(l=>l.href===t.href);if(r<0)throw Error(`Locator not found in reading order: ${t.href}`);const s=n[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];e.readingOrder.items.forEach((d,p)=>{p!==r&&p!==r-1&&p!==r+1&&(h.includes(d.href)||h.push(d.href)),p===r&&(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 w=this.blobs.get(d);w&&(this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const w=this.pool.get(d);if(!this.blobs.has(d))await w.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await w.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const z=await new en(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,z)}const S=new sn(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);b?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}var Ht,ln;function jr(){if(ln)return Ht;ln=1;function o(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function e(n,r){for(var s="",a=0,l=-1,c=0,h,u=0;u<=n.length;++u){if(u<n.length)h=n.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(s.length<2||a!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var m=s.lastIndexOf("/");if(m!==s.length-1){m===-1?(s="",a=0):(s=s.slice(0,m),a=s.length-1-s.lastIndexOf("/")),l=u,c=0;continue}}else if(s.length===2||s.length===1){s="",a=0,l=u,c=0;continue}}r&&(s.length>0?s+="/..":s="..",a=2)}else s.length>0?s+="/"+n.slice(l+1,u):s=n.slice(l+1,u),a=u-l-1;l=u,c=0}else h===46&&c!==-1?++c:c=-1}return s}function t(n,r){var s=r.dir||r.root,a=r.base||(r.name||"")+(r.ext||"");return s?s===r.root?s+a:s+n+a:a}var i={resolve:function(){for(var r="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=process.cwd()),c=a),o(c),c.length!==0&&(r=c+"/"+r,s=c.charCodeAt(0)===47)}return r=e(r,!s),s?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(r){if(o(r),r.length===0)return".";var s=r.charCodeAt(0)===47,a=r.charCodeAt(r.length-1)===47;return r=e(r,!s),r.length===0&&!s&&(r="."),r.length>0&&a&&(r+="/"),s?"/"+r:r},isAbsolute:function(r){return o(r),r.length>0&&r.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var r,s=0;s<arguments.length;++s){var a=arguments[s];o(a),a.length>0&&(r===void 0?r=a:r+="/"+a)}return r===void 0?".":i.normalize(r)},relative:function(r,s){if(o(r),o(s),r===s||(r=i.resolve(r),s=i.resolve(s),r===s))return"";for(var a=1;a<r.length&&r.charCodeAt(a)===47;++a);for(var l=r.length,c=l-a,h=1;h<s.length&&s.charCodeAt(h)===47;++h);for(var u=s.length,m=u-h,b=c<m?c:m,d=-1,p=0;p<=b;++p){if(p===b){if(m>b){if(s.charCodeAt(h+p)===47)return s.slice(h+p+1);if(p===0)return s.slice(h+p)}else c>b&&(r.charCodeAt(a+p)===47?d=p:p===0&&(d=0));break}var S=r.charCodeAt(a+p),w=s.charCodeAt(h+p);if(S!==w)break;S===47&&(d=p)}var z="";for(p=a+d+1;p<=l;++p)(p===l||r.charCodeAt(p)===47)&&(z.length===0?z+="..":z+="/..");return z.length>0?z+s.slice(h+d):(h+=d,s.charCodeAt(h)===47&&++h,s.slice(h))},_makeLong:function(r){return r},dirname:function(r){if(o(r),r.length===0)return".";for(var s=r.charCodeAt(0),a=s===47,l=-1,c=!0,h=r.length-1;h>=1;--h)if(s=r.charCodeAt(h),s===47){if(!c){l=h;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":r.slice(0,l)},basename:function(r,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');o(r);var a=0,l=-1,c=!0,h;if(s!==void 0&&s.length>0&&s.length<=r.length){if(s.length===r.length&&s===r)return"";var u=s.length-1,m=-1;for(h=r.length-1;h>=0;--h){var b=r.charCodeAt(h);if(b===47){if(!c){a=h+1;break}}else m===-1&&(c=!1,m=h+1),u>=0&&(b===s.charCodeAt(u)?--u===-1&&(l=h):(u=-1,l=m))}return a===l?l=m:l===-1&&(l=r.length),r.slice(a,l)}else{for(h=r.length-1;h>=0;--h)if(r.charCodeAt(h)===47){if(!c){a=h+1;break}}else l===-1&&(c=!1,l=h+1);return l===-1?"":r.slice(a,l)}},extname:function(r){o(r);for(var s=-1,a=0,l=-1,c=!0,h=0,u=r.length-1;u>=0;--u){var m=r.charCodeAt(u);if(m===47){if(!c){a=u+1;break}continue}l===-1&&(c=!1,l=u+1),m===46?s===-1?s=u:h!==1&&(h=1):s!==-1&&(h=-1)}return s===-1||l===-1||h===0||h===1&&s===l-1&&s===a+1?"":r.slice(s,l)},format:function(r){if(r===null||typeof r!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof r);return t("/",r)},parse:function(r){o(r);var s={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return s;var a=r.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var h=-1,u=0,m=-1,b=!0,d=r.length-1,p=0;d>=c;--d){if(a=r.charCodeAt(d),a===47){if(!b){u=d+1;break}continue}m===-1&&(b=!1,m=d+1),a===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?s.base=s.name=r.slice(1,m):s.base=s.name=r.slice(u,m)):(u===0&&l?(s.name=r.slice(1,h),s.base=r.slice(1,m)):(s.name=r.slice(u,h),s.base=r.slice(u,m)),s.ext=r.slice(h,m)),u>0?s.dir=r.slice(0,u-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Ht=i,Ht}var st=jr();const at={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 K=(o=>(o.start="start",o.left="left",o.right="right",o.justify="justify",o))(K||{});const le={range:[0,100],step:1},Oe={range:[.7,4],step:.05},Z={range:[100,1e3],step:100},Te={range:[50,250],step:10},ze={range:[0,1],step:.125},Me={range:[1,2],step:.1},ce={range:[20,100],step:1},Ie={range:[0,3],step:.25},Ne={range:[0,3],step:.25},Fe={range:[0,2],step:.125},Ue={range:[.7,4],step:.05},De={range:[0,1],step:.1},We={range:[.5,4],step:.1},Q={range:[5,60],step:5};class He{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 Bt extends He{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 cn extends He{constructor(e){super(),this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=at[t].value}),e}}class hn{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 Bt(t)}}function dn(o,e){return o==null||e==null||o<=e?o:void 0}function un(o,e){return o==null||e==null||o>=e?o:void 0}function F(o){return typeof o=="string"?o:o===null?null:void 0}function E(o){return typeof o=="boolean"||o==null?o:void 0}function Be(o,e){if(o!==void 0)return o===null?null:e[o]!==void 0?o:void 0}function he(o){return typeof o=="boolean"||typeof o=="number"&&o>=0?o:o===null?null:void 0}function _(o){if(o!==void 0)return o===null?null:o<0?void 0:o}function M(o,e){if(o===void 0)return;if(o===null)return null;const t=Math.min(...e),i=Math.max(...e);return o>=t&&o<=i?o:void 0}function lt(o,e){return o===void 0?e:o}function Vt(o){if(o!==void 0)return o===null?null:o.filter(e=>e in at)}class we{constructor(e={}){this.fontFamily=F(e.fontFamily),this.fontWeight=M(e.fontWeight,Z.range),this.hyphens=E(e.hyphens),this.iOSPatch=E(e.iOSPatch),this.iPadOSPatch=E(e.iPadOSPatch),this.letterSpacing=_(e.letterSpacing),this.ligatures=E(e.ligatures),this.lineHeight=_(e.lineHeight),this.noRuby=E(e.noRuby),this.paragraphIndent=_(e.paragraphIndent),this.paragraphSpacing=_(e.paragraphSpacing),this.textAlign=Be(e.textAlign,K),this.textNormalization=E(e.textNormalization),this.wordSpacing=_(e.wordSpacing),this.zoom=M(e.zoom,Ue.range)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new we(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new we(t)}}class pn{constructor(e){this.fontFamily=F(e.fontFamily)||null,this.fontWeight=M(e.fontWeight,Z.range)||null,this.hyphens=E(e.hyphens)??null,this.iOSPatch=e.iOSPatch===!1?!1:(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:A.OS.iPadOS&&A.iOSRequest==="desktop",this.letterSpacing=_(e.letterSpacing)||null,this.ligatures=E(e.ligatures)??null,this.lineHeight=_(e.lineHeight)||null,this.noRuby=E(e.noRuby)??!1,this.paragraphIndent=_(e.paragraphIndent)??null,this.paragraphSpacing=_(e.paragraphSpacing)??null,this.textAlign=Be(e.textAlign,K)||null,this.textNormalization=E(e.textNormalization)??!1,this.wordSpacing=_(e.wordSpacing)||null,this.zoom=M(e.zoom,Ue.range)||1,this.experiments=Vt(e.experiments)??null}}class jt{constructor(e,t,i){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,i&&(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?(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?A.OS.iPadOS&&A.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:i,onChange:n}){this._value=e,this._effectiveValue=t,this._isEffective=i,this._onChange=n}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 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 Gt extends T{constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:n,supportedValues:r}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:n}),this._supportedValues=r}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 C extends T{constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:n,supportedRange:r,step:s}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:n}),this._supportedRange=r,this._step=s,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 Xt{constructor(e,t,i){this.preferences=e,this.settings=t,this.metadata=i}clear(){this.preferences=new we({})}updatePreference(e,t){this.preferences[e]=t}get isDisplayTransformable(){return this.metadata?.accessibility?.feature?.some(e=>e.value===$e.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 C({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontWeight",e||null)},supportedRange:Z.range,step:Z.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 C({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("letterSpacing",e||null)},supportedRange:ze.range,step:ze.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 C({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 C({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 C({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphSpacing",e||null)},supportedRange:Ne.range,step:Ne.step})}get textAlign(){return new Gt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||K.start,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textAlign",e||null)},supportedValues:Object.values(K)})}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 C({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("wordSpacing",e||null)},supportedRange:Fe.range,step:Fe.step})}get zoom(){return new C({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:e=>{this.updatePreference("zoom",e||null)},supportedRange:Ue.range,step:Ue.step})}}const mn=o=>{if("blob"in o&&o.blob.type)return o.blob.type;if(o.as==="script")return"text/javascript";if(o.as==="link"&&"url"in o){const e=o.url.toLowerCase();if(e.endsWith(".css"))return"text/css";if([".js",".mjs",".cjs"].some(t=>e.endsWith(t)))return"text/javascript"}},gn=(o,e)=>{e.attributes&&Object.entries(e.attributes).forEach(([t,i])=>{t==="type"||t==="rel"||t==="href"||t==="src"||i!=null&&(typeof i=="boolean"?i&&o.setAttribute(t,""):o.setAttribute(t,i))})},Gr=(o,e,t)=>{const i=o.createElement("script");i.dataset.readium="true",e.id&&(i.id=e.id);const n=e.type||mn(e);return n&&(i.type=n),gn(i,e),i.src=t,i},fn=(o,e,t)=>{const i=o.createElement("link");i.dataset.readium="true",e.id&&(i.id=e.id),e.rel&&(i.rel=e.rel);const n=e.type||mn(e);return n&&(i.type=n),gn(i,e),i.href=t,i};class $t{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 i={...t};return t.prepend&&(i.prepend=t.prepend.map(n=>({...n,id:n.id||`injectable-${this.injectableIdCounter++}`})).reverse()),t.append&&(i.append=t.append.map(n=>({...n,id:n.id||`injectable-${this.injectableIdCounter++}`}))),i})}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 i of this.rules)this.matchesRule(i,t)&&await this.applyRule(e,i)}matchesRule(e,t){const i=t.href;return e.resources.some(n=>n instanceof RegExp?n.test(i):i===n)}async getOrCreateBlobUrl(e){const t=e.id;if(this.blobStore.has(t)){const i=this.blobStore.get(t);return i.refCount++,i.url}if("blob"in e){const i=URL.createObjectURL(e.blob);return this.blobStore.set(t,{url:i,refCount:1}),this.createdBlobUrls.add(i),i}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(i=>i.url===e);if(t&&(t.refCount--,t.refCount<=0)){URL.revokeObjectURL(e),this.createdBlobUrls.delete(e);for(const[i,n]of this.blobStore.entries())if(n.url===e){this.blobStore.delete(i);break}}}async getResourceUrl(e,t){if("url"in e){const i=new URL(e.url,t.baseURI).toString();if(!this.isValidUrl(i,t))throw new Error(`Invalid URL: Only HTTPS, data:, blob:, or localhost HTTP URLs are allowed. Got: ${e.url}`);return i}else return this.getOrCreateBlobUrl(e)}createPreloadLink(e,t,i){if(t.as!=="link"||t.rel!=="preload")return;const n={...t,rel:"preload",attributes:{...t.attributes,as:t.as}},r=fn(e,n,i);e.head.appendChild(r)}createElement(e,t,i){if(t.as==="script")return Gr(e,t,i);if(t.as==="link")return fn(e,t,i);throw new Error(`Unsupported element type: ${t.as}`)}async applyRule(e,t){const i=[],n=t.prepend?t.prepend.filter(s=>!s.condition||s.condition(e)):[],r=t.append?t.append.filter(s=>!s.condition||s.condition(e)):[];try{for(const s of n)await this.processInjectable(s,e,i,"prepend");for(const s of r)await this.processInjectable(s,e,i,"append")}catch(s){for(const{element:a,url:l}of i)try{a.remove(),await this.releaseBlobUrl(l)}catch(c){console.error("Error during cleanup:",c)}throw s}}async processInjectable(e,t,i,n){const r=e.target==="body"?t.body:t.head;if(!r)return;let s=null;try{if(s=await this.getResourceUrl(e,t),e.rel==="preload"&&"url"in e)this.createPreloadLink(t,e,s);else{const a=this.createElement(t,e,s);i.push({element:a,url:s}),n==="prepend"?r.prepend(a):r.append(a)}}catch(a){throw console.error("Failed to process resource:",a),s&&"blob"in e&&await this.releaseBlobUrl(s),a}}isValidUrl(e,t){try{const i=new URL(e,t.baseURI);if(i.protocol==="data:"||i.protocol==="blob:"&&this.createdBlobUrls.has(e))return!0;if(this.allowedDomains.length>0){const n=i.origin;return this.allowedDomains.some(r=>{const s=new URL(r).origin;return n===s})}return!1}catch{return!1}}}const Pe=o=>o.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),ct=o=>o.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," "),Xr=`/*!
|
|
86
|
-
* Readium CSS v.2.0.
|
|
84
|
+
`,e.document.head.appendChild(i),this.styleElement=i,this.beforePrintHandler=n=>(n.preventDefault(),!1),e.addEventListener("beforeprint",this.beforePrintHandler)}registerPrintHandlers(){this.comms?.register("print_protection",ne.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(ne.moduleName),this.configApplied=!1,!0}},ne.moduleName="print_protection",ne);const Or=["fixed_setup","decorator","peripherals","print_protection"],Tr=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper","print_protection"],zr=["webpub_setup","webpub_snapper","decorator","peripherals","print_protection"],rt=new Map([Ft,It,Nt,zt,Mt,Lt,Ot,Tt,Ar].map(o=>[o.moduleName,o]));class be{constructor(e=window,t=[]){this.loadedModules=[],this.wnd=e,this.comms=new rr(e);const i=[...new Set(t)];if(i.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=i.map(n=>{const r=this.loadModule(n);if(r)return r.mount(this.wnd,this.comms),r}).filter(n=>n!==void 0)}}loadModule(e){const t=rt.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=rt.get(e);if(t===void 0)return this.comms.log(`Module "${e}" does not exist in the library`),!1;const i=this.loadedModules.findIndex(n=>n instanceof t);return i<0?!1:(this.loadedModules[i].unmount(this.wnd,this.comms),this.loadedModules.splice(i,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(e=>e.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const Mr={type:"developer_tools",keyCombos:[{keyCode:73,meta:!0,alt:!0},{keyCode:74,meta:!0,alt:!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:123},{keyCode:123,shift:!0},{keyCode:123,ctrl:!0,shift:!0},{keyCode:123,meta:!0,alt:!0}]},Ir={type:"select_all",keyCombos:[{keyCode:65,meta:!0},{keyCode:65,ctrl:!0}]},Fr={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}]},Nr={type:"save",keyCombos:[{keyCode:83,meta:!0},{keyCode:83,ctrl:!0}]};class Ut{mergeKeyboardPeripherals(e,t=[]){const i=[],n=t.filter(r=>!["developer_tools","select_all","print","save"].includes(r.type));e.disableSelectAll&&i.push(Ir),e.disableSave&&i.push(Nr),e.monitorDevTools&&i.push(Mr),e.protectPrinting?.disable&&i.push(Fr);for(const r of n){const s=r.keyCombos.filter(a=>!i.some(l=>l.keyCombos.some(c=>a.keyCode===c.keyCode&&a.ctrl===c.ctrl&&a.shift===c.shift&&a.alt===c.alt&&a.meta===c.meta)));s.length>0&&i.push({...r,keyCombos:s})}return i}}class Dt extends Ut{goLeft(e=!1,t){this.readingProgression===U.ltr?this.goBackward(e,t):this.readingProgression===U.rtl&&this.goForward(e,t)}goRight(e=!1,t){this.readingProgression===U.ltr?this.goForward(e,t):this.readingProgression===U.rtl&&this.goBackward(e,t)}}class Ji extends Ut{}class Zi{constructor(e,t,i,n){this.injector=null,this.pub=e,this.item=i,this.burl=i.toURL(t)||"",this.cssProperties=n.cssProperties,this.injector=n.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),i=t.querySelector("parsererror");if(i){const n=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${n?.textContent||i.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 i in e){const n=e[i];n&&t.documentElement.style.setProperty(i,n)}}finalizeDOM(e,t,i,n,r){if(!e)return"";if(r&&this.setProperties(r,e),e.body.querySelectorAll("img").forEach(a=>{a.setAttribute("fetchpriority","high")}),t!==void 0){const a=e.createElement("base");a.href=t,a.dataset.readium="true",e.head.firstChild.before(a)}let s;return i.string==="application/xhtml+xml"?s=new XMLSerializer().serializeToString(e):s=this.serializeAsHTML(e,n||""),URL.createObjectURL(new Blob([s],{type:i.isHTML?i.string:"application/xhtml+xml"}))}serializeAsHTML(e,t){const i=t.match(/<!DOCTYPE[^>]*>/i),n=i?i[0]+`
|
|
85
|
+
`:"";let s=e.documentElement.outerHTML;return n+s}}const Ur=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=vt()}this.gc=setInterval(()=>{this.registry.forEach((i,n)=>{performance.now()-i.time>Ur&&(console.warn(n,"event for",i.key,"was never handled!"),this.registry.delete(n))})},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 i=this.registry.get(t.id);if(!i)return;this.registry.delete(t.id),i.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,i,n=!1,r=[]){const s=vt();return i&&this.registry.set(s,{cb:i,time:performance.now(),key:e}),this.wnd.postMessage({_readium:me,_channel:this.channelId,id:s,data:t,key:e,strict:n},"/",r),s}}const Dr={RS__oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif"},Wr=16,Qi=Dr.RS__oldStyleTf;class Se{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||Wr,this._fontFace=e.fontFace||Qi,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=Se.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||Qi),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=Se.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 i=0;if(t&&t.length>=e){const n=t.match(/([\s]+)/gi);i=(n?n.length:0)*(e/t.length)}return i}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 i=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(t.font=`${this._baseFontSize}px ${e}`,this._sample&&this._sample.length>=this._optimalChars&&(i=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(i).width;{const n=this._letterSpacing*(this._optimalChars-1),r=this._wordSpacing*Se.approximateWordSpaces(this._optimalChars,this._sample);return t.measureText(i).width+n+r}}else return this.getLineLengthFallback()}}const en=()=>typeof navigator>"u"?"":navigator.userAgent||"",tn=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class nn{constructor(){const e=tn(),t=en(),i=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],n=(r="")=>{if(!r)return[];const s=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(t)?i(t.replace(s,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(r.iOS=n("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?r.iOS=r.iPadOS=n("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=n():r.macOS=n("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?r.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(n("Windows(?: NT)?")):/Android \d/.test(t)?r.Android=n("Android"):/CrOS/.test(t)?r.ChromeOS=n():/X11;/.test(t)&&(r.Linux=n()),r))({}),e&&e.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(s=>{const a=r.platform,l=r.platformVersion;if(!(!a||!l)){if(/^i(OS|P(hone|od touch))$/.test(a))s.iOS=i(l);else if(/^iPad(OS)?$/.test(a))s.iOS=s.iPadOS=i(l);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(a))document.ontouchend!==void 0?s.iOS=s.iPadOS=i():s.macOS=i(l);else if(/^(Microsoft )?Windows$/.test(a))s.Windows=i(l);else if(/^(Google )?Android$/.test(a))s.Android=i(l);else if(/^((Google )?Chrome OS|CrOS)$/.test(a))s.ChromeOS=i(l);else if(/^(Linux|Ubuntu|X11)$/.test(a))s.Linux=i(l);else return;Object.keys(this.OS).forEach(c=>delete this.OS[c]),Object.assign(this.OS,s)}})({})),this.UA=(r=>{let s=!1;if(e&&Array.isArray(e.brands)){const a=e.brands.reduce((l,c)=>(l[c.brand]=[c.version*1],l),{});a["Google Chrome"]?(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Chrome=a["Google Chrome"]):a["Microsoft Edge"]?(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Edge=a["Microsoft Edge"]):a.Opera&&(s=!0,r.Blink=r.Chromium=a.Chromium||[],r.Opera=a.Opera)}return s||(/ Gecko\/\d/.test(t)?(r.Gecko=n("rv"),/ Waterfox\/\d/.test(t)?r.Waterfox=n("Waterfox"):/ Firefox\/\d/.test(t)&&(r.Firefox=n("Firefox"))):/ Edge\/\d/.test(t)?(r.EdgeHTML=n("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(r.Blink=r.Chromium=(a=>a[0]?a:n("Chrome"))(n("Chromium")),/ EdgA?\/\d/.test(t)?r.Edge=(a=>a[0]?a:n("Edg"))(n("EdgA")):/ OPR\/\d/.test(t)?r.Opera=n("OPR"):/ Vivaldi\/\d/.test(t)?r.Vivaldi=n("Vivaldi"):/ Silk\/\d/.test(t)?r.Silk=n("Silk"):/ UCBrowser\/\d/.test(t)?r.UCBrowser=n("UCBrowser"):/ Phoebe\/\d/.test(t)?r.Phoebe=n("Phoebe"):r.Chrome=(a=>a[0]?a:r.Chromium)(n("Chrome"))):/ AppleWebKit\/\d/.test(t)?(r.WebKit=n("AppleWebKit"),/ CriOS \d/.test(t)?r.Chrome=n("CriOS"):/ FxiOS \d/.test(t)?r.Firefox=n("FxiOS"):/ EdgiOS\/\d/.test(t)?r.Edge=n("EdgiOS"):/ Version\/\d/.test(t)&&(r.Safari=n("Version"))):/ Trident\/\d/.test(t)&&(r.Trident=n("Trident"),r.InternetExplorer=(a=>a[0]?a:n("MSIE"))(n("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(r.Facebook=n("FBAV")),/ Line\/\d/.test(t)&&(r.LINE=n("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,s)=>{for(const a in s)s[a]&&r.push(a);return r},[])}}}class Hr extends nn{get iOSRequest(){const e=tn(),t=en();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 nn,A=new Hr;class rn{constructor(e,t={},i=[]){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=[...i]}async load(e=[]){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new be(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async 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,i=>{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,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{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,n):n()})})})}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 on{constructor(e,t,i,n={},r=[]){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=i,this.contentProtectionConfig=n,this.keyboardPeripheralsConfig=[...r]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),this.blobs.clear(),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i){const n=e.readingOrder.items;let r=n.findIndex(l=>l.href===t.href);if(r<0)throw Error(`Locator not found in reading order: ${t.href}`);const s=n[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];e.readingOrder.items.forEach((d,p)=>{p!==r&&p!==r-1&&p!==r+1&&(h.includes(d.href)||h.push(d.href)),p===r&&(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 w=this.blobs.get(d);w&&(this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const w=this.pool.get(d);if(!this.blobs.has(d))await w.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await w.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const z=await new Zi(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,z)}const S=new rn(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);b?.source!==this._currentFrame?.source&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}var Wt,sn;function Br(){if(sn)return Wt;sn=1;function o(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function e(n,r){for(var s="",a=0,l=-1,c=0,h,u=0;u<=n.length;++u){if(u<n.length)h=n.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(s.length<2||a!==2||s.charCodeAt(s.length-1)!==46||s.charCodeAt(s.length-2)!==46){if(s.length>2){var m=s.lastIndexOf("/");if(m!==s.length-1){m===-1?(s="",a=0):(s=s.slice(0,m),a=s.length-1-s.lastIndexOf("/")),l=u,c=0;continue}}else if(s.length===2||s.length===1){s="",a=0,l=u,c=0;continue}}r&&(s.length>0?s+="/..":s="..",a=2)}else s.length>0?s+="/"+n.slice(l+1,u):s=n.slice(l+1,u),a=u-l-1;l=u,c=0}else h===46&&c!==-1?++c:c=-1}return s}function t(n,r){var s=r.dir||r.root,a=r.base||(r.name||"")+(r.ext||"");return s?s===r.root?s+a:s+n+a:a}var i={resolve:function(){for(var r="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=process.cwd()),c=a),o(c),c.length!==0&&(r=c+"/"+r,s=c.charCodeAt(0)===47)}return r=e(r,!s),s?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(r){if(o(r),r.length===0)return".";var s=r.charCodeAt(0)===47,a=r.charCodeAt(r.length-1)===47;return r=e(r,!s),r.length===0&&!s&&(r="."),r.length>0&&a&&(r+="/"),s?"/"+r:r},isAbsolute:function(r){return o(r),r.length>0&&r.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var r,s=0;s<arguments.length;++s){var a=arguments[s];o(a),a.length>0&&(r===void 0?r=a:r+="/"+a)}return r===void 0?".":i.normalize(r)},relative:function(r,s){if(o(r),o(s),r===s||(r=i.resolve(r),s=i.resolve(s),r===s))return"";for(var a=1;a<r.length&&r.charCodeAt(a)===47;++a);for(var l=r.length,c=l-a,h=1;h<s.length&&s.charCodeAt(h)===47;++h);for(var u=s.length,m=u-h,b=c<m?c:m,d=-1,p=0;p<=b;++p){if(p===b){if(m>b){if(s.charCodeAt(h+p)===47)return s.slice(h+p+1);if(p===0)return s.slice(h+p)}else c>b&&(r.charCodeAt(a+p)===47?d=p:p===0&&(d=0));break}var S=r.charCodeAt(a+p),w=s.charCodeAt(h+p);if(S!==w)break;S===47&&(d=p)}var z="";for(p=a+d+1;p<=l;++p)(p===l||r.charCodeAt(p)===47)&&(z.length===0?z+="..":z+="/..");return z.length>0?z+s.slice(h+d):(h+=d,s.charCodeAt(h)===47&&++h,s.slice(h))},_makeLong:function(r){return r},dirname:function(r){if(o(r),r.length===0)return".";for(var s=r.charCodeAt(0),a=s===47,l=-1,c=!0,h=r.length-1;h>=1;--h)if(s=r.charCodeAt(h),s===47){if(!c){l=h;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":r.slice(0,l)},basename:function(r,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');o(r);var a=0,l=-1,c=!0,h;if(s!==void 0&&s.length>0&&s.length<=r.length){if(s.length===r.length&&s===r)return"";var u=s.length-1,m=-1;for(h=r.length-1;h>=0;--h){var b=r.charCodeAt(h);if(b===47){if(!c){a=h+1;break}}else m===-1&&(c=!1,m=h+1),u>=0&&(b===s.charCodeAt(u)?--u===-1&&(l=h):(u=-1,l=m))}return a===l?l=m:l===-1&&(l=r.length),r.slice(a,l)}else{for(h=r.length-1;h>=0;--h)if(r.charCodeAt(h)===47){if(!c){a=h+1;break}}else l===-1&&(c=!1,l=h+1);return l===-1?"":r.slice(a,l)}},extname:function(r){o(r);for(var s=-1,a=0,l=-1,c=!0,h=0,u=r.length-1;u>=0;--u){var m=r.charCodeAt(u);if(m===47){if(!c){a=u+1;break}continue}l===-1&&(c=!1,l=u+1),m===46?s===-1?s=u:h!==1&&(h=1):s!==-1&&(h=-1)}return s===-1||l===-1||h===0||h===1&&s===l-1&&s===a+1?"":r.slice(s,l)},format:function(r){if(r===null||typeof r!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof r);return t("/",r)},parse:function(r){o(r);var s={root:"",dir:"",base:"",ext:"",name:""};if(r.length===0)return s;var a=r.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var h=-1,u=0,m=-1,b=!0,d=r.length-1,p=0;d>=c;--d){if(a=r.charCodeAt(d),a===47){if(!b){u=d+1;break}continue}m===-1&&(b=!1,m=d+1),a===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?s.base=s.name=r.slice(1,m):s.base=s.name=r.slice(u,m)):(u===0&&l?(s.name=r.slice(1,h),s.base=r.slice(1,m)):(s.name=r.slice(u,h),s.base=r.slice(u,m)),s.ext=r.slice(h,m)),u>0?s.dir=r.slice(0,u-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Wt=i,Wt}var ot=Br();const st={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 K=(o=>(o.start="start",o.left="left",o.right="right",o.justify="justify",o))(K||{});const ae={range:[0,100],step:1},Ae={range:[.7,4],step:.05},Z={range:[100,1e3],step:100},Oe={range:[50,250],step:10},Te={range:[0,1],step:.125},ze={range:[1,2],step:.1},le={range:[20,100],step:1},Me={range:[0,3],step:.25},Ie={range:[0,3],step:.25},Fe={range:[0,2],step:.125},Ne={range:[.7,4],step:.05},Ue={range:[0,1],step:.1},De={range:[.5,4],step:.1},Q={range:[5,60],step:5};class We{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 Ht extends We{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 an extends We{constructor(e){super(),this.experiments=e.experiments??null}toCSSProperties(){const e={};return this.experiments&&this.experiments.forEach(t=>{e["--RS__"+t]=st[t].value}),e}}class ln{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 Ht(t)}}function cn(o,e){return o==null||e==null||o<=e?o:void 0}function hn(o,e){return o==null||e==null||o>=e?o:void 0}function N(o){return typeof o=="string"?o:o===null?null:void 0}function E(o){return typeof o=="boolean"||o==null?o:void 0}function He(o,e){if(o!==void 0)return o===null?null:e[o]!==void 0?o:void 0}function ce(o){return typeof o=="boolean"||typeof o=="number"&&o>=0?o:o===null?null:void 0}function _(o){if(o!==void 0)return o===null?null:o<0?void 0:o}function M(o,e){if(o===void 0)return;if(o===null)return null;const t=Math.min(...e),i=Math.max(...e);return o>=t&&o<=i?o:void 0}function at(o,e){return o===void 0?e:o}function Bt(o){if(o!==void 0)return o===null?null:o.filter(e=>e in st)}class _e{constructor(e={}){this.fontFamily=N(e.fontFamily),this.fontWeight=M(e.fontWeight,Z.range),this.hyphens=E(e.hyphens),this.iOSPatch=E(e.iOSPatch),this.iPadOSPatch=E(e.iPadOSPatch),this.letterSpacing=_(e.letterSpacing),this.ligatures=E(e.ligatures),this.lineHeight=_(e.lineHeight),this.noRuby=E(e.noRuby),this.paragraphIndent=_(e.paragraphIndent),this.paragraphSpacing=_(e.paragraphSpacing),this.textAlign=He(e.textAlign,K),this.textNormalization=E(e.textNormalization),this.wordSpacing=_(e.wordSpacing),this.zoom=M(e.zoom,Ne.range)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new _e(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new _e(t)}}class dn{constructor(e){this.fontFamily=N(e.fontFamily)||null,this.fontWeight=M(e.fontWeight,Z.range)||null,this.hyphens=E(e.hyphens)??null,this.iOSPatch=e.iOSPatch===!1?!1:(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:A.OS.iPadOS&&A.iOSRequest==="desktop",this.letterSpacing=_(e.letterSpacing)||null,this.ligatures=E(e.ligatures)??null,this.lineHeight=_(e.lineHeight)||null,this.noRuby=E(e.noRuby)??!1,this.paragraphIndent=_(e.paragraphIndent)??null,this.paragraphSpacing=_(e.paragraphSpacing)??null,this.textAlign=He(e.textAlign,K)||null,this.textNormalization=E(e.textNormalization)??!1,this.wordSpacing=_(e.wordSpacing)||null,this.zoom=M(e.zoom,Ne.range)||1,this.experiments=Bt(e.experiments)??null}}class Vt{constructor(e,t,i){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,i&&(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?(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?A.OS.iPadOS&&A.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:i,onChange:n}){this._value=e,this._effectiveValue=t,this._isEffective=i,this._onChange=n}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 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:i,onChange:n,supportedValues:r}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:n}),this._supportedValues=r}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 C extends T{constructor({initialValue:e=null,effectiveValue:t,isEffective:i,onChange:n,supportedRange:r,step:s}){super({initialValue:e,effectiveValue:t,isEffective:i,onChange:n}),this._supportedRange=r,this._step=s,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 Gt{constructor(e,t,i){this.preferences=e,this.settings=t,this.metadata=i}clear(){this.preferences=new _e({})}updatePreference(e,t){this.preferences[e]=t}get isDisplayTransformable(){return this.metadata?.accessibility?.feature?.some(e=>e.value===$e.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 C({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:Z.range,step:Z.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 C({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Te.range,step:Te.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 C({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:ze.range,step:ze.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 C({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Me.range,step:Me.step})}get paragraphSpacing(){return new C({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:Ie.range,step:Ie.step})}get textAlign(){return new jt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||K.start,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(K)})}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 C({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.isDisplayTransformable,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:Fe.range,step:Fe.step})}get zoom(){return new C({initialValue:this.preferences.zoom,effectiveValue:this.settings.zoom||1,isEffective:CSS.supports("zoom","1")??!1,onChange:e=>{this.updatePreference("zoom",e??null)},supportedRange:Ne.range,step:Ne.step})}}const un=o=>{if("blob"in o&&o.blob.type)return o.blob.type;if(o.as==="script")return"text/javascript";if(o.as==="link"&&"url"in o){const e=o.url.toLowerCase();if(e.endsWith(".css"))return"text/css";if([".js",".mjs",".cjs"].some(t=>e.endsWith(t)))return"text/javascript"}},pn=(o,e)=>{e.attributes&&Object.entries(e.attributes).forEach(([t,i])=>{t==="type"||t==="rel"||t==="href"||t==="src"||i!=null&&(typeof i=="boolean"?i&&o.setAttribute(t,""):o.setAttribute(t,i))})},Vr=(o,e,t)=>{const i=o.createElement("script");i.dataset.readium="true",e.id&&(i.id=e.id);const n=e.type||un(e);return n&&(i.type=n),pn(i,e),i.src=t,i},mn=(o,e,t)=>{const i=o.createElement("link");i.dataset.readium="true",e.id&&(i.id=e.id),e.rel&&(i.rel=e.rel);const n=e.type||un(e);return n&&(i.type=n),pn(i,e),i.href=t,i};class $t{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 i={...t};return t.prepend&&(i.prepend=t.prepend.map(n=>({...n,id:n.id||`injectable-${this.injectableIdCounter++}`})).reverse()),t.append&&(i.append=t.append.map(n=>({...n,id:n.id||`injectable-${this.injectableIdCounter++}`}))),i})}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 i of this.rules)this.matchesRule(i,t)&&await this.applyRule(e,i)}matchesRule(e,t){const i=t.href;return e.resources.some(n=>n instanceof RegExp?n.test(i):i===n)}async getOrCreateBlobUrl(e){const t=e.id;if(this.blobStore.has(t)){const i=this.blobStore.get(t);return i.refCount++,i.url}if("blob"in e){const i=URL.createObjectURL(e.blob);return this.blobStore.set(t,{url:i,refCount:1}),this.createdBlobUrls.add(i),i}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(i=>i.url===e);if(t&&(t.refCount--,t.refCount<=0)){URL.revokeObjectURL(e),this.createdBlobUrls.delete(e);for(const[i,n]of this.blobStore.entries())if(n.url===e){this.blobStore.delete(i);break}}}async getResourceUrl(e,t){if("url"in e){const i=new URL(e.url,t.baseURI).toString();if(!this.isValidUrl(i,t))throw new Error(`Invalid URL: Only HTTPS, data:, blob:, or localhost HTTP URLs are allowed. Got: ${e.url}`);return i}else return this.getOrCreateBlobUrl(e)}createPreloadLink(e,t,i){if(t.as!=="link"||t.rel!=="preload")return;const n={...t,rel:"preload",attributes:{...t.attributes,as:t.as}},r=mn(e,n,i);e.head.appendChild(r)}createElement(e,t,i){if(t.as==="script")return Vr(e,t,i);if(t.as==="link")return mn(e,t,i);throw new Error(`Unsupported element type: ${t.as}`)}async applyRule(e,t){const i=[],n=t.prepend?t.prepend.filter(s=>!s.condition||s.condition(e)):[],r=t.append?t.append.filter(s=>!s.condition||s.condition(e)):[];try{for(const s of n)await this.processInjectable(s,e,i,"prepend");for(const s of r)await this.processInjectable(s,e,i,"append")}catch(s){for(const{element:a,url:l}of i)try{a.remove(),await this.releaseBlobUrl(l)}catch(c){console.error("Error during cleanup:",c)}throw s}}async processInjectable(e,t,i,n){const r=e.target==="body"?t.body:t.head;if(!r)return;let s=null;try{if(s=await this.getResourceUrl(e,t),e.rel==="preload"&&"url"in e)this.createPreloadLink(t,e,s);else{const a=this.createElement(t,e,s);i.push({element:a,url:s}),n==="prepend"?r.prepend(a):r.append(a)}}catch(a){throw console.error("Failed to process resource:",a),s&&"blob"in e&&await this.releaseBlobUrl(s),a}}isValidUrl(e,t){try{const i=new URL(e,t.baseURI);if(i.protocol==="data:"||i.protocol==="blob:"&&this.createdBlobUrls.has(e))return!0;if(this.allowedDomains.length>0){const n=i.origin;return this.allowedDomains.some(r=>{const s=new URL(r).origin;return n===s})}return!1}catch{return!1}}}const we=o=>o.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),lt=o=>o.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," "),jr=`/*!
|
|
86
|
+
* Readium CSS v.2.0.1
|
|
87
87
|
* Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
|
|
88
88
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
89
89
|
* LICENSE file present in the project repository where this source code is maintained.
|
|
@@ -236,8 +236,7 @@
|
|
|
236
236
|
text-indent:var(--USER__paraIndent) !important;
|
|
237
237
|
}
|
|
238
238
|
|
|
239
|
-
:root[style*="--USER__paraIndent"] p
|
|
240
|
-
:root[style*="--USER__paraIndent"] p:first-letter{
|
|
239
|
+
:root[style*="--USER__paraIndent"] p *{
|
|
241
240
|
text-indent:0 !important;
|
|
242
241
|
}
|
|
243
242
|
|
|
@@ -356,11 +355,11 @@
|
|
|
356
355
|
|
|
357
356
|
:root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
|
|
358
357
|
-webkit-text-zoom:normal;
|
|
359
|
-
}`,
|
|
358
|
+
}`,gn='!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})()));',Gr=`// WebPub-specific setup - no execution blocking needed
|
|
360
359
|
window._readium_blockedEvents = [];
|
|
361
360
|
window._readium_blockEvents = false; // WebPub doesn't need event blocking
|
|
362
361
|
window._readium_eventBlocker = null;
|
|
363
|
-
`,
|
|
362
|
+
`,fn=`(function() {
|
|
364
363
|
if(window.onload) window.onload = new Proxy(window.onload, {
|
|
365
364
|
apply: function(target, receiver, args) {
|
|
366
365
|
if(!window._readium_blockEvents) {
|
|
@@ -373,7 +372,7 @@ window._readium_eventBlocker = null;
|
|
|
373
372
|
}
|
|
374
373
|
});
|
|
375
374
|
})();
|
|
376
|
-
`;function
|
|
375
|
+
`;function $r(o){const e=o.filter(r=>r.mediaType.isHTML).map(r=>r.href),t=e.length>0?e:[/\.html$/,/\.xhtml$/,/\/$/],i=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([we(gn)],{type:"text/javascript"})},{id:"webpub-execution",as:"script",target:"head",blob:new Blob([we(Gr)],{type:"text/javascript"})}],n=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([we(fn)],{type:"text/javascript"}),condition:r=>!!(r.querySelector("script")||r.querySelector("body[onload]:not(body[onload=''])"))},{id:"readium-css-webpub",as:"link",target:"head",blob:new Blob([lt(jr)],{type:"text/css"}),rel:"stylesheet"}];return[{resources:t,prepend:i,append:n}]}class Xr{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 qr=0;function Yr(){return++qr}const Kr=`
|
|
377
376
|
onmessage = function(event) {
|
|
378
377
|
var action = event.data;
|
|
379
378
|
var startTime = performance.now()
|
|
@@ -384,7 +383,7 @@ onmessage = function(event) {
|
|
|
384
383
|
time: performance.now() - startTime
|
|
385
384
|
})
|
|
386
385
|
}
|
|
387
|
-
`,
|
|
386
|
+
`,ri=class ri{constructor(e,t){this.callbacks=new Map,this.worker=e,this.blobUrl=t,this.worker.onmessage=i=>{const n=i.data,r=n.id,s=this.callbacks.get(n.id);s&&(s({time:n.time}),this.callbacks.delete(r))},this.log=(...i)=>this.send("log",...i),this.table=(...i)=>this.send("table",...i),this.clear=(...i)=>this.send("clear",...i)}async send(e,...t){const i=Yr();return new Promise((n,r)=>{this.callbacks.set(i,n),this.worker.postMessage({id:i,type:e,payload:t}),setTimeout(()=>{r(new Error("timeout")),this.callbacks.delete(i)},2e3)})}destroy(){this.worker.terminate(),URL.revokeObjectURL(this.blobUrl)}};ri.workerScript=Kr;let ct=ri;function Xt(o){return typeof window<"u"&&console?console[o]:(...e)=>{}}const Jr=Xt("log"),yn=Xt("table"),Zr=Xt("clear");async function bn(){if(typeof navigator<"u"&&navigator.brave&&navigator.brave.isBrave)try{return await Promise.race([navigator.brave.isBrave(),new Promise(o=>setTimeout(()=>o(!1),1e3))])}catch{return!0}return!1}function Qr(o){return o.excludes.some(e=>e())?!1:o.includes.some(e=>e())}class eo{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([ct.workerScript],{type:"application/javascript"}),i=URL.createObjectURL(t),n=new Worker(i);this.workerConsole=new ct(n,i)}catch(t){console.warn("Failed to create Web Worker for DevTools detection:",t)}this.startDetection()}createLargeObjectArray(){const e={};for(let i=0;i<500;i++)e[`${i}`]=`${i}`;const t=[];for(let i=0;i<50;i++)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 i=performance.now();return yn(e),performance.now()-i}else{const t=performance.now();return yn(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 Jr(e),performance.now()-t}}isPerformanceDetectionEnabled(){return Qr({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():Zr(),e===0?!1:this.maxPrintTime===0?!!await bn():e>this.maxPrintTime*10}async checkDebuggerBased(){if(!this.isDebuggerDetectionEnabled()||await bn())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 to{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:i,isCrossOrigin:n}=this.isIframed();i&&!this.detected&&(this.handleDetected(n),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 io{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=`
|
|
388
387
|
@media print {
|
|
389
388
|
body * {
|
|
390
389
|
display: none !important;
|
|
@@ -398,11 +397,11 @@ onmessage = function(event) {
|
|
|
398
397
|
transform: translateY(-50%);
|
|
399
398
|
}
|
|
400
399
|
}
|
|
401
|
-
`,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=i=>(i.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 oo{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 qt{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(de,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new io({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new qr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new no({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new ro({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new oo({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 Kt{constructor(e={}){this.keyManager=new qi,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(ue,{detail:i});window.dispatchEvent(n)};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 so=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class _n extends Wt{constructor(e,t,i,n=void 0,r={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=so(i),this._preferences=new we(r.preferences),this._defaults=new pn(r.defaults),this._settings=new jt(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new hn({rsProperties:new cn({experiments:this._settings.experiments||null}),userProperties:new Bt({zoom:this._settings.zoom})});const s=Yr(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new $t({rules:[...s,...a.rules],allowedDomains:a.allowedDomains}),this._contentProtection=r.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,r.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new qt(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 Kt({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(ue,this._keyboardPeripheralListener)),n&&typeof n.copyWithLocations=="function"){this.currentLocation=n;const l=this.pub.readingOrder.findIndexWithHref(n.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 an(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 Xt(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 Xt(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[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;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===$e.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 i=N.deserialize(t);if(!i)break;this.currentLocation=new N({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new j({href:a}).locator);else try{let l;if(a.startsWith("http://")||a.startsWith("https://"))l=a;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);l=new URL(a,h).href}else l=st.join(st.dirname(this.currentLocation.href),a);const c=this.pub.readingOrder.findWithHref(l);c?this.goLink(c,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new j({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new j({href:a}).locator)}}else console.log("Clicked on",s)}else if(e==="click"?this.listeners.click(n):this.listeners.tap(n))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 r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){return Array.from(ot.keys()).filter(t=>Ir.includes(t))}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),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return i===t?!1:(this.currentIndex=i,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(i=>{t(i)})}goForward(e,t){this.changeResource(1).then(i=>{t(i)})}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 i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(n))return i(this.listeners.handleLocator(e));const s=this.pub.readingOrder.findIndexWithHref(n);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,a=>i(a))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const n=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 k({fragments:[],progression:n,position:this.currentIndex+1})})}}const ao=_n,lo=o=>{const e=o.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 wn{constructor(e,t,i,n){this.injector=null,this.pub=e,this.item=i,this.burl=i.toURL(t)||"",this.cssProperties=n.cssProperties,this.injector=n.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 i=new DOMParser().parseFromString(t,this.item.mediaType.string),n=i.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${r?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(i,this.item),this.finalizeDOM(i,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 i in e){const n=e[i];n&&t.documentElement.style.setProperty(i,n)}}finalizeDOM(e,t,i,n,r=!1,s){if(!e)return"";const a=this.injector?.getAllowedDomains?.()||[],l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high")}),n.isHTML&&this.pub.metadata.languages?.[0]){const h=this.pub.metadata.languages[0];if(n===g.XHTML){const u=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),m=document.body.lang||document.body.getAttribute("xml:lang");m&&!u?(document.documentElement.lang=m,document.documentElement.setAttribute("xml:lang",m),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):u||(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=h)}if(i!==void 0){const h=e.createElement("base");h.href=i,h.dataset.readium="true",e.head.firstChild.before(h)}const c=e.createElement("meta");return c.httpEquiv="Content-Security-Policy",c.content=lo(l),c.dataset.readium="true",e.head.firstChild.before(c),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:n.isHTML?n.string:"application/xhtml+xml"}))}}class Pn{constructor(e,t={},i=[]){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=[...i]}async load(e){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ve(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new ve(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async 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,i=>{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 Se(this.frame.contentWindow,this.source),new Promise((t,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{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,n):n()})})})}setCSSProperties(e){this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?this.comms?.resume():this.comms=new Se(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 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 En=5,kn=3;class Cn{constructor(e,t,i,n,r,s){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=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i,n=!1){let r=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(r<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 s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+En||p<r-En)&&(h.includes(d.href)||h.push(d.href)),p<r+kn&&p>r-kn&&(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(n&&(this.blobs.forEach(w=>{this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const w=this.blobs.get(d);w&&(this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const w=this.pool.get(d);if(!this.blobs.has(d))await w.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await w.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const z=await new wn(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,z)}const S=new Pn(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);(b?.source!==this._currentFrame?.source||n)&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}class xn{constructor(e,t,i,n={},r=[]){this.currModules=[],this.cachedPage=void 0,this.peripherals=e,this.debugHref=i,this.contentProtectionConfig={...n},this.keyboardPeripheralsConfig=[...r],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=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===U.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((i,n)=>{if(this.loader&&this.loaded){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{i(r),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new ve(r,e),this.currModules=e,this.comms=void 0;try{i(r),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const r=this.frame.contentWindow;this.loader=new ve(r,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(r);try{i(r)}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{n(r.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 i=/(\w+) *= *([^\s,]+)/g;let n,r=0,s=0;for(;n=i.exec(t.content);)n[1]==="width"?r=Number.parseFloat(n[2]):n[1]==="height"&&(s=Number.parseFloat(n[2]));if(r>0&&s>0)return{width:r,height:s}}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 i=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${i})`;const n=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-n.height;if(this.frame.style.top=`${r/2}px`,e===X.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===X.center){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s/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(){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",i=>{try{this.showPromise=void 0,t(i.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,i=>{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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),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 Se(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,i)=>{this.comms.send("focus",void 0,n=>{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 Ln=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(Ln||{}),Rn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(Rn||{});class An{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 i={X:0,Y:0};return/^touch/.test(e.type)?(i.X=e.touches[t].screenX,i.Y=e.touches[t].screenY):(i.X=e.screenX,i.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(i.X-=this.HTML.scrollLeft+this.Body.scrollLeft,i.Y-=this.HTML.scrollTop+this.Body.scrollTop),i.X-=this.outerWidth,i.Y-=this.outerHeight,i}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,i=e.touches[0].screenY-this.outerHeight,n=e.touches[1].screenX-this.outerWidth,r=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(n-t,2)+Math.pow(r-i,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,n=e.touches[0].screenX-this.outerWidth-t,r=e.touches[0].screenY-this.outerHeight-i,s=e.touches[1].screenX-this.outerWidth-t,a=e.touches[1].screenY-this.outerHeight-i;return{X:(n+s)/2,Y:(r+a)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let i=.3;const n={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let r,s,a,l;a=r=i,l=s=1-i;const c={X:null,Y:null};return n.X<a?c.X=0:l<n.X?c.X=2:c.X=1,n.Y<r?c.Y=0:s<n.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:c}}}class co{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 On=6,Jt=1.02,Tn=50;class zn{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 An,this.attachEvents(),t&&(this.debugger=new co)}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<Jt&&(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 n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.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 i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.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)>Tn&&Math.abs(this.pan.overscrollY)<Tn/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<Jt&&(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 i=this.coordinator?.getTouchDistance(e);let n=!1;const r=this.scale;if(this.dragState===2&&i){if(this.pinch.touchN++,this.pinch.touchN<4)return;let s=i/this.pinch.startDistance*this.scale;s>=On&&(s=On),s<=Jt&&(s=1),this.scale=s,this.pinch.startDistance=i,n=!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 b=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${b.Y-10}px`,this.debugger.DOM.touch2.style.left=`${b.X-10}px`,this.debugger.DOM.touch2.innerText=`${b.X.toFixed(2)},${b.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/r;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/r;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 s=this.frameBounds.width/6,a=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-a&&(this.pan.overscrollY=-(a+this.pan.translateY),this.pan.translateY=-a),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>a&&(this.pan.overscrollY=a-this.pan.translateY,this.pan.translateY=a),n=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
400
|
+
`,document.head.appendChild(t),this.styleElement=t,this.beforePrintHandler=i=>(i.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 no{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 he="readium:navigator:suspiciousActivity";class qt{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(he,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new eo({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new Xr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new to({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new io({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new no({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const de="readium:navigator:keyboardPeripheral";class Yt{constructor(e={}){this.keyManager=new qi,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(de,{detail:i});window.dispatchEvent(n)};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 ro=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class vn extends Dt{constructor(e,t,i,n=void 0,r={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=ro(i),this._preferences=new _e(r.preferences),this._defaults=new dn(r.defaults),this._settings=new Vt(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new ln({rsProperties:new an({experiments:this._settings.experiments||null}),userProperties:new Ht({zoom:this._settings.zoom})});const s=$r(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new $t({rules:[...s,...a.rules],allowedDomains:a.allowedDomains}),this._contentProtection=r.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,r.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new qt(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(he,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new Yt({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const c=l.detail;this.listeners.peripheral(c)},window.addEventListener(de,this._keyboardPeripheralListener)),n&&typeof n.copyWithLocations=="function"){this.currentLocation=n;const l=this.pub.readingOrder.findIndexWithHref(n.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 on(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 Gt(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 Vt(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Gt(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[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;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===$e.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 i=F.deserialize(t);if(!i)break;this.currentLocation=new F({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new j({href:a}).locator);else try{let l;if(a.startsWith("http://")||a.startsWith("https://"))l=a;else if(this.currentLocation.href.startsWith("http://")||this.currentLocation.href.startsWith("https://")){const h=new URL(this.currentLocation.href);l=new URL(a,h).href}else l=ot.join(ot.dirname(this.currentLocation.href),a);const c=this.pub.readingOrder.findWithHref(l);c?this.goLink(c,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new j({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new j({href:a}).locator)}}else console.log("Clicked on",s)}else if(e==="click"?this.listeners.click(n):this.listeners.tap(n))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 r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);break;case"log":console.log(this.framePool.currentFrames[0]?.source?.split("/")[3],...t);break;default:this.listeners.customEvent(e,t);break}}determineModules(){return Array.from(rt.keys()).filter(t=>zr.includes(t))}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(he,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(de,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),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));return i===t?!1:(this.currentIndex=i,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(i=>{t(i)})}goForward(e,t){this.changeResource(1).then(i=>{t(i)})}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 i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];if(!this.pub.readingOrder.findWithHref(n))return i(this.listeners.handleLocator(e));const s=this.pub.readingOrder.findIndexWithHref(n);s>=0&&(this.currentIndex=s),this.currentLocation=this.createCurrentLocator(),this.apply().then(()=>this.loadLocator(e,a=>i(a))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}createCurrentLocator(){const t=this.pub.readingOrder.items[this.currentIndex];if(!t)throw new Error("No current resource available");const n=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:n,position:this.currentIndex+1})})}}const oo=vn,so=o=>{const e=o.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 Sn{constructor(e,t,i,n){this.injector=null,this.pub=e,this.item=i,this.burl=i.toURL(t)||"",this.cssProperties=n.cssProperties,this.injector=n.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 i=new DOMParser().parseFromString(t,this.item.mediaType.string),n=i.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${r?.textContent||n.textContent}`)}return this.injector&&await this.injector.injectForDocument(i,this.item),this.finalizeDOM(i,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 i in e){const n=e[i];n&&t.documentElement.style.setProperty(i,n)}}finalizeDOM(e,t,i,n,r=!1,s){if(!e)return"";const a=this.injector?.getAllowedDomains?.()||[],l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(h=>{h.setAttribute("fetchpriority","high")}),n.isHTML&&this.pub.metadata.languages?.[0]){const h=this.pub.metadata.languages[0];if(n===g.XHTML){const u=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),m=document.body.lang||document.body.getAttribute("xml:lang");m&&!u?(document.documentElement.lang=m,document.documentElement.setAttribute("xml:lang",m),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):u||(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=h)}if(i!==void 0){const h=e.createElement("base");h.href=i,h.dataset.readium="true",e.head.firstChild.before(h)}const c=e.createElement("meta");return c.httpEquiv="Content-Security-Policy",c.content=so(l),c.dataset.readium="true",e.head.firstChild.before(c),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(e)],{type:n.isHTML?n.string:"application/xhtml+xml"}))}}class _n{constructor(e,t={},i=[]){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=[...i]}async load(e){return new Promise((t,i)=>{if(this.loader){const n=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{t(n)}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(n,e),this.currModules=e,this.comms=void 0;try{t(n)}catch{}return}this.frame.onload=()=>{const n=this.frame.contentWindow;this.loader=new be(n,e),this.currModules=e;try{t(n)}catch{}},this.frame.onerror=n=>{try{i(n)}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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),this.contentProtectionConfig.monitorScrollingExperimental&&this.comms.send("scroll_protection",{}),this.contentProtectionConfig.protectPrinting?.disable&&this.comms.send("print_protection",this.contentProtectionConfig.protectPrinting)}async 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,i=>{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,i)=>{this.comms?.send("activate",void 0,()=>{this.comms?.send("focus",void 0,()=>{this.applyContentProtection();const n=()=>{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,n):n()})})})}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 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 wn=5,Pn=3;class En{constructor(e,t,i,n,r,s){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=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[]}async destroy(){let e=this.inprogress.values(),t=e.next();const i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>{this.injector?.releaseBlobUrl?.(s),URL.revokeObjectURL(s)}),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(e,t,i,n=!1){let r=this.positions.findIndex(l=>l.locations.position===t.locations.position);if(r<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 s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+wn||p<r-wn)&&(h.includes(d.href)||h.push(d.href)),p<r+Pn&&p>r-Pn&&(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(n&&(this.blobs.forEach(w=>{this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const w=this.blobs.get(d);w&&(this.injector?.releaseBlobUrl?.(w),URL.revokeObjectURL(w),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const w=this.pool.get(d);if(!this.blobs.has(d))await w.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await w.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const z=await new Sn(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,z)}const S=new _n(this.blobs.get(d),this.contentProtectionConfig,this.keyboardPeripheralsConfig);d!==s&&await S.hide(),this.container.appendChild(S.iframe),await S.load(i),this.pool.set(d,S)};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=this.pool.get(s);(b?.source!==this._currentFrame?.source||n)&&(await this._currentFrame?.hide(),b&&await b.load(i),b&&await b.show(t.locations.progression),this._currentFrame=b),l()});this.inprogress.set(s,a),await a,this.inprogress.delete(s)}setCSSProperties(e){if(!((i,n)=>{const r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const a of r)if(i[a]!==n[a])return!1;return!0})(this.currentCssProperties||{},e)){this.currentCssProperties=e,this.pool.forEach(i=>{i.setCSSProperties(e)});for(const i of this.blobs.keys())this.pendingUpdates.set(i,{inPool:this.pool.has(i)})}}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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}}class kn{constructor(e,t,i,n={},r=[]){this.currModules=[],this.cachedPage=void 0,this.peripherals=e,this.debugHref=i,this.contentProtectionConfig={...n},this.keyboardPeripheralsConfig=[...r],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=i,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===U.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((i,n)=>{if(this.loader&&this.loaded){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...e].sort().join("|")){try{i(r),this.loadPromise=void 0}catch{}return}this.comms?.halt(),this.loader.destroy(),this.loader=new be(r,e),this.currModules=e,this.comms=void 0;try{i(r),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const r=this.frame.contentWindow;this.loader=new be(r,e),this.currModules=e,this.peripherals.observe(this.wrapper),this.peripherals.observe(r);try{i(r)}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{n(r.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 i=/(\w+) *= *([^\s,]+)/g;let n,r=0,s=0;for(;n=i.exec(t.content);)n[1]==="width"?r=Number.parseFloat(n[2]):n[1]==="height"&&(s=Number.parseFloat(n[2]));if(r>0&&s>0)return{width:r,height:s}}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 i=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${i})`;const n=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-n.height;if(this.frame.style.top=`${r/2}px`,e===$.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===$.center){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s/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(){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",i=>{try{this.showPromise=void 0,t(i.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,i=>{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.comms.send("keyboard_peripherals",this.keyboardPeripheralsConfig),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,i)=>{this.comms.send("focus",void 0,n=>{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 Cn=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(Cn||{}),xn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(xn||{});class Ln{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 i={X:0,Y:0};return/^touch/.test(e.type)?(i.X=e.touches[t].screenX,i.Y=e.touches[t].screenY):(i.X=e.screenX,i.Y=e.screenY),(e.target.ownerDocument?.documentElement||e.target.documentElement)===this.HTML&&(i.X-=this.HTML.scrollLeft+this.Body.scrollLeft,i.Y-=this.HTML.scrollTop+this.Body.scrollTop),i.X-=this.outerWidth,i.Y-=this.outerHeight,i}getTouchDistance(e){if(e.touches.length!==2)return 0;const t=e.touches[0].screenX-this.outerWidth,i=e.touches[0].screenY-this.outerHeight,n=e.touches[1].screenX-this.outerWidth,r=e.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(n-t,2)+Math.pow(r-i,2))}getTouchCenter(e){if(e.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,i=this.HTML.scrollTop+this.Body.scrollTop,n=e.touches[0].screenX-this.outerWidth-t,r=e.touches[0].screenY-this.outerHeight-i,s=e.touches[1].screenX-this.outerWidth-t,a=e.touches[1].screenY-this.outerHeight-i;return{X:(n+s)/2,Y:(r+a)/2}}getBibiEvent(e){if(!e)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(e);let i=.3;const n={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let r,s,a,l;a=r=i,l=s=1-i;const c={X:null,Y:null};return n.X<a?c.X=0:l<n.X?c.X=2:c.X=1,n.Y<r?c.Y=0:s<n.Y?c.Y=2:c.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:c}}}class ao{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 Rn=6,Kt=1.02,An=50;class On{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 Ln,this.attachEvents(),t&&(this.debugger=new ao)}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<Kt&&(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 n=this.startTouch(e);this.pan.startX=n.X,this.pan.startY=n.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 i=this.startTouch(e);this.pan.startX=i.X,this.pan.startY=i.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)>An&&Math.abs(this.pan.overscrollY)<An/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<Kt&&(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 i=this.coordinator?.getTouchDistance(e);let n=!1;const r=this.scale;if(this.dragState===2&&i){if(this.pinch.touchN++,this.pinch.touchN<4)return;let s=i/this.pinch.startDistance*this.scale;s>=Rn&&(s=Rn),s<=Kt&&(s=1),this.scale=s,this.pinch.startDistance=i,n=!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 b=this.coordinator.getBibiEventCoord(e,1);this.debugger.DOM.touch2.style.top=`${b.Y-10}px`,this.debugger.DOM.touch2.style.left=`${b.X-10}px`,this.debugger.DOM.touch2.innerText=`${b.X.toFixed(2)},${b.Y.toFixed(2)}`}l.X-=this.manager.width/2,l.Y-=this.manager.height/2;let c=-l.X/r;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/r;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 s=this.frameBounds.width/6,a=this.frameBounds.height/6;this.pan.translateX<-s&&(this.pan.overscrollX=-(s+this.pan.translateX),this.pan.translateX=-s),this.pan.translateY<-a&&(this.pan.overscrollY=-(a+this.pan.translateY),this.pan.translateY=-a),this.pan.translateX>s&&(this.pan.overscrollX=s-this.pan.translateX,this.pan.translateX=s),this.pan.translateY>a&&(this.pan.overscrollY=a-this.pan.translateY,this.pan.translateY=a),n=!0,this.debugger?.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
|
|
402
401
|
TY: ${this.pan.translateY.toFixed(2)}
|
|
403
402
|
Zoom: ${this.scale.toFixed(2)}
|
|
404
|
-
Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(n){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const a=this.manager.currentSlide*(this.manager.width/this.manager.perPage),l=this.pan.endX-this.pan.startX,c=this.manager.rtl?a+l:a-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 dt=(o=>(o.auto="auto",o.landscape="landscape",o.portrait="portrait",o))(dt||{}),ut=(o=>(o.auto="auto",o.both="both",o.none="none",o.landscape="landscape",o))(ut||{});class Mn{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((i,n)=>{t||(e.readingOrder.items[n]=i.addProperties({number:n+1,isImage:i.type?.indexOf("image/")===0}));const r=i.properties?.otherProperties.orientation==="landscape";(!i.properties?.page||t)&&(i.properties=i.properties?.add({page:r?"center":((this.shift?0:1)+n-this.nLandscape)%2?e.metadata.readingProgression===U.rtl?"right":"left":e.metadata.readingProgression===U.rtl?"left":"right"})),(r||i.properties?.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(e.readingOrder)}testShift(e){let t=!1;this.spreads.forEach((i,n)=>{if(i.length>1)return;const r=i[0],s=r.properties?.otherProperties.orientation;n===0&&(s==="landscape"||s!=="portrait"&&((r.width||0)>(r.height||0)||r.properties?.otherProperties.spread==="both"))&&(this.shift=!1),t&&r.properties?.page===X.center&&this.spreads[n-1][0].addProperties({addBlank:!0}),s==="portrait"&&r.properties?.page!=="center"&&r.properties?.otherProperties.number>1?t=!0:t=!1}),this.shift||this.index(e,!0)}buildSpreads(e){let t=[];e.items.forEach((i,n)=>{!n&&this.shift?this.spreads.push([i]):i.properties?.page===X.center?(t.length>0&&this.spreads.push(t),this.spreads.push([i]),t=[]):t.length>=2?(this.spreads.push(t),t=[i]):t.push(i)}),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 In=8,Nn=5,ho=300,uo=15e3,po=250,mo=150,go=500;class Fn{constructor(e,t,i,n,r,s){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=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[],this.spreadPresentation=i.metadata.otherMetadata?.spread||ut.auto,this.pub.metadata.effectiveReadingProgression!==U.rtl&&this.pub.metadata.effectiveReadingProgression!==U.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Mn(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 zn(this),this.pub.readingOrder.items.forEach(a=>{const l=new xn(this.peripherals,this.pub.metadata.effectiveReadingProgression,a.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.spineElement.appendChild(l.element),this.pool.set(a.href,l),l.width=100/this.length*(a.properties?.otherProperties.orientation===dt.landscape||a.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((i,n)=>{let r=this.pub.readingOrder.items.findIndex(l=>l.href===n);const s=this.pub.readingOrder.items[r];if(i.width=100/this.length*(s.properties?.otherProperties.orientation===dt.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),i.height=this.height,!i.loaded)return;const a=this.spreader.findByLink(s);i.update(this.spreadPosition(a,s))})},po)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===U.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===ut.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(e,t=!0){let i="0";this.updateDimensions(),this.perPage>1&&(i=`${this.width/2}px`);const n={transition:e?`all ${t?mo:go}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?i:"0",marginLeft:this.rtl?"0":i,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,n)}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 i=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==i&&(this.transform=i,this.updateSpineStyle(!0,t),this.deselect())})});else{const i=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===i)return;this.transform=i,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 i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.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,i,n=!1){let r=this.pub.readingOrder.items.findIndex(l=>l.href===t.href);if(r<0)throw Error("Href not found in reading order");this.currentSlide!==r&&(this.currentSlide=this.reAlign(r),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&r++;for(const l of s)await this.waitForItem(l.href);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+In||p<r-In)&&(h.includes(d.href)||h.push(d.href)),p<r+Nn&&p>r-Nn&&(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),S=e.readingOrder.items[p];if(S){if(!this.blobs.has(d)){const z=await new wn(e,this.currentBaseURL||"",S,{injector:this.injector}).build(!0);this.blobs.set(d,z)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((w,z)=>{let oe=!1;const Io=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const No=this.makeSpread(this.reAlign(p)),Fo=this.spreadPosition(No,S),Jn=this.pool.get(d);await Jn.load(i,this.blobs.get(d)),this.peripherals.isScaled||await Jn.show(Fo),this.delayedShow.delete(d),oe=!0,w()},ho);setTimeout(()=>{!oe&&this.delayedShow.has(d)&&z(`Offscreen load timeout: ${d}`)},uo),this.delayedTimeout.set(d,Io)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=[];for(const d of s){const p=this.pool.get(d.href),S=this.blobs.get(d.href);S&&(this.cancelShowing(d.href),await p.load(i,S),await p.show(this.spreadPosition(s,d)),this.previousFrames.push(p),await p.activate(),b.push(p))}for(;this.previousFrames.length>0;){const d=this.previousFrames.shift();d&&!b.includes(d)&&await d.unfocus()}this.previousFrames=b,l()});for(const l of s)this.inprogress.set(l.href,a);await a;for(const l of s)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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}get viewport(){const e={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(i=>{e.readingOrder.push(i.href),e.progressions.set(i.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 Ee{constructor(e={}){this.backgroundColor=F(e.backgroundColor),this.blendFilter=E(e.blendFilter),this.constraint=_(e.constraint),this.columnCount=_(e.columnCount),this.darkenFilter=he(e.darkenFilter),this.deprecatedFontSize=E(e.deprecatedFontSize),this.fontFamily=F(e.fontFamily),this.fontSize=M(e.fontSize,Oe.range),this.fontSizeNormalize=E(e.fontSizeNormalize),this.fontOpticalSizing=E(e.fontOpticalSizing),this.fontWeight=M(e.fontWeight,Z.range),this.fontWidth=M(e.fontWidth,Te.range),this.hyphens=E(e.hyphens),this.invertFilter=he(e.invertFilter),this.invertGaijiFilter=he(e.invertGaijiFilter),this.iOSPatch=E(e.iOSPatch),this.iPadOSPatch=E(e.iPadOSPatch),this.letterSpacing=_(e.letterSpacing),this.ligatures=E(e.ligatures),this.lineHeight=_(e.lineHeight),this.linkColor=F(e.linkColor),this.noRuby=E(e.noRuby),this.pageGutter=_(e.pageGutter),this.paragraphIndent=_(e.paragraphIndent),this.paragraphSpacing=_(e.paragraphSpacing),this.scroll=E(e.scroll),this.scrollPaddingTop=_(e.scrollPaddingTop),this.scrollPaddingBottom=_(e.scrollPaddingBottom),this.scrollPaddingLeft=_(e.scrollPaddingLeft),this.scrollPaddingRight=_(e.scrollPaddingRight),this.selectionBackgroundColor=F(e.selectionBackgroundColor),this.selectionTextColor=F(e.selectionTextColor),this.textAlign=Be(e.textAlign,K),this.textColor=F(e.textColor),this.textNormalization=E(e.textNormalization),this.visitedColor=F(e.visitedColor),this.wordSpacing=_(e.wordSpacing),this.optimalLineLength=_(e.optimalLineLength),this.maximalLineLength=_(e.maximalLineLength),this.minimalLineLength=_(e.minimalLineLength)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Ee(t)}catch(t){return console.error("Failed to deserialize preferences:",t),null}}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(i!=="maximalLineLength"||e[i]===null||e[i]>=(e.optimalLineLength??t.optimalLineLength??65))&&(i!=="minimalLineLength"||e[i]===null||e[i]<=(e.optimalLineLength??t.optimalLineLength??65))&&(t[i]=e[i]);return new Ee(t)}}class Un{constructor(e){this.backgroundColor=F(e.backgroundColor)||null,this.blendFilter=E(e.blendFilter)??!1,this.constraint=_(e.constraint)||0,this.columnCount=_(e.columnCount)||null,this.darkenFilter=he(e.darkenFilter)??!1,this.deprecatedFontSize=E(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=F(e.fontFamily)||null,this.fontSize=M(e.fontSize,Oe.range)||1,this.fontSizeNormalize=E(e.fontSizeNormalize)??!1,this.fontOpticalSizing=E(e.fontOpticalSizing)??null,this.fontWeight=M(e.fontWeight,Z.range)||null,this.fontWidth=M(e.fontWidth,Te.range)||null,this.hyphens=E(e.hyphens)??null,this.invertFilter=he(e.invertFilter)??!1,this.invertGaijiFilter=he(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:A.OS.iPadOS&&A.iOSRequest==="desktop",this.letterSpacing=_(e.letterSpacing)||null,this.ligatures=E(e.ligatures)??null,this.lineHeight=_(e.lineHeight)||null,this.linkColor=F(e.linkColor)||null,this.noRuby=E(e.noRuby)??!1,this.pageGutter=lt(_(e.pageGutter),20),this.paragraphIndent=_(e.paragraphIndent)??null,this.paragraphSpacing=_(e.paragraphSpacing)??null,this.scroll=E(e.scroll)??!1,this.scrollPaddingTop=_(e.scrollPaddingTop)??null,this.scrollPaddingBottom=_(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=_(e.scrollPaddingLeft)??null,this.scrollPaddingRight=_(e.scrollPaddingRight)??null,this.selectionBackgroundColor=F(e.selectionBackgroundColor)||null,this.selectionTextColor=F(e.selectionTextColor)||null,this.textAlign=Be(e.textAlign,K)||null,this.textColor=F(e.textColor)||null,this.textNormalization=E(e.textNormalization)??!1,this.visitedColor=F(e.visitedColor)||null,this.wordSpacing=_(e.wordSpacing)||null,this.optimalLineLength=_(e.optimalLineLength)||65,this.maximalLineLength=lt(un(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=lt(dn(e.minimalLineLength,this.optimalLineLength),40),this.experiments=Vt(e.experiments)||null}}const ke={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class Zt{constructor(e,t,i){this.preferences=e,this.settings=t,this.metadata=i,this.layout=this.metadata?.effectiveLayout||v.reflowable}clear(){this.preferences=new Ee({optimalLineLength:65})}updatePreference(e,t){this.preferences[e]=t}get backgroundColor(){return new T({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||ke.RS__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 T({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==v.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 C({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!==v.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!==v.fixed,onChange:e=>{this.updatePreference("fontFamily",e||null)}})}get fontSize(){return new C({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("fontSize",e||null)},supportedRange:Oe.range,step:Oe.step})}get fontSizeNormalize(){return new O({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==v.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!==v.fixed&&this.preferences.fontOpticalSizing!==null,onChange:e=>{this.updatePreference("fontOpticalSizing",e||null)}})}get fontWeight(){return new C({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==v.fixed&&this.preferences.fontWeight!==null,onChange:e=>{this.updatePreference("fontWeight",e||null)},supportedRange:Z.range,step:Z.step})}get fontWidth(){return new C({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==v.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!==v.fixed&&this.metadata?.effectiveReadingProgression===U.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e||null)}})}get invertFilter(){return new C({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 C({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!==v.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!==v.fixed,onChange:e=>{this.updatePreference("iPadOSPatch",e||null)}})}get letterSpacing(){return new C({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.letterSpacing!==null,onChange:e=>{this.updatePreference("letterSpacing",e||null)},supportedRange:ze.range,step:ze.step})}get ligatures(){return new O({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:(()=>{if(this.preferences.ligatures===null||this.layout===v.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 C({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==v.fixed&&this.preferences.lineHeight!==null,onChange:e=>{this.updatePreference("lineHeight",e||null)},supportedRange:Me.range,step:Me.step})}get linkColor(){return new T({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||ke.RS__linkColor,isEffective:this.layout!==v.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e||null)}})}get maximalLineLength(){return new C({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:ce.range,step:ce.step})}get minimalLineLength(){return new C({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==v.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!==v.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:e=>{this.updatePreference("noRuby",e||null)}})}get optimalLineLength(){return new C({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==v.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!==v.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("pageGutter",e||null)}})}get paragraphIndent(){return new C({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphIndent!==null,onChange:e=>{this.updatePreference("paragraphIndent",e||null)},supportedRange:Ie.range,step:Ie.step})}get paragraphSpacing(){return new C({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphSpacing!==null,onChange:e=>{this.updatePreference("paragraphSpacing",e||null)},supportedRange:Ne.range,step:Ne.step})}get scroll(){return new O({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==v.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!==v.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!==v.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!==v.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!==v.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||ke.RS__selectionBackgroundColor,isEffective:this.layout!==v.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||ke.RS__selectionTextColor,isEffective:this.layout!==v.fixed&&this.preferences.selectionTextColor!==null,onChange:e=>{this.updatePreference("selectionTextColor",e||null)}})}get textAlign(){return new Gt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||K.start,isEffective:this.layout!==v.fixed&&this.preferences.textAlign!==null,onChange:e=>{this.updatePreference("textAlign",e||null)},supportedValues:Object.values(K)})}get textColor(){return new T({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||ke.RS__textColor,isEffective:this.layout!==v.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!==v.fixed,onChange:e=>{this.updatePreference("textNormalization",e||null)}})}get visitedColor(){return new T({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||ke.RS__visitedColor,isEffective:this.layout!==v.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e||null)}})}get wordSpacing(){return new C({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.wordSpacing!==null,onChange:e=>{this.updatePreference("wordSpacing",e||null)},supportedRange:Fe.range,step:Fe.step})}}class Qt{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?(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?A.OS.iPadOS&&A.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 pt(o){const e=getComputedStyle(o),t=parseFloat(e.paddingLeft||"0"),i=parseFloat(e.paddingRight||"0");return o.clientWidth-t-i}class ei extends He{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 Dn extends He{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]=at[t].value}),e}}class Wn{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.cachedColCount=e.userProperties.colCount,this.effectiveContainerWidth=pt(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 i={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 ei(i)}updateLayout(e,t,i,n){return i??this.userProperties.view==="scroll"?this.computeScrollLength(e,t):this.paginate(e,t,n)}getCompensatedMetrics(e,t){const i=e||this.userProperties.fontSize||1,n=i<1?1/i:t?i:1;return{zoomFactor:i,zoomCompensation:n,optimal:Math.round(this.lineLengths.optimalLineLength)*i,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*i):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*i):null}}paginate(e,t,i){const n=Math.round(pt(this.containerParent)-this.constraint),r=this.getCompensatedMetrics(e,t),{zoomCompensation:s,optimal:a,minimal:l,maximal:c}=r,h=()=>n>=a&&c!==null?Math.min(Math.round(c*s),n):n;let u=1,m=n;if(i===void 0)return{colCount:void 0,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u*s)};if(i===null)if(n>=a&&c!==null){u=Math.floor(n/a);const b=Math.round(u*(c*s));m=Math.min(b,n)}else m=h();else if(i>1){const b=Math.round(i*(l!==null?l:a));if(n>=b)if(u=i,c===null)m=n;else{const d=Math.round(u*(c*s));m=Math.min(d,n)}else if(l!==null&&n<Math.round(i*l))if(u=Math.floor(n/l),u<=1)u=1,m=h();else{const d=Math.round(u*(a*s));m=Math.min(d,n)}else{u=i;const d=Math.round(u*(a*s));m=Math.min(d,n)}}else u=1,m=h();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*s)}}computeScrollLength(e,t){const i=Math.round(pt(this.containerParent)-this.constraint),n=this.getCompensatedMetrics(e&&(e<1||t)?e:1,t),r=n.zoomCompensation,s=n.optimal,a=n.maximal;let l,c=i,h=Math.round(s*r);if(a===null)h=i;else{const u=Math.min(Math.round(a*r),i);h=t?u:Math.round(u*r)}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 fo=`/*!
|
|
405
|
-
* Readium CSS v.2.0.
|
|
403
|
+
Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(n){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const a=this.manager.currentSlide*(this.manager.width/this.manager.perPage),l=this.pan.endX-this.pan.startX,c=this.manager.rtl?a+l:a-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 ht=(o=>(o.auto="auto",o.landscape="landscape",o.portrait="portrait",o))(ht||{}),dt=(o=>(o.auto="auto",o.both="both",o.none="none",o.landscape="landscape",o))(dt||{});class Tn{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((i,n)=>{t||(e.readingOrder.items[n]=i.addProperties({number:n+1,isImage:i.type?.indexOf("image/")===0}));const r=i.properties?.otherProperties.orientation==="landscape";(!i.properties?.page||t)&&(i.properties=i.properties?.add({page:r?"center":((this.shift?0:1)+n-this.nLandscape)%2?e.metadata.readingProgression===U.rtl?"right":"left":e.metadata.readingProgression===U.rtl?"left":"right"})),(r||i.properties?.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(e.readingOrder)}testShift(e){let t=!1;this.spreads.forEach((i,n)=>{if(i.length>1)return;const r=i[0],s=r.properties?.otherProperties.orientation;n===0&&(s==="landscape"||s!=="portrait"&&((r.width||0)>(r.height||0)||r.properties?.otherProperties.spread==="both"))&&(this.shift=!1),t&&r.properties?.page===$.center&&this.spreads[n-1][0].addProperties({addBlank:!0}),s==="portrait"&&r.properties?.page!=="center"&&r.properties?.otherProperties.number>1?t=!0:t=!1}),this.shift||this.index(e,!0)}buildSpreads(e){let t=[];e.items.forEach((i,n)=>{!n&&this.shift?this.spreads.push([i]):i.properties?.page===$.center?(t.length>0&&this.spreads.push(t),this.spreads.push([i]),t=[]):t.length>=2?(this.spreads.push(t),t=[i]):t.push(i)}),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 zn=8,Mn=5,lo=300,co=15e3,ho=250,uo=150,po=500;class In{constructor(e,t,i,n,r,s){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=i,this.injector=n??null,this.contentProtectionConfig=r||{},this.keyboardPeripheralsConfig=s||[],this.spreadPresentation=i.metadata.otherMetadata?.spread||dt.auto,this.pub.metadata.effectiveReadingProgression!==U.rtl&&this.pub.metadata.effectiveReadingProgression!==U.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Tn(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 On(this),this.pub.readingOrder.items.forEach(a=>{const l=new kn(this.peripherals,this.pub.metadata.effectiveReadingProgression,a.href,this.contentProtectionConfig,this.keyboardPeripheralsConfig);this.spineElement.appendChild(l.element),this.pool.set(a.href,l),l.width=100/this.length*(a.properties?.otherProperties.orientation===ht.landscape||a.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((i,n)=>{let r=this.pub.readingOrder.items.findIndex(l=>l.href===n);const s=this.pub.readingOrder.items[r];if(i.width=100/this.length*(s.properties?.otherProperties.orientation===ht.landscape||s.properties?.otherProperties.addBlank?this.perPage:1),i.height=this.height,!i.loaded)return;const a=this.spreader.findByLink(s);i.update(this.spreadPosition(a,s))})},ho)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===U.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===dt.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(e,t=!0){let i="0";this.updateDimensions(),this.perPage>1&&(i=`${this.width/2}px`);const n={transition:e?`all ${t?uo:po}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?i:"0",marginLeft:this.rtl?"0":i,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,n)}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 i=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==i&&(this.transform=i,this.updateSpineStyle(!0,t),this.deselect())})});else{const i=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===i)return;this.transform=i,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 i=[];for(;t.value;)i.push(t.value),t=e.next();i.length>0&&await Promise.allSettled(i),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.injector?.dispose(),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.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?$.center:t.href===e[0].href?this.rtl?$.right:$.left:this.rtl?$.left:$.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,i,n=!1){let r=this.pub.readingOrder.items.findIndex(l=>l.href===t.href);if(r<0)throw Error("Href not found in reading order");this.currentSlide!==r&&(this.currentSlide=this.reAlign(r),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&r++;for(const l of s)await this.waitForItem(l.href);const a=new Promise(async(l,c)=>{const h=[],u=[];this.positions.forEach((d,p)=>{(p>r+zn||p<r-zn)&&(h.includes(d.href)||h.push(d.href)),p<r+Mn&&p>r-Mn&&(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),S=e.readingOrder.items[p];if(S){if(!this.blobs.has(d)){const z=await new Sn(e,this.currentBaseURL||"",S,{injector:this.injector}).build(!0);this.blobs.set(d,z)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((w,z)=>{let re=!1;const zo=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const Mo=this.makeSpread(this.reAlign(p)),Io=this.spreadPosition(Mo,S),Yn=this.pool.get(d);await Yn.load(i,this.blobs.get(d)),this.peripherals.isScaled||await Yn.show(Io),this.delayedShow.delete(d),re=!0,w()},lo);setTimeout(()=>{!re&&this.delayedShow.has(d)&&z(`Offscreen load timeout: ${d}`)},co),this.delayedTimeout.set(d,zo)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){c(d)}const b=[];for(const d of s){const p=this.pool.get(d.href),S=this.blobs.get(d.href);S&&(this.cancelShowing(d.href),await p.load(i,S),await p.show(this.spreadPosition(s,d)),this.previousFrames.push(p),await p.activate(),b.push(p))}for(;this.previousFrames.length>0;){const d=this.previousFrames.shift();d&&!b.includes(d)&&await d.unfocus()}this.previousFrames=b,l()});for(const l of s)this.inprogress.set(l.href,a);await a;for(const l of s)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 i=t.realSize;e.x=Math.min(e.x,i.x),e.y=Math.min(e.y,i.y),e.width+=i.width,e.height=Math.max(e.height,i.height),e.top=Math.min(e.top,i.top),e.right=Math.min(e.right,i.right),e.bottom=Math.min(e.bottom,i.bottom),e.left=Math.min(e.left,i.left)}),e}get viewport(){const e={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(i=>{e.readingOrder.push(i.href),e.progressions.set(i.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 Pe{constructor(e={}){this.backgroundColor=N(e.backgroundColor),this.blendFilter=E(e.blendFilter),this.constraint=_(e.constraint),this.columnCount=_(e.columnCount),this.darkenFilter=ce(e.darkenFilter),this.deprecatedFontSize=E(e.deprecatedFontSize),this.fontFamily=N(e.fontFamily),this.fontSize=M(e.fontSize,Ae.range),this.fontSizeNormalize=E(e.fontSizeNormalize),this.fontOpticalSizing=E(e.fontOpticalSizing),this.fontWeight=M(e.fontWeight,Z.range),this.fontWidth=M(e.fontWidth,Oe.range),this.hyphens=E(e.hyphens),this.invertFilter=ce(e.invertFilter),this.invertGaijiFilter=ce(e.invertGaijiFilter),this.iOSPatch=E(e.iOSPatch),this.iPadOSPatch=E(e.iPadOSPatch),this.letterSpacing=_(e.letterSpacing),this.ligatures=E(e.ligatures),this.lineHeight=_(e.lineHeight),this.linkColor=N(e.linkColor),this.noRuby=E(e.noRuby),this.pageGutter=_(e.pageGutter),this.paragraphIndent=_(e.paragraphIndent),this.paragraphSpacing=_(e.paragraphSpacing),this.scroll=E(e.scroll),this.scrollPaddingTop=_(e.scrollPaddingTop),this.scrollPaddingBottom=_(e.scrollPaddingBottom),this.scrollPaddingLeft=_(e.scrollPaddingLeft),this.scrollPaddingRight=_(e.scrollPaddingRight),this.selectionBackgroundColor=N(e.selectionBackgroundColor),this.selectionTextColor=N(e.selectionTextColor),this.textAlign=He(e.textAlign,K),this.textColor=N(e.textColor),this.textNormalization=E(e.textNormalization),this.visitedColor=N(e.visitedColor),this.wordSpacing=_(e.wordSpacing),this.optimalLineLength=_(e.optimalLineLength),this.maximalLineLength=_(e.maximalLineLength),this.minimalLineLength=_(e.minimalLineLength)}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 i of Object.keys(e))e[i]!==void 0&&(i!=="maximalLineLength"||e[i]===null||e[i]>=(e.optimalLineLength??t.optimalLineLength??65))&&(i!=="minimalLineLength"||e[i]===null||e[i]<=(e.optimalLineLength??t.optimalLineLength??65))&&(t[i]=e[i]);return new Pe(t)}}class Fn{constructor(e){this.backgroundColor=N(e.backgroundColor)||null,this.blendFilter=E(e.blendFilter)??!1,this.constraint=_(e.constraint)||0,this.columnCount=_(e.columnCount)||null,this.darkenFilter=ce(e.darkenFilter)??!1,this.deprecatedFontSize=E(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=N(e.fontFamily)||null,this.fontSize=M(e.fontSize,Ae.range)||1,this.fontSizeNormalize=E(e.fontSizeNormalize)??!1,this.fontOpticalSizing=E(e.fontOpticalSizing)??null,this.fontWeight=M(e.fontWeight,Z.range)||null,this.fontWidth=M(e.fontWidth,Oe.range)||null,this.hyphens=E(e.hyphens)??null,this.invertFilter=ce(e.invertFilter)??!1,this.invertGaijiFilter=ce(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:A.OS.iPadOS&&A.iOSRequest==="desktop",this.letterSpacing=_(e.letterSpacing)||null,this.ligatures=E(e.ligatures)??null,this.lineHeight=_(e.lineHeight)||null,this.linkColor=N(e.linkColor)||null,this.noRuby=E(e.noRuby)??!1,this.pageGutter=at(_(e.pageGutter),20),this.paragraphIndent=_(e.paragraphIndent)??null,this.paragraphSpacing=_(e.paragraphSpacing)??null,this.scroll=E(e.scroll)??!1,this.scrollPaddingTop=_(e.scrollPaddingTop)??null,this.scrollPaddingBottom=_(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=_(e.scrollPaddingLeft)??null,this.scrollPaddingRight=_(e.scrollPaddingRight)??null,this.selectionBackgroundColor=N(e.selectionBackgroundColor)||null,this.selectionTextColor=N(e.selectionTextColor)||null,this.textAlign=He(e.textAlign,K)||null,this.textColor=N(e.textColor)||null,this.textNormalization=E(e.textNormalization)??!1,this.visitedColor=N(e.visitedColor)||null,this.wordSpacing=_(e.wordSpacing)||null,this.optimalLineLength=_(e.optimalLineLength)||65,this.maximalLineLength=at(hn(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=at(cn(e.minimalLineLength,this.optimalLineLength),40),this.experiments=Bt(e.experiments)||null}}const Ee={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class Jt{constructor(e,t,i){this.preferences=e,this.settings=t,this.metadata=i,this.layout=this.metadata?.effectiveLayout||v.reflowable}clear(){this.preferences=new Pe({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 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 T({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout!==v.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 C({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:ae.range,step:ae.step})}get deprecatedFontSize(){return new O({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout!==v.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!==v.fixed,onChange:e=>{this.updatePreference("fontFamily",e??null)}})}get fontSize(){return new C({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("fontSize",e??null)},supportedRange:Ae.range,step:Ae.step})}get fontSizeNormalize(){return new O({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout!==v.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!==v.fixed&&this.preferences.fontOpticalSizing!==null,onChange:e=>{this.updatePreference("fontOpticalSizing",e??null)}})}get fontWeight(){return new C({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout!==v.fixed&&this.preferences.fontWeight!==null,onChange:e=>{this.updatePreference("fontWeight",e??null)},supportedRange:Z.range,step:Z.step})}get fontWidth(){return new C({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout!==v.fixed&&this.preferences.fontWidth!==null,onChange:e=>{this.updatePreference("fontWidth",e??null)},supportedRange:Oe.range,step:Oe.step})}get hyphens(){return new O({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout!==v.fixed&&this.metadata?.effectiveReadingProgression===U.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e??null)}})}get invertFilter(){return new C({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:ae.range,step:ae.step})}get invertGaijiFilter(){return new C({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:ae.range,step:ae.step})}get iOSPatch(){return new O({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout!==v.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!==v.fixed,onChange:e=>{this.updatePreference("iPadOSPatch",e??null)}})}get letterSpacing(){return new C({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.letterSpacing!==null,onChange:e=>{this.updatePreference("letterSpacing",e??null)},supportedRange:Te.range,step:Te.step})}get ligatures(){return new O({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:(()=>{if(this.preferences.ligatures===null||this.layout===v.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 C({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout!==v.fixed&&this.preferences.lineHeight!==null,onChange:e=>{this.updatePreference("lineHeight",e??null)},supportedRange:ze.range,step:ze.step})}get linkColor(){return new T({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||Ee.RS__linkColor,isEffective:this.layout!==v.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e??null)}})}get maximalLineLength(){return new C({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:le.range,step:le.step})}get minimalLineLength(){return new C({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("minimalLineLength",e)},supportedRange:le.range,step:le.step})}get noRuby(){return new O({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout!==v.fixed&&this.metadata?.languages?.includes("ja")||!1,onChange:e=>{this.updatePreference("noRuby",e??null)}})}get optimalLineLength(){return new C({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("optimalLineLength",e)},supportedRange:le.range,step:le.step})}get pageGutter(){return new T({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout!==v.fixed&&!this.settings.scroll,onChange:e=>{this.updatePreference("pageGutter",e??null)}})}get paragraphIndent(){return new C({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphIndent!==null,onChange:e=>{this.updatePreference("paragraphIndent",e??null)},supportedRange:Me.range,step:Me.step})}get paragraphSpacing(){return new C({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.paragraphSpacing!==null,onChange:e=>{this.updatePreference("paragraphSpacing",e??null)},supportedRange:Ie.range,step:Ie.step})}get scroll(){return new O({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout!==v.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!==v.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!==v.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!==v.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!==v.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!==v.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!==v.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||K.start,isEffective:this.layout!==v.fixed&&this.preferences.textAlign!==null,onChange:e=>{this.updatePreference("textAlign",e??null)},supportedValues:Object.values(K)})}get textColor(){return new T({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||Ee.RS__textColor,isEffective:this.layout!==v.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!==v.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!==v.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e??null)}})}get wordSpacing(){return new C({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout!==v.fixed&&this.preferences.wordSpacing!==null,onChange:e=>{this.updatePreference("wordSpacing",e??null)},supportedRange:Fe.range,step:Fe.step})}}class Zt{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?(A.OS.iOS||A.OS.iPadOS)&&A.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?A.OS.iPadOS&&A.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 ut(o){const e=getComputedStyle(o),t=parseFloat(e.paddingLeft||"0"),i=parseFloat(e.paddingRight||"0");return o.clientWidth-t-i}class Qt extends We{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 Nn extends We{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]=st[t].value}),e}}class Un{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.cachedColCount=e.userProperties.colCount,this.effectiveContainerWidth=ut(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 i={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 Qt(i)}updateLayout(e,t,i,n){return i??this.userProperties.view==="scroll"?this.computeScrollLength(e,t):this.paginate(e,t,n)}getCompensatedMetrics(e,t){const i=e||this.userProperties.fontSize||1,n=i<1?1/i:t?i:1;return{zoomFactor:i,zoomCompensation:n,optimal:Math.round(this.lineLengths.optimalLineLength)*i,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*i):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*i):null}}paginate(e,t,i){const n=Math.round(ut(this.containerParent)-this.constraint),r=this.getCompensatedMetrics(e,t),{zoomCompensation:s,optimal:a,minimal:l,maximal:c}=r,h=()=>n>=a&&c!==null?Math.min(Math.round(c*s),n):n;let u=1,m=n;if(i===void 0)return{colCount:void 0,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u*s)};if(i===null)if(n>=a&&c!==null){u=Math.floor(n/a);const b=Math.round(u*(c*s));m=Math.min(b,n)}else m=h();else if(i>1){const b=Math.round(i*(l!==null?l:a));if(n>=b)if(u=i,c===null)m=n;else{const d=Math.round(u*(c*s));m=Math.min(d,n)}else if(l!==null&&n<Math.round(i*l))if(u=Math.floor(n/l),u<=1)u=1,m=h();else{const d=Math.round(u*(a*s));m=Math.min(d,n)}else{u=i;const d=Math.round(u*(a*s));m=Math.min(d,n)}}else u=1,m=h();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*s)}}computeScrollLength(e,t){const i=Math.round(ut(this.containerParent)-this.constraint),n=this.getCompensatedMetrics(e&&(e<1||t)?e:1,t),r=n.zoomCompensation,s=n.optimal,a=n.maximal;let l,c=i,h=Math.round(s*r);if(a===null)h=i;else{const u=Math.min(Math.round(a*r),i);h=t?u:Math.round(u*r)}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 mo=`/*!
|
|
404
|
+
* Readium CSS v.2.0.1
|
|
406
405
|
* Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
|
|
407
406
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
408
407
|
* LICENSE file present in the project repository where this source code is maintained.
|
|
@@ -765,8 +764,7 @@ body{
|
|
|
765
764
|
text-indent:var(--USER__paraIndent) !important;
|
|
766
765
|
}
|
|
767
766
|
|
|
768
|
-
:root[style*="--USER__paraIndent"] p
|
|
769
|
-
:root[style*="--USER__paraIndent"] p:first-letter{
|
|
767
|
+
:root[style*="--USER__paraIndent"] p *{
|
|
770
768
|
text-indent:0 !important;
|
|
771
769
|
}
|
|
772
770
|
|
|
@@ -990,8 +988,8 @@ body{
|
|
|
990
988
|
|
|
991
989
|
:root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
|
|
992
990
|
-webkit-text-zoom:normal;
|
|
993
|
-
}`,
|
|
994
|
-
* Readium CSS v.2.0.
|
|
991
|
+
}`,go=`/*!
|
|
992
|
+
* Readium CSS v.2.0.1
|
|
995
993
|
* Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
|
|
996
994
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
997
995
|
* LICENSE file present in the project repository where this source code is maintained.
|
|
@@ -1411,8 +1409,8 @@ audio{
|
|
|
1411
1409
|
table{
|
|
1412
1410
|
max-width:var(--RS__maxMediaWidth);
|
|
1413
1411
|
box-sizing:var(--RS__boxSizingTable);
|
|
1414
|
-
}`,
|
|
1415
|
-
* Readium CSS v.2.0.
|
|
1412
|
+
}`,fo=`/*!
|
|
1413
|
+
* Readium CSS v.2.0.1
|
|
1416
1414
|
* Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
|
|
1417
1415
|
* Use of this source code is governed by a BSD-style license which is detailed in the
|
|
1418
1416
|
* LICENSE file present in the project repository where this source code is maintained.
|
|
@@ -1569,7 +1567,7 @@ th{
|
|
|
1569
1567
|
th, td{
|
|
1570
1568
|
padding:4px;
|
|
1571
1569
|
border:1px solid currentcolor;
|
|
1572
|
-
}`,
|
|
1570
|
+
}`,yo=`// Note: we aren't blocking some of the events right now to try and be as nonintrusive as possible.
|
|
1573
1571
|
// For a more comprehensive implementation, see https://github.com/hackademix/noscript/blob/3a83c0e4a506f175e38b0342dad50cdca3eae836/src/content/syncFetchPolicy.js#L142
|
|
1574
1572
|
// The snippet of code at the beginning of this source is an attempt at defence against JS using persistent storage
|
|
1575
1573
|
(function() {
|
|
@@ -1634,26 +1632,54 @@ th, td{
|
|
|
1634
1632
|
window.addEventListener("DOMContentLoaded", window._readium_eventBlocker, true);
|
|
1635
1633
|
window.addEventListener("load", window._readium_eventBlocker, true);
|
|
1636
1634
|
})();
|
|
1637
|
-
`;function So(o,e){const t=o.effectiveLayout===v.fixed,i=e.filter(a=>a.mediaType.isHTML).map(a=>a.href),n=i.length>0?i:[/\.xhtml$/,/\.html$/],r=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([Pe(yn)],{type:"text/javascript"})},{id:"execution-prevention",as:"script",target:"head",blob:new Blob([Pe(vo)],{type:"text/javascript"}),condition:a=>!!(a.querySelector("script")||a.querySelector("body[onload]:not(body[onload=''])"))}],s=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([Pe(bn)],{type:"text/javascript"}),condition:a=>!!(a.querySelector("script")||a.querySelector("body[onload]:not(body[onload=''])"))}];return t||(r.unshift({id:"readium-css-before",as:"link",target:"head",blob:new Blob([ct(yo)],{type:"text/css"}),rel:"stylesheet"}),s.unshift({id:"readium-css-default",as:"link",target:"head",blob:new Blob([ct(bo)],{type:"text/css"}),rel:"stylesheet",condition:a=>!(a.querySelector("link[rel='stylesheet']")||a.querySelector("style")||a.querySelector("[style]:not([style=''])"))},{id:"readium-css-after",as:"link",target:"head",blob:new Blob([ct(fo)],{type:"text/css"}),rel:"stylesheet"})),[{resources:n,prepend:r,append:s}]}const _o=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),miscPointer:o.miscPointer||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class ti extends Wt{constructor(e,t,i,n=[],r=void 0,s={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=_o(i),this.currentLocation=r,n.length&&(this.positions=n),this._preferences=new Ee(s.preferences),this._defaults=new Un(s.defaults),this._settings=new Qt(this._preferences,this._defaults),this._css=new Wn({rsProperties:new Dn({}),userProperties:new ei({}),lineLengths:new _e({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}),container:e,constraint:this._settings.constraint}),this._layout=ti.determineLayout(t,!!this._settings.scroll),this.currentProgression=t.metadata.effectiveReadingProgression;const a=So(t.metadata,t.readingOrder.items),l=s.injectables||{rules:[],allowedDomains:[]};this._injector=new $t({rules:[...a,...l.rules],allowedDomains:l.allowedDomains}),this._contentProtection=s.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,s.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new qt(this._contentProtection),this._suspiciousActivityListener=c=>{const{type:h,...u}=c.detail;h==="context_menu"?this.listeners.contextMenu(u):this.listeners.contentProtection(h,u)},window.addEventListener(de,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new Kt({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=c=>{const h=c.detail;this.listeners.peripheral(h)},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 i=e.metadata.effectiveLayout;return i===v.fixed||e.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in e.metadata.otherMetadata||e.metadata?.conformsTo?.includes(yi.DIVINA)?v.fixed:i===v.scrolled||i===v.reflowable&&t?v.scrolled:v.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),this._layout===v.fixed)this.framePool=new Fn(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 Cn(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===v.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 Zt(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 Qt(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new Zt(this._preferences,this.settings,this.pub.metadata)),this._layout===v.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[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t),this._css.userProperties.view==="paged"&&this._layout===v.scrolled?await this.setLayout(v.reflowable):this._css.userProperties.view==="scroll"&&this._layout===v.reflowable&&await this.setLayout(v.scrolled),this._css.setContainerWidth()}async resizeHandler(){const e=this.container.parentElement||document.documentElement;if(this._layout===v.fixed)this.container.style.width=`${pt(e)-this._settings.constraint}px`,this.framePool.resizeHandler();else{const t=this._css.userProperties.colCount,i=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&t!==this._css.userProperties.colCount||i!==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}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 i=N.deserialize(t);if(!i)break;this.currentLocation=new N({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new j({href:a}).locator);else try{this.goLink(new j({href:st.join(st.dirname(this.currentLocation.href),a)}),!1,()=>{})}catch(l){console.warn(`Couldn't go to link for ${a}: ${l}`),this.listeners.handleLocator(new j({href:a}).locator)}}else console.log("Clicked on",s)}else{if(this._layout===v.fixed&&this.framePool.doNotDisturb&&(n.doNotDisturb=!0),this._layout===v.fixed&&(this.currentProgression===U.rtl||this.currentProgression===U.ltr)&&this.framePool.currentFrames.length>1){const l=this.framePool.currentFrames;n.targetFrameSrc===l[this.currentProgression===U.rtl?0:1]?.source&&(n.x+=(l[this.currentProgression===U.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(e==="click"?this.listeners.click(n):this.listeners.tap(n))break;const a=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;n.x>=a&&n.x<=a*3&&this.listeners.miscPointer(1),n.x<a?this.goLeft(!1,()=>{}):n.x>a*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 r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);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(ot.keys());return this._layout===v.fixed?e.filter(t=>zr.includes(t)):(e=e.filter(t=>Mr.includes(t)),this._layout===v.scrolled?e=e.filter(t=>t!=="column_snapper"):e=e.filter(t=>t!=="scroll_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=(i,n)=>{this.eventListener(i,n)})})}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===v.fixed){const n=this.framePool,r=n.viewport.positions[0];if(e===1){if(!n.next(n.perPage))return!1}else if(e===-1){if(!n.prev(n.perPage))return!1}else throw Error("Invalid relative value for FXL");const s=n.viewport.positions[0];if(r>s){for(let a=this.positions.length-1;a>=0;a--)if(this.positions[a].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[a].copyWithLocations({progression:.999999999999});break}}else if(r<s){for(let a=0;a<this.positions.length;a++)if(this.positions[a].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[a];break}}return await this.apply(),!0}const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));if(i===t)return this._cframes[0]?.msg?.send("shake",void 0,async n=>{}),!1;if(t>i){for(let n=this.positions.length-1;n>=0;n--)if(this.positions[n].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[n].copyWithLocations({progression:.999999999999});break}}else for(let n=0;n<this.positions.length;n++)if(this.positions[n].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[n];break}return await this.apply(),!0}findLastPositionInProgressionRange(e,t){const i=e.findLastIndex(n=>{const r=n.locations.progression;return!!(r&&r>t.start&&r<=t.end)});return i!==-1?e[i]:void 0}findNearestPositions(e){const t=this.positions.filter(r=>r.href===this.currentLocation.href);let i=this.currentLocation,n;return t.some((r,s)=>{const a=r.locations.progression??0;if(e.start<=a){i=r;const l=t.splice(s+1,t.length);return n=this.findLastPositionInProgressionRange(l,e),!0}else return!1}),{first:i,last:n}}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,i=this.findNearestPositions(t);this.currentLocation=i.first.copyWithLocations({progression:t.start}),this.lastLocationInView=i.last,this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this._layout===v.fixed?(this.changeResource(-1),t(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async i=>{t(i?!0:await this.changeResource(-1))})}goForward(e,t){this._layout===v.fixed?(this.changeResource(1),t(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async i=>{t(i?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===v.fixed?this.framePool.viewport: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 i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];let r=this.pub.readingOrder.findWithHref(n);if(!r)return i(this.listeners.handleLocator(e));this.currentLocation=this.positions.find(s=>s.href===r.href),this.apply().then(()=>this.loadLocator(e,s=>i(s))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}}const wo=`// PreservePitchProcessor.js
|
|
1638
|
-
// AudioWorklet processor for pitch preservation via pitch shifting
|
|
1635
|
+
`;function bo(o,e){const t=o.effectiveLayout===v.fixed,i=e.filter(a=>a.mediaType.isHTML).map(a=>a.href),n=i.length>0?i:[/\.xhtml$/,/\.html$/],r=[{id:"css-selector-generator",as:"script",target:"head",blob:new Blob([we(gn)],{type:"text/javascript"})},{id:"execution-prevention",as:"script",target:"head",blob:new Blob([we(yo)],{type:"text/javascript"}),condition:a=>!!(a.querySelector("script")||a.querySelector("body[onload]:not(body[onload=''])"))}],s=[{id:"onload-proxy",as:"script",target:"head",blob:new Blob([we(fn)],{type:"text/javascript"}),condition:a=>!!(a.querySelector("script")||a.querySelector("body[onload]:not(body[onload=''])"))}];return t||(r.unshift({id:"readium-css-before",as:"link",target:"head",blob:new Blob([lt(go)],{type:"text/css"}),rel:"stylesheet"}),s.unshift({id:"readium-css-default",as:"link",target:"head",blob:new Blob([lt(fo)],{type:"text/css"}),rel:"stylesheet",condition:a=>!(a.querySelector("link[rel='stylesheet']")||a.querySelector("style")||a.querySelector("[style]:not([style=''])"))},{id:"readium-css-after",as:"link",target:"head",blob:new Blob([lt(mo)],{type:"text/css"}),rel:"stylesheet"})),[{resources:n,prepend:r,append:s}]}const vo=o=>({frameLoaded:o.frameLoaded||(()=>{}),positionChanged:o.positionChanged||(()=>{}),tap:o.tap||(()=>!1),click:o.click||(()=>!1),zoom:o.zoom||(()=>{}),miscPointer:o.miscPointer||(()=>{}),scroll:o.scroll||(()=>{}),customEvent:o.customEvent||(()=>{}),handleLocator:o.handleLocator||(()=>!1),textSelected:o.textSelected||(()=>{}),contentProtection:o.contentProtection||(()=>{}),contextMenu:o.contextMenu||(()=>{}),peripheral:o.peripheral||(()=>{})});class ei extends Dt{constructor(e,t,i,n=[],r=void 0,s={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=vo(i),this.currentLocation=r,n.length&&(this.positions=n),this._preferences=new Pe(s.preferences),this._defaults=new Fn(s.defaults),this._settings=new Zt(this._preferences,this._defaults),this._css=new Un({rsProperties:new Nn({}),userProperties:new Qt({}),lineLengths:new Se({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}),container:e,constraint:this._settings.constraint}),this._layout=ei.determineLayout(t,!!this._settings.scroll),this.currentProgression=t.metadata.effectiveReadingProgression;const a=bo(t.metadata,t.readingOrder.items),l=s.injectables||{rules:[],allowedDomains:[]};this._injector=new $t({rules:[...a,...l.rules],allowedDomains:l.allowedDomains}),this._contentProtection=s.contentProtection||{},this._keyboardPeripherals=this.mergeKeyboardPeripherals(this._contentProtection,s.keyboardPeripherals||[]),(this._contentProtection.disableContextMenu||this._contentProtection.checkAutomation||this._contentProtection.checkIFrameEmbedding||this._contentProtection.monitorDevTools||this._contentProtection.protectPrinting?.disable)&&(this._navigatorProtector=new qt(this._contentProtection),this._suspiciousActivityListener=c=>{const{type:h,...u}=c.detail;h==="context_menu"?this.listeners.contextMenu(u):this.listeners.contentProtection(h,u)},window.addEventListener(he,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new Yt({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=c=>{const h=c.detail;this.listeners.peripheral(h)},window.addEventListener(de,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 i=e.metadata.effectiveLayout;return i===v.fixed||e.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in e.metadata.otherMetadata||e.metadata?.conformsTo?.includes(fi.DIVINA)?v.fixed:i===v.scrolled||i===v.reflowable&&t?v.scrolled:v.reflowable}async load(){if(this.positions?.length||(this.positions=await this.pub.positionsFromManifest()),this._layout===v.fixed)this.framePool=new In(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 En(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===v.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 Jt(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 Zt(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new Jt(this._preferences,this.settings,this.pub.metadata)),this._layout===v.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[i,n]of Object.entries(e.rsProperties.toCSSProperties()))t[i]=n;for(const[i,n]of Object.entries(e.userProperties.toCSSProperties()))t[i]=n;return t}async commitCSS(e){const t=this.compileCSSProperties(e);this.framePool.setCSSProperties(t),this._css.userProperties.view==="paged"&&this._layout===v.scrolled?await this.setLayout(v.reflowable):this._css.userProperties.view==="scroll"&&this._layout===v.reflowable&&await this.setLayout(v.scrolled),this._css.setContainerWidth()}async resizeHandler(){const e=this.container.parentElement||document.documentElement;if(this._layout===v.fixed)this.container.style.width=`${ut(e)-this._settings.constraint}px`,this.framePool.resizeHandler();else{const t=this._css.userProperties.colCount,i=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&t!==this._css.userProperties.colCount||i!==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}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 i=F.deserialize(t);if(!i)break;this.currentLocation=new F({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:i?.locations,text:i?.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const n=t;if(n.interactiveElement){const s=new DOMParser().parseFromString(n.interactiveElement,"text/html").body.children[0];if(s.nodeType===s.ELEMENT_NODE&&s.nodeName==="A"&&s.hasAttribute("href")){const a=s.attributes.getNamedItem("href")?.value;if(a.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[a.substring(1)]}),!1,()=>{});else if(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("mailto:")||a.startsWith("tel:"))this.listeners.handleLocator(new j({href:a}).locator);else try{this.goLink(new j({href:ot.join(ot.dirname(this.currentLocation.href),a)}),!1,()=>{})}catch(l){console.warn(`Couldn't go to link for ${a}: ${l}`),this.listeners.handleLocator(new j({href:a}).locator)}}else console.log("Clicked on",s)}else{if(this._layout===v.fixed&&this.framePool.doNotDisturb&&(n.doNotDisturb=!0),this._layout===v.fixed&&(this.currentProgression===U.rtl||this.currentProgression===U.ltr)&&this.framePool.currentFrames.length>1){const l=this.framePool.currentFrames;n.targetFrameSrc===l[this.currentProgression===U.rtl?0:1]?.source&&(n.x+=(l[this.currentProgression===U.rtl?1:0]?.iframe.contentWindow?.innerWidth??0)*window.devicePixelRatio)}if(e==="click"?this.listeners.click(n):this.listeners.tap(n))break;const a=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;n.x>=a&&n.x<=a*3&&this.listeners.miscPointer(1),n.x<a?this.goLeft(!1,()=>{}):n.x>a*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 r=t;this.listeners.contentProtection(r.type,r);break;case"context_menu":this.listeners.contextMenu(t);break;case"keyboard_peripherals":this.listeners.peripheral(t);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(rt.keys());return this._layout===v.fixed?e.filter(t=>Or.includes(t)):(e=e.filter(t=>Tr.includes(t)),this._layout===v.scrolled?e=e.filter(t=>t!=="column_snapper"):e=e.filter(t=>t!=="scroll_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=(i,n)=>{this.eventListener(i,n)})})}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(he,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(de,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),await this.framePool?.destroy()}async changeResource(e){if(e===0)return!1;if(this._layout===v.fixed){const n=this.framePool,r=n.viewport.positions[0];if(e===1){if(!n.next(n.perPage))return!1}else if(e===-1){if(!n.prev(n.perPage))return!1}else throw Error("Invalid relative value for FXL");const s=n.viewport.positions[0];if(r>s){for(let a=this.positions.length-1;a>=0;a--)if(this.positions[a].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[a].copyWithLocations({progression:.999999999999});break}}else if(r<s){for(let a=0;a<this.positions.length;a++)if(this.positions[a].href===this.pub.readingOrder.items[s-1].href){this.currentLocation=this.positions[a];break}}return await this.apply(),!0}const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),i=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+e));if(i===t)return this._cframes[0]?.msg?.send("shake",void 0,async n=>{}),!1;if(t>i){for(let n=this.positions.length-1;n>=0;n--)if(this.positions[n].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[n].copyWithLocations({progression:.999999999999});break}}else for(let n=0;n<this.positions.length;n++)if(this.positions[n].href===this.pub.readingOrder.items[i].href){this.currentLocation=this.positions[n];break}return await this.apply(),!0}findLastPositionInProgressionRange(e,t){const i=e.findLastIndex(n=>{const r=n.locations.progression;return!!(r&&r>t.start&&r<=t.end)});return i!==-1?e[i]:void 0}findNearestPositions(e){const t=this.positions.filter(r=>r.href===this.currentLocation.href);let i=this.currentLocation,n;return t.some((r,s)=>{const a=r.locations.progression??0;if(e.start<=a){i=r;const l=t.splice(s+1,t.length);return n=this.findLastPositionInProgressionRange(l,e),!0}else return!1}),{first:i,last:n}}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,i=this.findNearestPositions(t);this.currentLocation=i.first.copyWithLocations({progression:t.start}),this.lastLocationInView=i.last,this.updateViewport(t),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(e,t){this._layout===v.fixed?(this.changeResource(-1),t(!0)):this._cframes[0]?.msg?.send("go_prev",void 0,async i=>{t(i?!0:await this.changeResource(-1))})}goForward(e,t){this._layout===v.fixed?(this.changeResource(1),t(!0)):this._cframes[0]?.msg?.send("go_next",void 0,async i=>{t(i?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this._layout===v.fixed?this.framePool.viewport: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 i=!1,n=typeof e.locations.getCssSelector=="function"&&e.locations.getCssSelector();if(e.text?.highlight?i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),h=>l(h))}):n&&(i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_text",["",n],h=>l(h))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_id",r,h=>l(h))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,c)=>{this._cframes[0].msg.send("go_progression",s,h=>l(h))}):i=!0,t(i)}go(e,t,i){const n=e.href.split("#")[0];let r=this.pub.readingOrder.findWithHref(n);if(!r)return i(this.listeners.handleLocator(e));this.currentLocation=this.positions.find(s=>s.href===r.href),this.apply().then(()=>this.loadLocator(e,s=>i(s))).then(()=>{this.attachListener()})}goLink(e,t,i){return this.go(e.locator,t,i)}}const So=`// PreservePitchProcessor.js
|
|
1636
|
+
// AudioWorklet processor for pitch preservation via pitch shifting.
|
|
1637
|
+
//
|
|
1638
|
+
// Architecture:
|
|
1639
|
+
// - Overlap-add (OLA) phase vocoder with an iterative in-place Cooley-Tukey FFT/IFFT.
|
|
1640
|
+
// - All intermediate buffers are pre-allocated in the constructor; the hot path
|
|
1641
|
+
// (process → _processBuffer → _fft) is allocation-free and GC-safe.
|
|
1642
|
+
// - An output ring buffer decouples OLA processing (fires every hopSize input
|
|
1643
|
+
// samples) from the Web Audio render quantum (128 frames), so process() always
|
|
1644
|
+
// fills outputChannel completely.
|
|
1639
1645
|
|
|
1640
1646
|
class PreservePitchProcessor extends AudioWorkletProcessor {
|
|
1641
1647
|
constructor() {
|
|
1642
1648
|
super();
|
|
1643
|
-
this.bufferSize
|
|
1644
|
-
this.hopSize
|
|
1645
|
-
this.overlap
|
|
1646
|
-
this.inputBuffer = new Float32Array(this.bufferSize);
|
|
1647
|
-
this.outputBuffer = new Float32Array(this.bufferSize);
|
|
1648
|
-
this.window = new Float32Array(this.bufferSize);
|
|
1649
|
-
this.bufferIndex = 0;
|
|
1649
|
+
this.bufferSize = 1024;
|
|
1650
|
+
this.hopSize = 256;
|
|
1651
|
+
this.overlap = this.bufferSize - this.hopSize;
|
|
1650
1652
|
this.pitchFactor = 1.0;
|
|
1651
1653
|
|
|
1652
|
-
//
|
|
1654
|
+
// Sliding input window (always holds the last bufferSize samples)
|
|
1655
|
+
this.inputBuffer = new Float32Array(this.bufferSize);
|
|
1656
|
+
this.inputFill = 0; // samples loaded during startup (saturates at bufferSize)
|
|
1657
|
+
this.hopAccum = 0; // new samples since last OLA step; triggers a step at hopSize
|
|
1658
|
+
|
|
1659
|
+
// OLA output accumulator: overlap-add results accumulate here; hopSize samples
|
|
1660
|
+
// are drained to the ring buffer and the remainder shifts down each OLA step.
|
|
1661
|
+
this.olaBuffer = new Float32Array(this.bufferSize);
|
|
1662
|
+
|
|
1663
|
+
// Output FIFO ring buffer — power-of-2 size for allocation-free modulo wrapping.
|
|
1664
|
+
this._ringSize = 4096;
|
|
1665
|
+
this._ring = new Float32Array(this._ringSize);
|
|
1666
|
+
this._ringMask = this._ringSize - 1;
|
|
1667
|
+
this._ringWrite = 0;
|
|
1668
|
+
this._ringRead = 0;
|
|
1669
|
+
this._ringAvail = 0;
|
|
1670
|
+
|
|
1671
|
+
// Hann window (pre-computed, never mutated)
|
|
1672
|
+
this.window = new Float32Array(this.bufferSize);
|
|
1653
1673
|
for (let i = 0; i < this.bufferSize; i++) {
|
|
1654
1674
|
this.window[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / this.bufferSize));
|
|
1655
1675
|
}
|
|
1656
1676
|
|
|
1677
|
+
// Pre-allocated FFT work buffers — never re-created in the hot path
|
|
1678
|
+
this._re = new Float64Array(this.bufferSize);
|
|
1679
|
+
this._im = new Float64Array(this.bufferSize);
|
|
1680
|
+
this._shiftedRe = new Float64Array(this.bufferSize);
|
|
1681
|
+
this._shiftedIm = new Float64Array(this.bufferSize);
|
|
1682
|
+
|
|
1657
1683
|
this.port.onmessage = (event) => {
|
|
1658
1684
|
if (event.data.type === 'setPitchFactor') {
|
|
1659
1685
|
this.pitchFactor = event.data.factor;
|
|
@@ -1662,125 +1688,162 @@ class PreservePitchProcessor extends AudioWorkletProcessor {
|
|
|
1662
1688
|
}
|
|
1663
1689
|
|
|
1664
1690
|
process(inputs, outputs) {
|
|
1665
|
-
const input
|
|
1691
|
+
const input = inputs[0];
|
|
1666
1692
|
const output = outputs[0];
|
|
1667
|
-
|
|
1668
1693
|
if (!input || !output) return true;
|
|
1694
|
+
const inCh = input[0];
|
|
1695
|
+
const outCh = output[0];
|
|
1696
|
+
if (!inCh || !outCh) return true;
|
|
1697
|
+
|
|
1698
|
+
const newCount = inCh.length; // always 128 under normal Web Audio conditions
|
|
1699
|
+
|
|
1700
|
+
// --- 1. Push new samples into the sliding input window ---
|
|
1701
|
+
if (this.inputFill < this.bufferSize) {
|
|
1702
|
+
// Startup: fill the window until we have a full bufferSize frame.
|
|
1703
|
+
// Since bufferSize (1024) is an exact multiple of the render quantum (128)
|
|
1704
|
+
// this branch always copies exactly newCount samples.
|
|
1705
|
+
this.inputBuffer.set(inCh, this.inputFill);
|
|
1706
|
+
this.inputFill += newCount;
|
|
1707
|
+
} else {
|
|
1708
|
+
// Steady state: slide left by newCount, append the new quantum at the end.
|
|
1709
|
+
this.inputBuffer.copyWithin(0, newCount);
|
|
1710
|
+
this.inputBuffer.set(inCh, this.bufferSize - newCount);
|
|
1711
|
+
}
|
|
1712
|
+
this.hopAccum += newCount;
|
|
1669
1713
|
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
this.bufferIndex++;
|
|
1714
|
+
// --- 2. Run OLA step(s) whenever hopAccum reaches hopSize ---
|
|
1715
|
+
// During startup we skip processing until a full window is available.
|
|
1716
|
+
while (this.inputFill >= this.bufferSize && this.hopAccum >= this.hopSize) {
|
|
1717
|
+
this.hopAccum -= this.hopSize;
|
|
1718
|
+
this._processBuffer(); // drains hopSize samples into _ring
|
|
1719
|
+
}
|
|
1677
1720
|
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
// Shift buffer
|
|
1686
|
-
for (let j = 0; j < this.overlap; j++) {
|
|
1687
|
-
this.inputBuffer[j] = this.inputBuffer[j + this.hopSize];
|
|
1688
|
-
}
|
|
1689
|
-
this.bufferIndex = this.overlap;
|
|
1690
|
-
// Clear output buffer for next
|
|
1691
|
-
this.outputBuffer.fill(0);
|
|
1721
|
+
// --- 3. Drain output ring into outputChannel ---
|
|
1722
|
+
// Output silence during the initial buffering latency (bufferSize samples ≈ 23 ms
|
|
1723
|
+
// at 44100 Hz). Once the ring has data it stays ahead of demand.
|
|
1724
|
+
if (this._ringAvail >= newCount) {
|
|
1725
|
+
for (let i = 0; i < newCount; i++) {
|
|
1726
|
+
outCh[i] = this._ring[this._ringRead];
|
|
1727
|
+
this._ringRead = (this._ringRead + 1) & this._ringMask;
|
|
1692
1728
|
}
|
|
1729
|
+
this._ringAvail -= newCount;
|
|
1730
|
+
} else {
|
|
1731
|
+
outCh.fill(0);
|
|
1693
1732
|
}
|
|
1694
1733
|
|
|
1695
1734
|
return true;
|
|
1696
1735
|
}
|
|
1697
1736
|
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1737
|
+
_processBuffer() {
|
|
1738
|
+
const N = this.bufferSize;
|
|
1739
|
+
const re = this._re;
|
|
1740
|
+
const im = this._im;
|
|
1741
|
+
const shiftedRe = this._shiftedRe;
|
|
1742
|
+
const shiftedIm = this._shiftedIm;
|
|
1743
|
+
const win = this.window;
|
|
1744
|
+
|
|
1745
|
+
// Load windowed input into real part; zero imaginary part
|
|
1746
|
+
for (let i = 0; i < N; i++) {
|
|
1747
|
+
re[i] = this.inputBuffer[i] * win[i];
|
|
1748
|
+
im[i] = 0;
|
|
1703
1749
|
}
|
|
1704
1750
|
|
|
1705
|
-
|
|
1706
|
-
|
|
1751
|
+
this._fft(re, im, false);
|
|
1752
|
+
|
|
1753
|
+
// Spectral pitch shift: map bin k → round(k * factor)
|
|
1754
|
+
shiftedRe.fill(0);
|
|
1755
|
+
shiftedIm.fill(0);
|
|
1756
|
+
const half = N >> 1;
|
|
1757
|
+
const factor = this.pitchFactor;
|
|
1758
|
+
for (let k = 0; k <= half; k++) {
|
|
1759
|
+
const newK = Math.round(k * factor);
|
|
1760
|
+
if (newK <= half) {
|
|
1761
|
+
shiftedRe[newK] += re[k];
|
|
1762
|
+
shiftedIm[newK] += im[k];
|
|
1763
|
+
// Restore conjugate symmetry so the IFFT yields a real-valued signal
|
|
1764
|
+
if (newK > 0 && newK < half) {
|
|
1765
|
+
shiftedRe[N - newK] = shiftedRe[newK];
|
|
1766
|
+
shiftedIm[N - newK] = -shiftedIm[newK];
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1707
1770
|
|
|
1708
|
-
//
|
|
1709
|
-
let shifted = this.pitchShift(fftResult, this.pitchFactor);
|
|
1771
|
+
this._fft(shiftedRe, shiftedIm, true); // in-place IFFT
|
|
1710
1772
|
|
|
1711
|
-
//
|
|
1712
|
-
let
|
|
1773
|
+
// Overlap-add into olaBuffer
|
|
1774
|
+
for (let i = 0; i < N; i++) {
|
|
1775
|
+
this.olaBuffer[i] += shiftedRe[i] * win[i];
|
|
1776
|
+
}
|
|
1713
1777
|
|
|
1714
|
-
//
|
|
1715
|
-
for (let i = 0; i < this.
|
|
1716
|
-
this.
|
|
1778
|
+
// Push hopSize output samples to the ring buffer
|
|
1779
|
+
for (let i = 0; i < this.hopSize; i++) {
|
|
1780
|
+
this._ring[this._ringWrite] = this.olaBuffer[i];
|
|
1781
|
+
this._ringWrite = (this._ringWrite + 1) & this._ringMask;
|
|
1717
1782
|
}
|
|
1783
|
+
this._ringAvail += this.hopSize;
|
|
1784
|
+
|
|
1785
|
+
// Shift the OLA accumulator left by hopSize; clear the vacated tail
|
|
1786
|
+
this.olaBuffer.copyWithin(0, this.hopSize);
|
|
1787
|
+
this.olaBuffer.fill(0, this.bufferSize - this.hopSize);
|
|
1718
1788
|
}
|
|
1719
1789
|
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1790
|
+
/**
|
|
1791
|
+
* In-place iterative Cooley-Tukey FFT / IFFT.
|
|
1792
|
+
* Operates entirely on the caller-supplied Float64Arrays — no allocation.
|
|
1793
|
+
*
|
|
1794
|
+
* @param {Float64Array} re Real parts (mutated in place)
|
|
1795
|
+
* @param {Float64Array} im Imaginary parts (mutated in place)
|
|
1796
|
+
* @param {boolean} inverse true → IFFT (divides by N), false → FFT
|
|
1797
|
+
*/
|
|
1798
|
+
_fft(re, im, inverse) {
|
|
1799
|
+
const N = re.length;
|
|
1800
|
+
|
|
1801
|
+
// Bit-reversal permutation
|
|
1802
|
+
let j = 0;
|
|
1803
|
+
for (let i = 1; i < N; i++) {
|
|
1804
|
+
let bit = N >> 1;
|
|
1805
|
+
for (; j & bit; bit >>= 1) j ^= bit;
|
|
1806
|
+
j ^= bit;
|
|
1807
|
+
if (i < j) {
|
|
1808
|
+
let tmp;
|
|
1809
|
+
tmp = re[i]; re[i] = re[j]; re[j] = tmp;
|
|
1810
|
+
tmp = im[i]; im[i] = im[j]; im[j] = tmp;
|
|
1728
1811
|
}
|
|
1729
1812
|
}
|
|
1730
|
-
return result;
|
|
1731
|
-
}
|
|
1732
1813
|
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
imag: even[k].imag - twiddled.imag
|
|
1757
|
-
};
|
|
1814
|
+
// Butterfly stages — O(N log N), no allocation
|
|
1815
|
+
const sign = inverse ? 1 : -1;
|
|
1816
|
+
for (let len = 2; len <= N; len <<= 1) {
|
|
1817
|
+
const halfLen = len >> 1;
|
|
1818
|
+
const ang = sign * Math.PI / halfLen;
|
|
1819
|
+
const wBaseRe = Math.cos(ang);
|
|
1820
|
+
const wBaseIm = Math.sin(ang);
|
|
1821
|
+
for (let i = 0; i < N; i += len) {
|
|
1822
|
+
let wRe = 1, wIm = 0;
|
|
1823
|
+
for (let k = 0; k < halfLen; k++) {
|
|
1824
|
+
const uRe = re[i + k];
|
|
1825
|
+
const uIm = im[i + k];
|
|
1826
|
+
const vRe = re[i + k + halfLen] * wRe - im[i + k + halfLen] * wIm;
|
|
1827
|
+
const vIm = re[i + k + halfLen] * wIm + im[i + k + halfLen] * wRe;
|
|
1828
|
+
re[i + k] = uRe + vRe;
|
|
1829
|
+
im[i + k] = uIm + vIm;
|
|
1830
|
+
re[i + k + halfLen] = uRe - vRe;
|
|
1831
|
+
im[i + k + halfLen] = uIm - vIm;
|
|
1832
|
+
const newWRe = wRe * wBaseRe - wIm * wBaseIm;
|
|
1833
|
+
wIm = wRe * wBaseIm + wIm * wBaseRe;
|
|
1834
|
+
wRe = newWRe;
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1758
1837
|
}
|
|
1759
|
-
return result;
|
|
1760
|
-
}
|
|
1761
1838
|
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
// FFT
|
|
1767
|
-
let fftConj = this.fft(conj.map(c => c.real)); // wait, fft expects real array
|
|
1768
|
-
// FFT on complex is needed, but simplify
|
|
1769
|
-
// For simplicity, implement IFFT similarly
|
|
1770
|
-
let result = new Float32Array(N);
|
|
1771
|
-
for (let n = 0; n < N; n++) {
|
|
1772
|
-
let sumReal = 0, sumImag = 0;
|
|
1773
|
-
for (let k = 0; k < N; k++) {
|
|
1774
|
-
let angle = 2 * Math.PI * k * n / N;
|
|
1775
|
-
let c = input[k];
|
|
1776
|
-
sumReal += c.real * Math.cos(angle) - c.imag * Math.sin(angle);
|
|
1777
|
-
sumImag += c.real * Math.sin(angle) + c.imag * Math.cos(angle);
|
|
1839
|
+
if (inverse) {
|
|
1840
|
+
for (let i = 0; i < N; i++) {
|
|
1841
|
+
re[i] /= N;
|
|
1842
|
+
im[i] /= N;
|
|
1778
1843
|
}
|
|
1779
|
-
result[n] = sumReal / N;
|
|
1780
1844
|
}
|
|
1781
|
-
return result;
|
|
1782
1845
|
}
|
|
1783
1846
|
}
|
|
1784
1847
|
|
|
1785
1848
|
registerProcessor('preserve-pitch-processor', PreservePitchProcessor);
|
|
1786
|
-
`;class ii{constructor(e){this.mediaElement=null,this.source=null,this.workletNode=null,this.url=null,this.ctx=e}static async createWorklet(e){const{ctx:t,mediaElement:i,pitchFactor:n,modulePath:r}=e,s=new ii(t);try{if(r)await t.audioWorklet.addModule(r);else{const a=new Blob([wo],{type:"text/javascript"});s.url=URL.createObjectURL(a),await t.audioWorklet.addModule(s.url)}}catch(a){throw s.destroy(),new Error(`Error adding module: ${a}`)}try{if(s.workletNode=new AudioWorkletNode(t,"preserve-pitch-processor"),n&&s.updatePitchFactor(n),i){const a=t.createMediaElementSource(i);a.connect(s.workletNode),s.mediaElement=i,s.source=a}}catch(a){throw s.destroy(),new Error(`Error creating worklet node: ${a}`)}return s}updatePitchFactor(e){this.workletNode&&this.workletNode.port.postMessage({type:"setPitchFactor",factor:e})}destroy(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.source&&(this.source.disconnect(),this.source=null),this.url&&(URL.revokeObjectURL(this.url),this.url=null)}}class Hn{constructor(e){this.audioContext=null,this.sourceNode=null,this.gainNode=null,this.listeners={},this.currentVolume=1,this.currentPlaybackRate=1,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(i=>i!==t))}deactivateWebAudio(){this.worklet&&(this.worklet.destroy(),this.worklet=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.webAudioActive=!1}setMediaElement(e){if(this.mediaElement.removeEventListener("canplaythrough",this.boundOnCanPlayThrough),this.mediaElement.removeEventListener("timeupdate",this.boundOnTimeUpdate),this.mediaElement.removeEventListener("error",this.boundOnError),this.mediaElement.removeEventListener("ended",this.boundOnEnded),this.mediaElement.removeEventListener("stalled",this.boundOnStalled),this.mediaElement.removeEventListener("emptied",this.boundOnEmptied),this.mediaElement.removeEventListener("suspend",this.boundOnSuspend),this.mediaElement.removeEventListener("waiting",this.boundOnWaiting),this.mediaElement.removeEventListener("loadedmetadata",this.boundOnLoadedMetadata),this.mediaElement.removeEventListener("seeking",this.boundOnSeeking),this.mediaElement.removeEventListener("seeked",this.boundOnSeeked),this.mediaElement.removeEventListener("play",this.boundOnPlay),this.mediaElement.removeEventListener("playing",this.boundOnPlaying),this.mediaElement.removeEventListener("pause",this.boundOnPause),this.mediaElement.removeEventListener("progress",this.boundOnProgress),this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!1,this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaElement=e,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.volume=this.isMutedValue?0:this.currentVolume,this.mediaElement.playbackRate=this.currentPlaybackRate,this.webAudioActive)try{const t=this.getOrCreateAudioContext();this.sourceNode=new MediaElementAudioSourceNode(t,{mediaElement:this.mediaElement}),this.gainNode||(this.gainNode=t.createGain(),this.gainNode.connect(t.destination)),this.worklet?.workletNode?this.sourceNode.connect(this.worklet.workletNode):this.sourceNode.connect(this.gainNode)}catch{this.deactivateWebAudio()}this.mediaElement.readyState>=1&&this.onLoadedMetadata(new Event("loadedmetadata")),this.mediaElement.seekable.length>0&&this.onProgress(),this.mediaElement.readyState>=4?this.onCanPlayThrough():(this.isLoadingValue=!0,this.isLoadedValue=!1)}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(i=>i(t))}async play(){if(!this.isPlayingValue)try{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){if(e<0){this.currentVolume=0,this.mediaElement.volume=0,this.gainNode&&(this.gainNode.gain.value=0),this.isMutedValue=!0;return}if(e>1){this.setVolume(e/100);return}this.currentVolume=e,this.mediaElement.volume=e,this.gainNode&&(this.gainNode.gain.value=e)}skip(e){const t=this.mediaElement.duration;if(!isFinite(t))return;const i=this.mediaElement.currentTime+e;i<0?this.mediaElement.currentTime=0:i>t?this.mediaElement.currentTime=t:this.mediaElement.currentTime=i}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.currentPlaybackRate=e,this.mediaElement.playbackRate=e,t?"preservesPitch"in this.mediaElement?this.mediaElement.preservesPitch=!0:this.activateWebAudio().then(()=>{this.worklet?this.worklet.updatePitchFactor(1/e):(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),ii.createWorklet({ctx:this.getOrCreateAudioContext(),mediaElement:this.mediaElement,pitchFactor:1}).then(i=>{this.worklet=i,this.worklet.workletNode.connect(this.gainNode),this.worklet.updatePitchFactor(1/e)}).catch(i=>{console.warn("Failed to create preserve pitch worklet",i)}))}).catch(i=>{console.warn("Web Audio unavailable, playing without pitch correction:",i)}):this.worklet&&(this.worklet.destroy(),this.worklet=null,this.webAudioActive&&(this.sourceNode=new MediaElementAudioSourceNode(this.getOrCreateAudioContext(),{mediaElement:this.mediaElement}),this.sourceNode.connect(this.gainNode)))}async activateWebAudio(){if(this.webAudioActive)return;const e=this.mediaElement.src;if(!e)return;const t=this.mediaElement.currentTime,i=this.isPlayingValue;i&&(this.mediaElement.pause(),this.isPlayingValue=!1),this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load(),await new Promise((r,s)=>{const a=()=>{this.mediaElement.removeEventListener("canplaythrough",a),this.mediaElement.removeEventListener("error",l),r()},l=()=>{this.mediaElement.removeEventListener("canplaythrough",a),this.mediaElement.removeEventListener("error",l),s(new Error("Audio reload with CORS failed — server may not send Access-Control-Allow-Origin"))};this.mediaElement.addEventListener("canplaythrough",a),this.mediaElement.addEventListener("error",l)}),this.mediaElement.currentTime=t,this.sourceNode=new MediaElementAudioSourceNode(this.getOrCreateAudioContext(),{mediaElement:this.mediaElement});const n=this.getOrCreateAudioContext();this.gainNode=n.createGain(),this.sourceNode.connect(this.gainNode),this.gainNode.connect(n.destination),this.webAudioActive=!0,i&&(await this.ensureAudioContextRunning(),await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1)}get isWebAudioActive(){return this.webAudioActive}getMediaElement(){return this.mediaElement}}class Ve{constructor(e={}){this.volume=M(e.volume,De.range),this.playbackRate=M(e.playbackRate,We.range),this.preservePitch=E(e.preservePitch),this.skipBackwardInterval=M(e.skipBackwardInterval,Q.range),this.skipForwardInterval=M(e.skipForwardInterval,Q.range),this.pollInterval=_(e.pollInterval),this.autoPlay=E(e.autoPlay),this.enableMediaSession=E(e.enableMediaSession)}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new Ve(t)}}class Bn{constructor(e={}){this.volume=M(e.volume,De.range)??1,this.playbackRate=M(e.playbackRate,We.range)??1,this.preservePitch=E(e.preservePitch)??!0,this.skipBackwardInterval=M(e.skipBackwardInterval,Q.range)??10,this.skipForwardInterval=M(e.skipForwardInterval,Q.range)??10,this.pollInterval=_(e.pollInterval)??1e3,this.autoPlay=E(e.autoPlay)??!0,this.enableMediaSession=E(e.enableMediaSession)??!0}}class ni{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 ri{constructor(e,t){this.preferences=e,this.settings=t}clear(){this.preferences=new Ve}updatePreference(e,t){this.preferences[e]=t}get volume(){return new C({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!==null,onChange:e=>{this.updatePreference("volume",e??1)},supportedRange:De.range,step:De.step})}get playbackRate(){return new C({initialValue:this.preferences.playbackRate,effectiveValue:this.settings.playbackRate,isEffective:this.preferences.playbackRate!==null,onChange:e=>{this.updatePreference("playbackRate",e??1)},supportedRange:We.range,step:We.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??!0)}})}get skipBackwardInterval(){return new C({initialValue:this.preferences.skipBackwardInterval,effectiveValue:this.settings.skipBackwardInterval,isEffective:this.preferences.skipBackwardInterval!==null,onChange:e=>{this.updatePreference("skipBackwardInterval",e??10)},supportedRange:Q.range,step:Q.step})}get skipForwardInterval(){return new C({initialValue:this.preferences.skipForwardInterval,effectiveValue:this.settings.skipForwardInterval,isEffective:this.preferences.skipForwardInterval!==null,onChange:e=>{this.updatePreference("skipForwardInterval",e??10)},supportedRange:Q.range,step:Q.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??1e3)}})}get autoPlay(){return new O({initialValue:this.preferences.autoPlay,effectiveValue:this.settings.autoPlay,isEffective:this.preferences.autoPlay!==null,onChange:e=>{this.updatePreference("autoPlay",e??!0)}})}get enableMediaSession(){return new O({initialValue:this.preferences.enableMediaSession,effectiveValue:this.settings.enableMediaSession,isEffective:this.preferences.enableMediaSession!==null,onChange:e=>{this.updatePreference("enableMediaSession",e??!0)}})}}const Vn=1,jn=1;class Po{constructor(e,t){this.pool=new Map,this._audioEngine=e,this._publication=t,this._supportedAudioTypes=this.detectSupportedAudioTypes()}detectSupportedAudioTypes(){const e=document.createElement("audio"),t=new Set;for(const n of this._publication.readingOrder.items){n.type&&t.add(n.type);for(const r of n.alternates?.items??[])r.type&&t.add(r.type)}const i=new Map;for(const n of t){const r=e.canPlayType(n);r!==""&&i.set(n,r)}return i}pickPlayableHref(e){const t=[e,...e.alternates?.items??[]];let i;for(const n of t){if(!n.type)continue;const r=this._supportedAudioTypes.get(n.type);if(r){if(r==="probably")return n.href;i||(i={href:n.href,confidence:r})}}return i?.href??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,i=new Set;for(let n=0;n<t.length;n++){const r=this.pickPlayableHref(t[n]);n>=e-jn&&n<=e+jn?(this.ensure(r),i.add(r)):n>=e-Vn&&n<=e+Vn&&this.pool.has(r)&&i.add(r)}for(const[n,r]of this.pool)i.has(n)||(r.removeAttribute("src"),r.load(),this.pool.delete(n))}setCurrentAudio(e,t){const i=this.pickPlayableHref(this._publication.readingOrder.items[e]),n=this.ensure(i);this.audioEngine.setMediaElement(n),this.pool.delete(i),this.update(e)}destroy(){this.audioEngine.stop();for(const[,e]of this.pool)e.removeAttribute("src"),e.load();this.pool.clear()}}class ne extends Qi{constructor(e){super();const t=e.toc;this.items=t&&t.items.length>0?ne.itemsFromToc(t.items):ne.itemsFromReadingOrder(e.readingOrder.items),this.flat=this.flatten(this.items)}get current(){return this._current}get previous(){return this._previous}get next(){return this._next}update(e){const t=e.href.split("#")[0],i=e.locations?.time()??0,n=this.findCurrent(this.items,t,i);n!==this._current&&(this._current=n,this._previous=n?this.findPrevious(n):void 0,this._next=n?this.findNext(n):void 0,this.changeCallback?.(this._current,this._previous,this._next))}findCurrent(e,t,i){let n;for(const r of this.flat)this.itemMatchesPosition(r,t,i)&&(n=r);if(!n){for(const r of this.flat)if(this.bareHref(r)===t){n=r;break}}return n}findPrevious(e){const t=this.flat.indexOf(e);if(t>0)return this.flat[t-1]}findNext(e){const t=this.flat.indexOf(e);if(t<this.flat.length-1)return this.flat[t+1]}bareHref(e){const t=e.references[0];return t?t.split("#")[0]:""}flatten(e){const t=[];for(const i of e)t.push(i),i.children&&t.push(...this.flatten(i.children));return t}itemMatchesPosition(e,t,i){for(const n of e.references){const[r,s]=n.split("#");if((r||t)!==t)continue;const l=this.parseTimeFragment(s);if(i>=l)return!0}return!1}parseTimeFragment(e){if(!e)return 0;const t=e.match(/(?:^|&)t=(\d+(?:\.\d+)?)/);return t?parseFloat(t[1]):0}static itemsFromToc(e){return e.map(t=>ne.linkToItem(t)).filter(Boolean)}static itemsFromReadingOrder(e){return e.map(t=>ne.linkToItem(t)).filter(Boolean)}static linkToItem(e){if(!e.title)return;const t=e.children?.items.map(i=>ne.linkToItem(i)).filter(Boolean);return{title:e.title,references:[e.href],children:t&&t.length>0?t:void 0}}}class Eo{constructor(e={}){this.dragstartHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onDragDetected?.(Array.from(t.dataTransfer?.types??[]))},this.dropHandler=t=>{t.preventDefault(),t.stopPropagation();const i=Array.from(t.dataTransfer?.types??[]),n=t.dataTransfer?.files.length??0;e.onDropDetected?.(i,n)},document.addEventListener("dragstart",this.dragstartHandler,!0),document.addEventListener("drop",this.dropHandler,!0),window.addEventListener("unload",()=>this.destroy())}destroy(){document.removeEventListener("dragstart",this.dragstartHandler,!0),document.removeEventListener("drop",this.dropHandler,!0)}}class ko{constructor(e={}){this.copyHandler=t=>{t.preventDefault(),t.stopPropagation(),e.onCopyBlocked?.()},document.addEventListener("copy",this.copyHandler,!0),window.addEventListener("unload",()=>this.destroy())}destroy(){document.removeEventListener("copy",this.copyHandler,!0)}}class Co extends qt{constructor(e={}){super(e),e.disableDragAndDrop&&(this.dragAndDropProtector=new Eo({onDragDetected:t=>{this.dispatchSuspiciousActivity("drag_detected",{dataTransferTypes:t,targetFrameSrc:""})},onDropDetected:(t,i)=>{this.dispatchSuspiciousActivity("drop_detected",{dataTransferTypes:t,fileCount:i,targetFrameSrc:""})}})),e.protectCopy&&(this.copyProtector=new ko({onCopyBlocked:()=>{this.dispatchSuspiciousActivity("bulk_copy",{targetFrameSrc:""})}}))}destroy(){super.destroy(),this.dragAndDropProtector?.destroy(),this.copyProtector?.destroy()}}const xo=o=>({trackLoaded:o.trackLoaded??(()=>{}),positionChanged:o.positionChanged??(()=>{}),error:o.error??(()=>{}),trackEnded:o.trackEnded??(()=>{}),play:o.play??(()=>{}),pause:o.pause??(()=>{}),metadataLoaded:o.metadataLoaded??(()=>{}),stalled:o.stalled??(()=>{}),seeking:o.seeking??(()=>{}),seekable:o.seekable??(()=>{}),contentProtection:o.contentProtection??(()=>{}),peripheral:o.peripheral??(()=>{}),contextMenu:o.contextMenu??(()=>{})});class Lo extends Zi{constructor(e,t,i,n={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.pub=e,this._timeline=new ne(e),this.listeners=xo(t),this._preferences=new Ve(n.preferences),this._defaults=new Bn(n.defaults),this._settings=new ni(this._preferences,this._defaults),i)this.currentLocation=this.ensureLocatorLocations(i);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 k({position:0,progression:0,totalProgression:0,fragments:["t=0"]})})}const r=this.currentLocation.href.split("#")[0],s=this.hrefToTrackIndex(r),a=this.currentLocation.locations?.time()||0,l=new Hn({playback:{state:{currentTime:a,duration:0},playWhenReady:!1,index:s}});this.pool=new Po(l,e);const c=n.contentProtection||{},h=this.mergeKeyboardPeripherals(c,n.keyboardPeripherals||[]);(c.disableContextMenu||c.checkAutomation||c.checkIFrameEmbedding||c.monitorDevTools||c.protectPrinting?.disable||c.disableDragAndDrop||c.protectCopy)&&(this._navigatorProtector=new Co(c),this._suspiciousActivityListener=u=>{const{type:m,...b}=u.detail;m==="context_menu"?this.listeners.contextMenu(b):this.listeners.contentProtection(m,b)},window.addEventListener(de,this._suspiciousActivityListener)),h.length>0&&(this._keyboardPeripheralsManager=new Kt({keyboardPeripherals:h}),this._keyboardPeripheralListener=u=>{this.listeners.peripheral(u.detail)},window.addEventListener(ue,this._keyboardPeripheralListener)),this.setupEventListeners(),this.applyPreferences(),this.pool.setCurrentAudio(s,"forward"),this.waitForLoadedAndSeeked(a).then(()=>{this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._timeline.update(this.currentLocator),this.listeners.positionChanged(this.currentLocator)}).catch(()=>{})}get settings(){return this._settings}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new ri(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){this._settings=new ni(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new ri(this._preferences,this.settings)),this.pool.audioEngine.setVolume(this._settings.volume),this.pool.audioEngine.setPlaybackRate(this._settings.playbackRate,this._settings.preservePitch),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._timeline}ensureLocatorLocations(e){return new N({...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(i=>i.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 i=this.pub.readingOrder.items[e];if(!i)throw new Error(`Invalid track index: ${e}`);const n=this.pool.audioEngine.duration();return new N({href:i.href,type:i.type||"audio/mpeg",title:i.title,locations:new k({progression:n>0?t/n:0,position:e,fragments:[`t=${t}`]})})}waitForLoadedAndSeeked(e,t){return new Promise((i,n)=>{const r=()=>{if(t!==void 0&&t!==this.navigationId){i();return}if(e<=0){i();return}const l=()=>{this.pool.audioEngine.off("seeked",l),i()};this.pool.audioEngine.on("seeked",l),this.seek(e)};if(this.pool.audioEngine.isLoaded()){r();return}const s=()=>{this.pool.audioEngine.off("canplaythrough",s),this.pool.audioEngine.off("error",a),r()},a=l=>{this.pool.audioEngine.off("canplaythrough",s),this.pool.audioEngine.off("error",a),n(l)};this.pool.audioEngine.on("canplaythrough",s),this.pool.audioEngine.on("error",a)})}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(),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.startPositionPolling(),this.listeners.play(this.currentLocator)}),this.pool.audioEngine.on("playing",()=>{this.listeners.stalled(!1)}),this.pool.audioEngine.on("pause",()=>{this.stopPositionPolling(),this.listeners.pause(this.currentLocator)}),this.pool.audioEngine.on("seeked",()=>{if(this.listeners.seeking(!1),!this.isPlaying){const e=this.currentTime,t=this.duration,i=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex(),progression:i,fragments:[`t=${e}`]})),this._timeline.update(this.currentLocation),this.listeners.positionChanged(this.currentLocation)}}),this.pool.audioEngine.on("seeking",()=>this.listeners.seeking(!0)),this.pool.audioEngine.on("waiting",()=>this.listeners.seeking(!0)),this.pool.audioEngine.on("stalled",()=>this.listeners.stalled(!0)),this.pool.audioEngine.on("progress",e=>this.listeners.seekable(e)),this.pool.audioEngine.on("loadedmetadata",()=>{this.listeners.metadataLoaded(this.pool.audioEngine.duration())})}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],i=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(n=>n.name.getTranslation()).join(", "):void 0,album:this.pub.metadata.title.getTranslation(),artwork:i?[{src:i.href,type:i.type}]:void 0})}startPositionPolling(){this.stopPositionPolling(),this.positionPollInterval=setInterval(()=>{const e=this.currentTime,t=this.duration,i=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex(),progression:i,fragments:[`t=${e}`]})),this._timeline.update(this.currentLocation),this.listeners.positionChanged(this.currentLocation)},this._settings.pollInterval)}stopPositionPolling(){this.positionPollInterval!==null&&(clearInterval(this.positionPollInterval),this.positionPollInterval=null)}async go(e,t,i){try{e=this.ensureLocatorLocations(e);const n=e.href.split("#")[0],r=this.hrefToTrackIndex(n),s=e.locations?.time()||0;if(r===-1){i(!1);return}const a=++this.navigationId,l=r>=this.currentTrackIndex()?"forward":"backward",c=this.isPlaying||this._playIntent;if(this._playIntent=c,this.stopPositionPolling(),this.pool.setCurrentAudio(r,l),this.currentLocation=e.copyWithLocations(e.locations),await this.waitForLoadedAndSeeked(s,a),a!==this.navigationId)return;this.listeners.trackLoaded(this.pool.audioEngine.getMediaElement()),this._timeline.update(this.currentLocator),this.listeners.positionChanged(this.currentLocator),this._settings.enableMediaSession&&this.updateMediaSessionMetadata(),c&&this.play(),this._playIntent=!1,i(!0)}catch(n){console.error("Failed to go to locator:",n),i(!1)}}async goLink(e,t,i){const n=this.hrefToTrackIndex(e.href);if(n===-1){i(!1);return}const r=e.locator.locations?.time()??0,s=this.createLocator(n,r);await this.go(s,t,i)}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 i=this.pub.readingOrder.items[e],n=this.duration||i?.duration||0;return n>0&&(this.currentLocation.locations?.time()??0)>=n}get canGoBackward(){return this.currentTrackIndex()>0}get canGoForward(){return this.currentTrackIndex()<this.pub.readingOrder.items.length-1}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.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 Gn=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"}}`),Ro=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Gn},publication:Gn},Symbol.toStringTag,{value:"Module"})),Xn={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:"مترجمون"}},Ao=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Xn},publication:Xn},Symbol.toStringTag,{value:"Module"})),$n={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"}},Oo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:$n},publication:$n},Symbol.toStringTag,{value:"Module"})),Yn=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"}}`),To=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Yn},publication:Yn},Symbol.toStringTag,{value:"Module"})),qn={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"}},zo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:qn},publication:qn},Symbol.toStringTag,{value:"Module"})),Kn={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"}},Mo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Kn},publication:Kn},Symbol.toStringTag,{value:"Module"}));y.AudioDefaults=Bn,y.AudioNavigator=Lo,y.AudioPreferences=Ve,y.AudioPreferencesEditor=ri,y.AudioSettings=ni,y.AudioTimeline=ne,y.BooleanPreference=O,y.EnumPreference=Gt,y.EpubDefaults=Un,y.EpubNavigator=ti,y.EpubPreferences=Ee,y.EpubPreferencesEditor=Zt,y.EpubSettings=Qt,y.ExperimentalWebPubNavigator=ao,y.FXLCoordinator=An,y.FXLFrameManager=xn,y.FXLFramePoolManager=Fn,y.FXLPeripherals=zn,y.FXLSpreader=Mn,y.FrameComms=Se,y.FrameManager=Pn,y.FramePoolManager=Cn,y.HorizontalThird=Ln,y.Injector=$t,y.LineLengths=_e,y.MediaNavigator=Zi,y.Navigator=Dt,y.Orientation=dt,y.Preference=T,y.Properties=He,y.RSProperties=Dn,y.RangePreference=C,y.ReadiumCSS=Wn,y.Spread=ut,y.TextAlignment=K,y.Timeline=Qi,y.UserProperties=ei,y.VerticalThird=Rn,y.VisualNavigator=Wt,y.WebAudioEngine=Hn,y.WebPubBlobBuilder=en,y.WebPubCSS=hn,y.WebPubDefaults=pn,y.WebPubFrameManager=sn,y.WebPubFramePoolManager=an,y.WebPubNavigator=_n,y.WebPubPreferences=we,y.WebPubPreferencesEditor=Xt,y.WebPubSettings=jt,y.WebRSProperties=cn,y.WebUserProperties=Bt,y.ensureBoolean=E,y.ensureEnumValue=Be,y.ensureExperiment=Vt,y.ensureFilter=he,y.ensureLessThanOrEqual=dn,y.ensureMoreThanOrEqual=un,y.ensureNonNegative=_,y.ensureString=F,y.ensureValueInRange=M,y.experiments=at,y.filterRangeConfig=le,y.fontSizeRangeConfig=Oe,y.fontWeightRangeConfig=Z,y.fontWidthRangeConfig=Te,y.letterSpacingRangeConfig=ze,y.lineHeightRangeConfig=Me,y.lineLengthRangeConfig=ce,y.paragraphIndentRangeConfig=Ie,y.paragraphSpacingRangeConfig=Ne,y.playbackRateRangeConfig=We,y.sML=Y,y.sMLWithRequest=A,y.skipIntervalRangeConfig=Q,y.volumeRangeConfig=De,y.withFallback=lt,y.wordSpacingRangeConfig=Fe,y.zoomRangeConfig=Ue,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
|
|
1849
|
+
`;class ti{constructor(e){this.workletNode=null,this.url=null,this.ctx=e}static async createWorklet(e){const{ctx:t,pitchFactor:i,modulePath:n}=e,r=new ti(t);try{if(n)await t.audioWorklet.addModule(n);else{const s=new Blob([So],{type:"text/javascript"});r.url=URL.createObjectURL(s),await t.audioWorklet.addModule(r.url)}}catch(s){throw r.destroy(),new Error(`Error adding module: ${s}`)}try{r.workletNode=new AudioWorkletNode(t,"preserve-pitch-processor"),i&&r.updatePitchFactor(i)}catch(s){throw r.destroy(),new Error(`Error creating worklet node: ${s}`)}return r}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 Dn{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(i=>i!==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(i=>i(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 i=this.mediaElement.currentTime+e;i<0?this.mediaElement.currentTime=0:i>t?this.mediaElement.currentTime=t:this.mediaElement.currentTime=i}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):ti.createWorklet({ctx:this.getOrCreateAudioContext(),pitchFactor:1}).then(i=>{this.sourceNode&&this.sourceNode.disconnect(),this.worklet=i,this.sourceNode?.connect(this.worklet.workletNode),this.worklet.workletNode.connect(this.gainNode),this.worklet.updatePitchFactor(1/e)}).catch(i=>{console.warn("Failed to create preserve pitch worklet",i)})}).catch(i=>{console.warn("Web Audio unavailable, playing without pitch correction:",i)}):("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,i=this.isPlayingValue;i&&(this.mediaElement.pause(),this.isPlayingValue=!1),this.mediaElement.crossOrigin="anonymous",this.mediaElement.src=e,this.mediaElement.load();try{await new Promise((r,s)=>{const a=()=>{this.mediaElement.removeEventListener("canplaythrough",a),this.mediaElement.removeEventListener("error",l),r()},l=()=>{this.mediaElement.removeEventListener("canplaythrough",a),this.mediaElement.removeEventListener("error",l),s(new Error("Audio reload with CORS failed — server may not send Access-Control-Allow-Origin"))};this.mediaElement.addEventListener("canplaythrough",a),this.mediaElement.addEventListener("error",l)})}catch(r){throw this.mediaElement.removeAttribute("crossorigin"),this.mediaElement.src=e,this.mediaElement.load(),i?(await new Promise(s=>{const a=()=>{this.mediaElement.removeEventListener("canplaythrough",a),s()};this.mediaElement.addEventListener("canplaythrough",a)}),this.mediaElement.currentTime=t,await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1):this.mediaElement.currentTime=t,r}this.mediaElement.currentTime=t,this.sourceNode=new MediaElementAudioSourceNode(this.getOrCreateAudioContext(),{mediaElement:this.mediaElement});const n=this.getOrCreateAudioContext();this.gainNode=n.createGain(),this.gainNode.gain.value=this.mediaElement.volume,this.mediaElement.volume=1,this.sourceNode.connect(this.gainNode),this.gainNode.connect(n.destination),this.webAudioActive=!0,i&&(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=()=>{n()},i=()=>{n(),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()},n=()=>{this.mediaElement.removeEventListener("canplaythrough",t),this.mediaElement.removeEventListener("error",i)};this.mediaElement.addEventListener("canplaythrough",t),this.mediaElement.addEventListener("error",i)}else this.mediaElement.src=e,this.mediaElement.load()}getMediaElement(){return this.mediaElement}}class Be{constructor(e={}){this.volume=M(e.volume,Ue.range),this.playbackRate=M(e.playbackRate,De.range),this.preservePitch=E(e.preservePitch),this.skipBackwardInterval=M(e.skipBackwardInterval,Q.range),this.skipForwardInterval=M(e.skipForwardInterval,Q.range),this.pollInterval=_(e.pollInterval),this.autoPlay=E(e.autoPlay),this.enableMediaSession=E(e.enableMediaSession)}merging(e){const t={...this};for(const i of Object.keys(e))e[i]!==void 0&&(t[i]=e[i]);return new Be(t)}}class Wn{constructor(e={}){this.volume=M(e.volume,Ue.range)??1,this.playbackRate=M(e.playbackRate,De.range)??1,this.preservePitch=E(e.preservePitch)??!0,this.skipBackwardInterval=M(e.skipBackwardInterval,Q.range)??10,this.skipForwardInterval=M(e.skipForwardInterval,Q.range)??10,this.pollInterval=_(e.pollInterval)??1e3,this.autoPlay=E(e.autoPlay)??!0,this.enableMediaSession=E(e.enableMediaSession)??!0}}class ii{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 ni{constructor(e,t){this.preferences=e,this.settings=t}clear(){this.preferences=new Be}updatePreference(e,t){this.preferences[e]=t}get volume(){return new C({initialValue:this.preferences.volume,effectiveValue:this.settings.volume,isEffective:this.preferences.volume!==null,onChange:e=>{this.updatePreference("volume",e??null)},supportedRange:Ue.range,step:Ue.step})}get playbackRate(){return new C({initialValue:this.preferences.playbackRate,effectiveValue:this.settings.playbackRate,isEffective:this.preferences.playbackRate!==null,onChange:e=>{this.updatePreference("playbackRate",e??null)},supportedRange:De.range,step:De.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 C({initialValue:this.preferences.skipBackwardInterval,effectiveValue:this.settings.skipBackwardInterval,isEffective:this.preferences.skipBackwardInterval!==null,onChange:e=>{this.updatePreference("skipBackwardInterval",e??null)},supportedRange:Q.range,step:Q.step})}get skipForwardInterval(){return new C({initialValue:this.preferences.skipForwardInterval,effectiveValue:this.settings.skipForwardInterval,isEffective:this.preferences.skipForwardInterval!==null,onChange:e=>{this.updatePreference("skipForwardInterval",e??null)},supportedRange:Q.range,step:Q.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 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 Hn=1,Bn=1;class _o{constructor(e,t,i={}){this.pool=new Map,this._audioEngine=e,this._publication=t,this._supportedAudioTypes=this.detectSupportedAudioTypes(),i.disableRemotePlayback&&(this._audioEngine.getMediaElement().disableRemotePlayback=!0)}detectSupportedAudioTypes(){const e=document.createElement("audio"),t=new Set;for(const n of this._publication.readingOrder.items){n.type&&t.add(n.type);for(const r of n.alternates?.items??[])r.type&&t.add(r.type)}const i=new Map;for(const n of t){const r=e.canPlayType(n);r!==""&&i.set(n,r)}return i}pickPlayableHref(e){const t=this._publication.baseURL,i=[e,...e.alternates?.items??[]];let n;for(const r of i){if(!r.type)continue;const s=this._supportedAudioTypes.get(r.type);if(!s)continue;const a=r.toURL(t)??r.href;if(s==="probably")return a;n||(n={href:a,confidence:s})}return n?.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,i=new Set;for(let n=0;n<t.length;n++){if(n===e)continue;const r=this.pickPlayableHref(t[n]);n>=e-Bn&&n<=e+Bn?(this.ensure(r),i.add(r)):n>=e-Hn&&n<=e+Hn&&this.pool.has(r)&&i.add(r)}for(const[n,r]of this.pool)i.has(n)||(r.removeAttribute("src"),r.load(),this.pool.delete(n))}setCurrentAudio(e,t){const i=this.pickPlayableHref(this._publication.readingOrder.items[e]);if(this.audioEngine.changeSrc(i),this.pool.has(i)){const n=this.pool.get(i);n.removeAttribute("src"),n.load(),this.pool.delete(i)}this.update(e)}destroy(){this.audioEngine.stop();for(const[,e]of this.pool)e.removeAttribute("src"),e.load();this.pool.clear()}}class wo{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 i=Array.from(t.dataTransfer?.types??[]),n=t.dataTransfer?.files.length??0;e.onDropDetected?.(i,n)},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 Po{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 Eo extends qt{constructor(e={}){super(e),e.disableDragAndDrop&&(this.dragAndDropProtector=new wo({onDragDetected:t=>{this.dispatchSuspiciousActivity("drag_detected",{dataTransferTypes:t,targetFrameSrc:""})},onDropDetected:(t,i)=>{this.dispatchSuspiciousActivity("drop_detected",{dataTransferTypes:t,fileCount:i,targetFrameSrc:""})}})),e.protectCopy&&(this.copyProtector=new Po({onCopyBlocked:()=>{this.dispatchSuspiciousActivity("bulk_copy",{targetFrameSrc:""})}}))}destroy(){super.destroy(),this.dragAndDropProtector?.destroy(),this.copyProtector?.destroy()}}const ko=o=>({trackLoaded:o.trackLoaded??(()=>{}),positionChanged:o.positionChanged??(()=>{}),timelineItemChanged:o.timelineItemChanged??(()=>{}),error:o.error??(()=>{}),trackEnded:o.trackEnded??(()=>{}),play:o.play??(()=>{}),pause:o.pause??(()=>{}),metadataLoaded:o.metadataLoaded??(()=>{}),stalled:o.stalled??(()=>{}),seeking:o.seeking??(()=>{}),seekable:o.seekable??(()=>{}),contentProtection:o.contentProtection??(()=>{}),peripheral:o.peripheral??(()=>{}),contextMenu:o.contextMenu??(()=>{}),remotePlaybackStateChanged:o.remotePlaybackStateChanged??(()=>{})});class Co extends Ji{constructor(e,t,i,n={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=ko(t),this._preferences=new Be(n.preferences),this._defaults=new Wn(n.defaults),this._settings=new ii(this._preferences,this._defaults),e.readingOrder.items.length===0)throw new Error("AudioNavigator: publication has an empty reading order");if(i)this.currentLocation=this.ensureLocatorLocations(i);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 r=this.currentLocation.href.split("#")[0],s=this.hrefToTrackIndex(r);if(s===-1)throw new Error(`AudioNavigator: initial href "${r}" not found in reading order`);const a=this.currentLocation.locations?.time()||0,l=new Dn({playback:{state:{currentTime:a,duration:0},playWhenReady:!1,index:s}});this.pool=new _o(l,e,n.contentProtection);const c=n.contentProtection||{};this._contentProtection=c;const h=this.mergeKeyboardPeripherals(c,n.keyboardPeripherals||[]);(c.disableContextMenu||c.checkAutomation||c.checkIFrameEmbedding||c.monitorDevTools||c.protectPrinting?.disable||c.disableDragAndDrop||c.protectCopy)&&(this._navigatorProtector=new Eo(c),this._suspiciousActivityListener=u=>{const{type:m,...b}=u.detail;m==="context_menu"?this.listeners.contextMenu(b):this.listeners.contentProtection(m,b)},window.addEventListener(he,this._suspiciousActivityListener)),h.length>0&&(this._keyboardPeripheralsManager=new Yt({keyboardPeripherals:h}),this._keyboardPeripheralListener=u=>{this.listeners.peripheral(u.detail)},window.addEventListener(de,this._keyboardPeripheralListener)),this.setupEventListeners(),this._isNavigating=!0,this.pool.setCurrentAudio(s,"forward"),this.applyPreferences(),this.waitForLoadedAndSeeked(a).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 ni(this._preferences,this.settings)),this._preferencesEditor}async submitPreferences(e){this._preferences=this._preferences.merging(e),this.applyPreferences()}applyPreferences(){this._settings=new ii(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new ni(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(i=>i.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 i=this.pub.readingOrder.items[e];if(!i)throw new Error(`Invalid track index: ${e}`);const n=this.pool.audioEngine.duration();return new F({href:i.href,type:i.type||"audio/mpeg",title:i.title,locations:new k({progression:n>0?t/n:0,position:e+1,fragments:[`t=${t}`]})})}waitForLoadedAndSeeked(e,t){return new Promise((i,n)=>{const r=()=>{if(t!==void 0&&t!==this.navigationId){i();return}if(e<=0){i();return}const l=()=>{this.pool.audioEngine.off("seeked",l),i()};this.pool.audioEngine.on("seeked",l),this.seek(e)};if(this.pool.audioEngine.isLoaded()){r();return}const s=()=>{this.pool.audioEngine.off("canplaythrough",s),this.pool.audioEngine.off("error",a),r()},a=l=>{this.pool.audioEngine.off("canplaythrough",s),this.pool.audioEngine.off("error",a),n(l)};this.pool.audioEngine.on("canplaythrough",s),this.pool.audioEngine.on("error",a)})}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,i=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex()+1,progression:i,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],i=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(n=>n.name.getTranslation()).join(", "):void 0,album:this.pub.metadata.title.getTranslation(),artwork:i?[{src:i.toURL(this.pub.baseURL)??i.href,type:i.type}]:void 0})}startPositionPolling(){this.stopPositionPolling(),this.positionPollInterval=setInterval(()=>{const e=this.currentTime,t=this.duration,i=t>0?e/t:0;this.currentLocation=this.currentLocation.copyWithLocations(new k({position:this.currentTrackIndex()+1,progression:i,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,i){try{e=this.ensureLocatorLocations(e);const n=e.href.split("#")[0],r=this.hrefToTrackIndex(n),s=e.locations?.time()||0;if(r===-1){i(!1);return}const a=++this.navigationId,l=this.currentTrackIndex(),c=r>=l?"forward":"backward",h=this.isPlaying||this._playIntent;if(this._playIntent=h,this._isNavigating=!0,this.stopPositionPolling(),this.pool.setCurrentAudio(r,c),this.currentLocation=e.copyWithLocations(e.locations),await this.waitForLoadedAndSeeked(s,a),this._isNavigating=!1,a!==this.navigationId){i(!1);return}r!==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(),i(!0)}catch(n){this._isNavigating=!1,console.error("Failed to go to locator:",n),i(!1)}finally{this._playIntent=!1}}async goLink(e,t,i){const n=this.hrefToTrackIndex(e.href);if(n===-1){i(!1);return}const r=e.locator.locations?.time()??0,s=this.createLocator(n,r);await this.go(s,t,i)}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 i=this.pub.readingOrder.items[e],n=this.duration||i?.duration||0;return n>0&&(this.currentLocation.locations?.time()??0)>=n}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(he,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(de,this._keyboardPeripheralListener),this._navigatorProtector?.destroy(),this._keyboardPeripheralsManager?.destroy(),this.pool.destroy()}}const Vn=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"}}`),xo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Vn},publication:Vn},Symbol.toStringTag,{value:"Module"})),jn={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:"مترجمون"}},Lo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:jn},publication:jn},Symbol.toStringTag,{value:"Module"})),Gn={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"}},Ro=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Gn},publication:Gn},Symbol.toStringTag,{value:"Module"})),$n=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"}}`),Ao=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:$n},publication:$n},Symbol.toStringTag,{value:"Module"})),Xn={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"}},Oo=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:Xn},publication:Xn},Symbol.toStringTag,{value:"Module"})),qn={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"}},To=Object.freeze(Object.defineProperty({__proto__:null,default:{publication:qn},publication:qn},Symbol.toStringTag,{value:"Module"}));y.AudioDefaults=Wn,y.AudioNavigator=Co,y.AudioPreferences=Be,y.AudioPreferencesEditor=ni,y.AudioSettings=ii,y.BooleanPreference=O,y.EnumPreference=jt,y.EpubDefaults=Fn,y.EpubNavigator=ei,y.EpubPreferences=Pe,y.EpubPreferencesEditor=Jt,y.EpubSettings=Zt,y.ExperimentalWebPubNavigator=oo,y.FXLCoordinator=Ln,y.FXLFrameManager=kn,y.FXLFramePoolManager=In,y.FXLPeripherals=On,y.FXLSpreader=Tn,y.FrameComms=ve,y.FrameManager=_n,y.FramePoolManager=En,y.HorizontalThird=Cn,y.Injector=$t,y.LineLengths=Se,y.MediaNavigator=Ji,y.Navigator=Ut,y.Orientation=ht,y.Preference=T,y.Properties=We,y.RSProperties=Nn,y.RangePreference=C,y.ReadiumCSS=Un,y.Spread=dt,y.TextAlignment=K,y.UserProperties=Qt,y.VerticalThird=xn,y.VisualNavigator=Dt,y.WebAudioEngine=Dn,y.WebPubBlobBuilder=Zi,y.WebPubCSS=ln,y.WebPubDefaults=dn,y.WebPubFrameManager=rn,y.WebPubFramePoolManager=on,y.WebPubNavigator=vn,y.WebPubPreferences=_e,y.WebPubPreferencesEditor=Gt,y.WebPubSettings=Vt,y.WebRSProperties=an,y.WebUserProperties=Ht,y.ensureBoolean=E,y.ensureEnumValue=He,y.ensureExperiment=Bt,y.ensureFilter=ce,y.ensureLessThanOrEqual=cn,y.ensureMoreThanOrEqual=hn,y.ensureNonNegative=_,y.ensureString=N,y.ensureValueInRange=M,y.experiments=st,y.filterRangeConfig=ae,y.fontSizeRangeConfig=Ae,y.fontWeightRangeConfig=Z,y.fontWidthRangeConfig=Oe,y.letterSpacingRangeConfig=Te,y.lineHeightRangeConfig=ze,y.lineLengthRangeConfig=le,y.paragraphIndentRangeConfig=Me,y.paragraphSpacingRangeConfig=Ie,y.playbackRateRangeConfig=De,y.sML=q,y.sMLWithRequest=A,y.skipIntervalRangeConfig=Q,y.volumeRangeConfig=Ue,y.withFallback=at,y.wordSpacingRangeConfig=Fe,y.zoomRangeConfig=Ne,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
|