@readium/navigator 2.4.0-alpha.2 → 2.4.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const w = class w {
1
+ const v = class v {
2
2
  constructor(t) {
3
3
  this.uri = t;
4
4
  }
@@ -7,7 +7,7 @@ const w = class w {
7
7
  */
8
8
  static deserialize(t) {
9
9
  if (!(!t || typeof t != "string"))
10
- return new w(t);
10
+ return new v(t);
11
11
  }
12
12
  /**
13
13
  * Serializes an [AccessibilityProfile] to its RWPM JSON representation.
@@ -19,23 +19,23 @@ const w = class w {
19
19
  * Returns true if the profile is a WCAG Level A profile.
20
20
  */
21
21
  get isWCAGLevelA() {
22
- return this === w.EPUB_A11Y_10_WCAG_20_A || this === w.EPUB_A11Y_11_WCAG_20_A || this === w.EPUB_A11Y_11_WCAG_21_A || this === w.EPUB_A11Y_11_WCAG_22_A;
22
+ return this === v.EPUB_A11Y_10_WCAG_20_A || this === v.EPUB_A11Y_11_WCAG_20_A || this === v.EPUB_A11Y_11_WCAG_21_A || this === v.EPUB_A11Y_11_WCAG_22_A;
23
23
  }
24
24
  /**
25
25
  * Returns true if the profile is a WCAG Level AA profile.
26
26
  */
27
27
  get isWCAGLevelAA() {
28
- return this === w.EPUB_A11Y_10_WCAG_20_AA || this === w.EPUB_A11Y_11_WCAG_20_AA || this === w.EPUB_A11Y_11_WCAG_21_AA || this === w.EPUB_A11Y_11_WCAG_22_AA;
28
+ return this === v.EPUB_A11Y_10_WCAG_20_AA || this === v.EPUB_A11Y_11_WCAG_20_AA || this === v.EPUB_A11Y_11_WCAG_21_AA || this === v.EPUB_A11Y_11_WCAG_22_AA;
29
29
  }
30
30
  /**
31
31
  * Returns true if the profile is a WCAG Level AAA profile.
32
32
  */
33
33
  get isWCAGLevelAAA() {
34
- return this === w.EPUB_A11Y_10_WCAG_20_AAA || this === w.EPUB_A11Y_11_WCAG_20_AAA || this === w.EPUB_A11Y_11_WCAG_21_AAA || this === w.EPUB_A11Y_11_WCAG_22_AAA;
34
+ return this === v.EPUB_A11Y_10_WCAG_20_AAA || this === v.EPUB_A11Y_11_WCAG_20_AAA || this === v.EPUB_A11Y_11_WCAG_21_AAA || this === v.EPUB_A11Y_11_WCAG_22_AAA;
35
35
  }
36
36
  };
37
- w.EPUB_A11Y_10_WCAG_20_A = new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"), w.EPUB_A11Y_10_WCAG_20_AA = new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"), w.EPUB_A11Y_10_WCAG_20_AAA = new w("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"), w.EPUB_A11Y_11_WCAG_20_A = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"), w.EPUB_A11Y_11_WCAG_20_AA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"), w.EPUB_A11Y_11_WCAG_20_AAA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"), w.EPUB_A11Y_11_WCAG_21_A = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"), w.EPUB_A11Y_11_WCAG_21_AA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"), w.EPUB_A11Y_11_WCAG_21_AAA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"), w.EPUB_A11Y_11_WCAG_22_A = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"), w.EPUB_A11Y_11_WCAG_22_AA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"), w.EPUB_A11Y_11_WCAG_22_AAA = new w("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");
38
- let De = w;
37
+ v.EPUB_A11Y_10_WCAG_20_A = new v("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-a"), v.EPUB_A11Y_10_WCAG_20_AA = new v("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aa"), v.EPUB_A11Y_10_WCAG_20_AAA = new v("http://www.idpf.org/epub/a11y/accessibility-20170105.html#wcag-aaa"), v.EPUB_A11Y_11_WCAG_20_A = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-a"), v.EPUB_A11Y_11_WCAG_20_AA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aa"), v.EPUB_A11Y_11_WCAG_20_AAA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.0-aaa"), v.EPUB_A11Y_11_WCAG_21_A = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-a"), v.EPUB_A11Y_11_WCAG_21_AA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aa"), v.EPUB_A11Y_11_WCAG_21_AAA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.1-aaa"), v.EPUB_A11Y_11_WCAG_22_A = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-a"), v.EPUB_A11Y_11_WCAG_22_AA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aa"), v.EPUB_A11Y_11_WCAG_22_AAA = new v("https://www.w3.org/TR/epub-a11y-11#wcag-2.2-aaa");
38
+ let De = v;
39
39
  const E = class E {
40
40
  constructor(t) {
41
41
  this.value = t;
@@ -913,7 +913,7 @@ class H {
913
913
  });
914
914
  }
915
915
  }
916
- class V {
916
+ class B {
917
917
  /**
918
918
  * Creates a [Link].
919
919
  */
@@ -925,7 +925,7 @@ class V {
925
925
  */
926
926
  static deserialize(t) {
927
927
  if (!(!t || typeof t.href != "string"))
928
- return new V({
928
+ return new B({
929
929
  href: t.href,
930
930
  templated: t.templated,
931
931
  type: t.type,
@@ -970,7 +970,7 @@ class V {
970
970
  * See RFC 6570 on URI template: https://tools.ietf.org/html/rfc6570
971
971
  */
972
972
  expandTemplate(t) {
973
- return new V({
973
+ return new B({
974
974
  href: new Xe(this.href).expand(t),
975
975
  templated: !1
976
976
  });
@@ -979,7 +979,7 @@ class V {
979
979
  * Makes a copy of this [Link] after merging in the given additional other [properties].
980
980
  */
981
981
  addProperties(t) {
982
- const e = V.deserialize(this.serialize());
982
+ const e = B.deserialize(this.serialize());
983
983
  return e.properties = e.properties ? e.properties?.add(t) : new G(t), e;
984
984
  }
985
985
  /**
@@ -1010,7 +1010,7 @@ class Ft {
1010
1010
  static deserialize(t) {
1011
1011
  if (t && Array.isArray(t))
1012
1012
  return new Ft(
1013
- t.map((e) => V.deserialize(e)).filter((e) => e !== void 0)
1013
+ t.map((e) => B.deserialize(e)).filter((e) => e !== void 0)
1014
1014
  );
1015
1015
  }
1016
1016
  /**
@@ -1341,7 +1341,7 @@ G.prototype.getAvailability = function() {
1341
1341
  return ke.deserialize(this.otherProperties.availability);
1342
1342
  };
1343
1343
  G.prototype.getAuthenticate = function() {
1344
- return V.deserialize(this.otherProperties.authenticate);
1344
+ return B.deserialize(this.otherProperties.authenticate);
1345
1345
  };
1346
1346
  const fn = "CssSelectorGenerator";
1347
1347
  function Ye(s = "unknown problem", ...t) {
@@ -1376,8 +1376,8 @@ bn([
1376
1376
  // Angular attributes
1377
1377
  "ng-*"
1378
1378
  ]);
1379
- const vn = Math.pow(2, 32), qe = () => Math.round(Math.random() * vn).toString(36), de = () => `${Math.round(performance.now())}-${qe()}-${qe()}`, ht = 1;
1380
- class wn {
1379
+ const wn = Math.pow(2, 32), qe = () => Math.round(Math.random() * wn).toString(36), de = () => `${Math.round(performance.now())}-${qe()}-${qe()}`, ht = 1;
1380
+ class vn {
1381
1381
  constructor(t) {
1382
1382
  this.destination = null, this.registrar = /* @__PURE__ */ new Map(), this.origin = "", this.channelId = "", this.receiver = this.receive.bind(this), this.preLog = [], this.wnd = t, t.addEventListener("message", this.receiver);
1383
1383
  }
@@ -1515,10 +1515,10 @@ function ki(s, t, e) {
1515
1515
  for (let p = 0; p <= r; p += 1) {
1516
1516
  d[p] = 0;
1517
1517
  for (let b = 0; b < n; b += 1) {
1518
- const v = p * n + b;
1519
- if (v >= t.length)
1518
+ const w = p * n + b;
1519
+ if (w >= t.length)
1520
1520
  continue;
1521
- t.charCodeAt(v) === y && (d[p] |= 1 << b);
1521
+ t.charCodeAt(w) === y && (d[p] |= 1 << b);
1522
1522
  }
1523
1523
  }
1524
1524
  }
@@ -1540,8 +1540,8 @@ function ki(s, t, e) {
1540
1540
  h += 1, o.P[h] = -1, o.M[h] = 0;
1541
1541
  let b;
1542
1542
  if (h === r) {
1543
- const v = t.length % n;
1544
- b = v === 0 ? n : v;
1543
+ const w = t.length % n;
1544
+ b = w === 0 ? n : w;
1545
1545
  } else
1546
1546
  b = n;
1547
1547
  u[h] = u[h - 1] + b - p + Ze(o, d, h, p);
@@ -2011,7 +2011,7 @@ function Mi(s, t, e) {
2011
2011
  const r = s[i], o = s[n];
2012
2012
  if (r === o)
2013
2013
  continue;
2014
- const a = B(r.top, o.top, t) && B(r.bottom, o.bottom, t), l = B(r.left, o.left, t) && B(r.right, o.right, t);
2014
+ const a = V(r.top, o.top, t) && V(r.bottom, o.bottom, t), l = V(r.left, o.left, t) && V(r.right, o.right, t);
2015
2015
  if (a && !l && Ni(r, o, t)) {
2016
2016
  const u = s.filter((y) => y !== r && y !== o), m = Ln(r, o);
2017
2017
  return u.push(m), Mi(
@@ -2052,7 +2052,7 @@ function kn(s, t, e) {
2052
2052
  return kt(s, t.left, t.top, e) && kt(s, t.right, t.top, e) && kt(s, t.left, t.bottom, e) && kt(s, t.right, t.bottom, e);
2053
2053
  }
2054
2054
  function kt(s, t, e, i) {
2055
- return (s.left < t || B(s.left, t, i)) && (s.right > t || B(s.right, t, i)) && (s.top < e || B(s.top, e, i)) && (s.bottom > e || B(s.bottom, e, i));
2055
+ return (s.left < t || V(s.left, t, i)) && (s.right > t || V(s.right, t, i)) && (s.top < e || V(s.top, e, i)) && (s.bottom > e || V(s.bottom, e, i));
2056
2056
  }
2057
2057
  function Ui(s) {
2058
2058
  for (let t = 0; t < s.length; t++)
@@ -2136,9 +2136,9 @@ function Tn(s, t) {
2136
2136
  };
2137
2137
  }
2138
2138
  function Ni(s, t, e) {
2139
- return (s.left < t.right || e >= 0 && B(s.left, t.right, e)) && (t.left < s.right || e >= 0 && B(t.left, s.right, e)) && (s.top < t.bottom || e >= 0 && B(s.top, t.bottom, e)) && (t.top < s.bottom || e >= 0 && B(t.top, s.bottom, e));
2139
+ return (s.left < t.right || e >= 0 && V(s.left, t.right, e)) && (t.left < s.right || e >= 0 && V(t.left, s.right, e)) && (s.top < t.bottom || e >= 0 && V(s.top, t.bottom, e)) && (t.top < s.bottom || e >= 0 && V(t.top, s.bottom, e));
2140
2140
  }
2141
- function B(s, t, e) {
2141
+ function V(s, t, e) {
2142
2142
  return Math.abs(s - t) <= e;
2143
2143
  }
2144
2144
  function Te(s) {
@@ -2329,14 +2329,14 @@ class Nn {
2329
2329
  ), r = i / (n || 1), o = this.wnd.document.scrollingElement, a = o.scrollLeft, l = o.scrollTop, c = (d, p, b) => {
2330
2330
  if (d.style.position = "absolute", t.decoration?.style?.width === "viewport") {
2331
2331
  d.style.width = `${i}px`, d.style.height = `${p.height}px`;
2332
- let v = Math.floor(p.left / i) * i;
2333
- d.style.left = `${v + a}px`, d.style.top = `${p.top + l}px`;
2332
+ let w = Math.floor(p.left / i) * i;
2333
+ d.style.left = `${w + a}px`, d.style.top = `${p.top + l}px`;
2334
2334
  } else if (t.decoration?.style?.width === "bounds")
2335
2335
  d.style.width = `${b.width}px`, d.style.height = `${p.height}px`, d.style.left = `${b.left + a}px`, d.style.top = `${p.top + l}px`;
2336
2336
  else if (t.decoration?.style?.width === "page") {
2337
2337
  d.style.width = `${r}px`, d.style.height = `${p.height}px`;
2338
- let v = Math.floor(p.left / r) * r;
2339
- d.style.left = `${v + a}px`, d.style.top = `${p.top + l}px`;
2338
+ let w = Math.floor(p.left / r) * r;
2339
+ d.style.left = `${w + a}px`, d.style.top = `${p.top + l}px`;
2340
2340
  } else
2341
2341
  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`;
2342
2342
  }, h = t.range.getBoundingClientRect();
@@ -2403,7 +2403,7 @@ class Nn {
2403
2403
  this.experimentalHighlights && this.wnd.CSS.highlights.delete(this.id), this.container && (this.container.remove(), this.container = void 0);
2404
2404
  }
2405
2405
  }
2406
- const vt = class vt extends ft {
2406
+ const wt = class wt extends ft {
2407
2407
  constructor() {
2408
2408
  super(...arguments), this.resizeFrame = 0, this.lastGroupId = 0, this.groups = /* @__PURE__ */ new Map(), this.handleResizer = this.handleResize.bind(this);
2409
2409
  }
@@ -2428,7 +2428,7 @@ const vt = class vt extends ft {
2428
2428
  }, 50);
2429
2429
  }
2430
2430
  mount(t, e) {
2431
- return this.wnd = t, e.register("decorate", vt.moduleName, (i, n) => {
2431
+ return this.wnd = t, e.register("decorate", wt.moduleName, (i, n) => {
2432
2432
  const r = i;
2433
2433
  r.decoration && r.decoration.locator && (r.decoration.locator = H.deserialize(r.decoration.locator)), this.groups.has(r.group) || this.groups.set(r.group, new Nn(
2434
2434
  t,
@@ -2468,12 +2468,12 @@ const vt = class vt extends ft {
2468
2468
  }), e.log("Decorator Mounted"), !0;
2469
2469
  }
2470
2470
  unmount(t, e) {
2471
- return t.removeEventListener("orientationchange", this.handleResizer), t.removeEventListener("resize", this.handleResizer), e.unregisterAll(vt.moduleName), this.resizeObserver.disconnect(), this.backgroundObserver.disconnect(), this.cleanup(), e.log("Decorator Unmounted"), !0;
2471
+ return t.removeEventListener("orientationchange", this.handleResizer), t.removeEventListener("resize", this.handleResizer), e.unregisterAll(wt.moduleName), this.resizeObserver.disconnect(), this.backgroundObserver.disconnect(), this.cleanup(), e.log("Decorator Unmounted"), !0;
2472
2472
  }
2473
2473
  };
2474
- vt.moduleName = "decorator";
2475
- let ge = vt;
2476
- const oi = "readium-snapper-style", wt = class wt extends ft {
2474
+ wt.moduleName = "decorator";
2475
+ let ge = wt;
2476
+ const oi = "readium-snapper-style", vt = class vt extends ft {
2477
2477
  constructor() {
2478
2478
  super(...arguments), this.protected = !1;
2479
2479
  }
@@ -2486,9 +2486,9 @@ const oi = "readium-snapper-style", wt = class wt extends ft {
2486
2486
  }
2487
2487
  mount(t, e) {
2488
2488
  const i = t.document.createElement("style");
2489
- return i.dataset.readium = "true", i.id = oi, i.textContent = this.buildStyles(), t.document.head.appendChild(i), e.register("protect", wt.moduleName, (n, r) => {
2489
+ return i.dataset.readium = "true", i.id = oi, i.textContent = this.buildStyles(), t.document.head.appendChild(i), e.register("protect", vt.moduleName, (n, r) => {
2490
2490
  this.protected = !0, i.textContent = this.buildStyles(), r(!0);
2491
- }), e.register("unprotect", wt.moduleName, (n, r) => {
2491
+ }), e.register("unprotect", vt.moduleName, (n, r) => {
2492
2492
  this.protected = !1, i.textContent = this.buildStyles(), r(!0);
2493
2493
  }), e.log("Snapper Mounted"), !0;
2494
2494
  }
@@ -2496,8 +2496,8 @@ const oi = "readium-snapper-style", wt = class wt extends ft {
2496
2496
  return t.document.getElementById(oi)?.remove(), e.log("Snapper Unmounted"), !0;
2497
2497
  }
2498
2498
  };
2499
- wt.moduleName = "snapper";
2500
- let Et = wt;
2499
+ vt.moduleName = "snapper";
2500
+ let Et = vt;
2501
2501
  function nt(s) {
2502
2502
  return s.document.body.dir.toLowerCase() === "rtl";
2503
2503
  }
@@ -2711,7 +2711,7 @@ const hi = "readium-column-snapper-style", jn = 200, U = class U extends Et {
2711
2711
  ), h = this.snapOffset(a + c), u = h > this.scrollOffset() ? "right" : "left";
2712
2712
  if (this.checkSuspiciousSnap(u, Math.abs(h - this.scrollOffset())), t && h !== this.scrollOffset()) {
2713
2713
  this.snappingCancelled = !1;
2714
- const m = (b, v, L, Q) => L > Q ? v : b + (v - b) * Fn(L / Q), y = (
2714
+ const m = (b, w, L, Q) => L > Q ? w : b + (w - b) * Fn(L / Q), y = (
2715
2715
  /*Math.abs(startX - (this.useTransform ? currentOffset : 0)) < 10 ? 1 : */
2716
2716
  jn * o
2717
2717
  );
@@ -2719,8 +2719,8 @@ const hi = "readium-column-snapper-style", jn = 200, U = class U extends Et {
2719
2719
  const p = (b) => {
2720
2720
  if (this.snappingCancelled) return;
2721
2721
  d || (d = b);
2722
- const v = b - d, L = m(this.overscroll, 0, v, y), Q = m(i, h, v, y);
2723
- n.scrollLeft = Q, this.overscroll !== 0 && (n.style.transform = `translate3d(${-L}px, 0px, 0px)`), v < y ? this.wnd.requestAnimationFrame(p) : (this.clearTouches(), n.style.removeProperty("transform"), n.scrollLeft = h, e || this.reportProgress());
2722
+ const w = b - d, L = m(this.overscroll, 0, w, y), Q = m(i, h, w, y);
2723
+ n.scrollLeft = Q, this.overscroll !== 0 && (n.style.transform = `translate3d(${-L}px, 0px, 0px)`), w < y ? this.wnd.requestAnimationFrame(p) : (this.clearTouches(), n.style.removeProperty("transform"), n.scrollLeft = h, e || this.reportProgress());
2724
2724
  };
2725
2725
  this.wnd.requestAnimationFrame(p);
2726
2726
  } else
@@ -3622,7 +3622,7 @@ const _t = class _t extends ft {
3622
3622
  ), Reflect.defineProperty(t.navigator, "epubReadingSystem", {
3623
3623
  value: {
3624
3624
  name: "readium-ts-toolkit",
3625
- version: "2.4.0-alpha.1",
3625
+ version: "2.4.0-alpha.2",
3626
3626
  hasFeature: (n, r = "") => {
3627
3627
  switch (n) {
3628
3628
  case "dom-manipulation":
@@ -3702,7 +3702,7 @@ const di = "readium-viewport", K = class K extends Ht {
3702
3702
  }
3703
3703
  };
3704
3704
  K.moduleName = "reflowable_setup";
3705
- let ve = K;
3705
+ let we = K;
3706
3706
  const ui = "readium-fixed-style", $ = class $ extends Ht {
3707
3707
  mount(t, e) {
3708
3708
  if (!super.mount(t, e)) return !1;
@@ -3745,7 +3745,7 @@ const ui = "readium-fixed-style", $ = class $ extends Ht {
3745
3745
  }
3746
3746
  };
3747
3747
  $.moduleName = "fixed_setup";
3748
- let we = $;
3748
+ let ve = $;
3749
3749
  const Z = class Z extends ft {
3750
3750
  wndOnErr(t) {
3751
3751
  this.comms?.send("error", {
@@ -3836,8 +3836,8 @@ const Yn = [
3836
3836
  "print_protection"
3837
3837
  ], Bt = new Map([
3838
3838
  // All modules go here
3839
- we,
3840
3839
  ve,
3840
+ we,
3841
3841
  _e,
3842
3842
  Se,
3843
3843
  be,
@@ -3852,7 +3852,7 @@ class gt {
3852
3852
  * @param initialModules List of initial modules to load
3853
3853
  */
3854
3854
  constructor(t = window, e = []) {
3855
- this.loadedModules = [], this.wnd = t, this.comms = new wn(t);
3855
+ this.loadedModules = [], this.wnd = t, this.comms = new vn(t);
3856
3856
  const i = [...new Set(e)];
3857
3857
  if (i.length) {
3858
3858
  if (typeof t > "u")
@@ -4371,15 +4371,15 @@ class hr {
4371
4371
  }), this.blobs.clear()), this.currentBaseURL = t.baseURL;
4372
4372
  const m = async (d) => {
4373
4373
  if (this.pendingUpdates.has(d) && this.pendingUpdates.get(d)?.inPool === !1) {
4374
- const v = this.blobs.get(d);
4375
- v && (this.injector?.releaseBlobUrl?.(v), URL.revokeObjectURL(v), this.blobs.delete(d), this.pendingUpdates.delete(d));
4374
+ const w = this.blobs.get(d);
4375
+ w && (this.injector?.releaseBlobUrl?.(w), URL.revokeObjectURL(w), this.blobs.delete(d), this.pendingUpdates.delete(d));
4376
4376
  }
4377
4377
  if (this.pool.has(d)) {
4378
- const v = this.pool.get(d);
4378
+ const w = this.pool.get(d);
4379
4379
  if (!this.blobs.has(d))
4380
- await v.destroy(), this.pool.delete(d), this.pendingUpdates.delete(d);
4380
+ await w.destroy(), this.pool.delete(d), this.pendingUpdates.delete(d);
4381
4381
  else {
4382
- await v.load(i);
4382
+ await w.load(i);
4383
4383
  return;
4384
4384
  }
4385
4385
  }
@@ -4536,8 +4536,8 @@ function cr() {
4536
4536
  } else c > y && (r.charCodeAt(a + p) === 47 ? d = p : p === 0 && (d = 0));
4537
4537
  break;
4538
4538
  }
4539
- var b = r.charCodeAt(a + p), v = o.charCodeAt(h + p);
4540
- if (b !== v)
4539
+ var b = r.charCodeAt(a + p), w = o.charCodeAt(h + p);
4540
+ if (b !== w)
4541
4541
  break;
4542
4542
  b === 47 && (d = p);
4543
4543
  }
@@ -5300,7 +5300,7 @@ class tn {
5300
5300
  }
5301
5301
  }
5302
5302
  }
5303
- const mt = (s) => s.replace(/\/\/.*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\n/g, "").replace(/\s+/g, " "), Mt = (s) => s.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, "").replace(/ {2,}/g, " "), vr = `/*!
5303
+ const mt = (s) => s.replace(/\/\/.*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\n/g, "").replace(/\s+/g, " "), Mt = (s) => s.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, "").replace(/ {2,}/g, " "), wr = `/*!
5304
5304
  * Readium CSS v.2.0.0
5305
5305
  * Copyright (c) 2017–2026. Readium Foundation. All rights reserved.
5306
5306
  * Use of this source code is governed by a BSD-style license which is detailed in the
@@ -5574,7 +5574,7 @@ const mt = (s) => s.replace(/\/\/.*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").repl
5574
5574
 
5575
5575
  :root[style*="readium-iPadOSPatch-on"] p:not(:has(b, cite, em, i, q, s, small, span, strong)):first-line{
5576
5576
  -webkit-text-zoom:normal;
5577
- }`, en = '!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})()));', wr = `// WebPub-specific setup - no execution blocking needed
5577
+ }`, en = '!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})()));', vr = `// WebPub-specific setup - no execution blocking needed
5578
5578
  window._readium_blockedEvents = [];
5579
5579
  window._readium_blockEvents = false; // WebPub doesn't need event blocking
5580
5580
  window._readium_eventBlocker = null;
@@ -5606,7 +5606,7 @@ function _r(s) {
5606
5606
  id: "webpub-execution",
5607
5607
  as: "script",
5608
5608
  target: "head",
5609
- blob: new Blob([mt(wr)], { type: "text/javascript" })
5609
+ blob: new Blob([mt(vr)], { type: "text/javascript" })
5610
5610
  }
5611
5611
  ], n = [
5612
5612
  // Onload Proxy - conditional (has executable scripts)
@@ -5622,7 +5622,7 @@ function _r(s) {
5622
5622
  id: "readium-css-webpub",
5623
5623
  as: "link",
5624
5624
  target: "head",
5625
- blob: new Blob([Mt(vr)], { type: "text/css" }),
5625
+ blob: new Blob([Mt(wr)], { type: "text/css" }),
5626
5626
  rel: "stylesheet"
5627
5627
  }
5628
5628
  ];
@@ -6171,7 +6171,7 @@ class Ur extends Gi {
6171
6171
  }), !1, () => {
6172
6172
  });
6173
6173
  else if (a.startsWith("mailto:") || a.startsWith("tel:"))
6174
- this.listeners.handleLocator(new V({
6174
+ this.listeners.handleLocator(new B({
6175
6175
  href: a
6176
6176
  }).locator);
6177
6177
  else
@@ -6186,11 +6186,11 @@ class Ur extends Gi {
6186
6186
  l = Vt.join(Vt.dirname(this.currentLocation.href), a);
6187
6187
  const c = this.pub.readingOrder.findWithHref(l);
6188
6188
  c ? this.goLink(c, !1, () => {
6189
- }) : (console.warn(`Internal link not found in readingOrder: ${l}`), this.listeners.handleLocator(new V({
6189
+ }) : (console.warn(`Internal link not found in readingOrder: ${l}`), this.listeners.handleLocator(new B({
6190
6190
  href: a
6191
6191
  }).locator));
6192
6192
  } catch (l) {
6193
- console.warn(`Couldn't resolve internal link for ${a}: ${l}`), this.listeners.handleLocator(new V({
6193
+ console.warn(`Couldn't resolve internal link for ${a}: ${l}`), this.listeners.handleLocator(new B({
6194
6194
  href: a
6195
6195
  }).locator);
6196
6196
  }
@@ -6393,37 +6393,43 @@ class on {
6393
6393
  this.pub = t, this.baseURL = e, this.item = i, this.injector = null, this.item = i, this.cssProperties = n.cssProperties, this.injector = n.injector ?? null;
6394
6394
  }
6395
6395
  async build(t = !1) {
6396
- if (this.item.mediaType.isHTML)
6396
+ const e = await this.pub.get(this.item).link();
6397
+ if (e.mediaType.isHTML)
6397
6398
  return await this.buildHtmlFrame(t);
6398
- if (this.item.mediaType.isBitmap || this.item.mediaType.equals(g.SVG))
6399
+ if (e.mediaType.isBitmap || e.mediaType.equals(g.SVG))
6399
6400
  return await this.buildImageFrame();
6400
- throw Error("Unsupported frame mediatype " + this.item.mediaType.string);
6401
+ throw Error("Unsupported frame mediatype " + e.mediaType.string);
6401
6402
  }
6402
6403
  async buildHtmlFrame(t = !1) {
6403
- const e = await this.pub.get(this.item).readAsString();
6404
- if (!e) throw new Error(`Failed reading item ${this.item.href}`);
6405
- const i = new DOMParser().parseFromString(
6406
- e,
6407
- this.item.mediaType.string
6408
- ), n = i.querySelector("parsererror");
6409
- if (n) {
6410
- const r = n.querySelector("div");
6411
- throw new Error(`Failed parsing item ${this.item.href}: ${r?.textContent || n.textContent}`);
6404
+ const e = this.pub.get(this.item), i = await e.link(), n = await e.readAsString();
6405
+ if (!n) throw new Error(`Failed reading item ${i.href}`);
6406
+ const r = new DOMParser().parseFromString(
6407
+ n,
6408
+ i.mediaType.string
6409
+ ), o = r.querySelector("parsererror");
6410
+ if (o) {
6411
+ const a = o.querySelector("div");
6412
+ throw new Error(`Failed parsing item ${i.href}: ${a?.textContent || o.textContent}`);
6412
6413
  }
6413
- return this.injector && await this.injector.injectForDocument(i, this.item), this.finalizeDOM(i, this.pub.baseURL, (await this.pub.get(this.item).link()).toURL(this.baseURL) || "", this.item.mediaType, t, this.cssProperties);
6414
+ return this.injector && await this.injector.injectForDocument(r, i), this.finalizeDOM(r, this.pub.baseURL, i.toURL(this.baseURL) || "", i.mediaType, t, this.cssProperties);
6414
6415
  }
6415
6416
  async buildImageFrame() {
6416
- const t = await this.pub.get(this.item).link(), e = t.toURL(this.baseURL) || "", i = document.implementation.createHTMLDocument(this.item.title || this.item.href);
6417
+ const t = await this.pub.get(this.item).link(), e = t.toURL(this.baseURL) || "", i = document.implementation.createHTMLDocument(t.title || t.href);
6417
6418
  if ((t?.height || 0) > 0 && (t?.width || 0) > 0) {
6418
6419
  const o = i.createElement("meta");
6419
6420
  o.name = "viewport", o.content = `width=${t.width}, height=${t.height}`, o.dataset.readium = "true", i.head.appendChild(o);
6420
6421
  }
6421
6422
  const n = document.createElement("img");
6422
- n.src = e || "", n.alt = this.item.title || "", n.decoding = "async", i.body.appendChild(n), this.injector && await this.injector.injectForDocument(i, this.item);
6423
+ n.src = e || "", n.alt = t.title || "", n.decoding = "async", i.body.appendChild(n), this.injector && await this.injector.injectForDocument(i, new B({
6424
+ // Temporary solution to address injector only expecting (X)HTML
6425
+ // documents for injection, which we are technically providing
6426
+ href: "readium-image-frame.xhtml",
6427
+ type: g.XHTML.string
6428
+ }));
6423
6429
  const r = i.createElement("style");
6424
6430
  return r.dataset.readium = "true", r.textContent = `
6425
6431
  html, body { width: 100%; height: 100%; margin: 0; padding: 0; font-size: 0; }
6426
- img { margin: 0; padding: 0; border: 0; }`, i.head.appendChild(r), this.finalizeDOM(i, this.pub.baseURL, e, this.item.mediaType, !0);
6432
+ img { margin: 0; padding: 0; border: 0; }`, i.head.appendChild(r), this.finalizeDOM(i, this.pub.baseURL, e, t.mediaType, !0);
6427
6433
  }
6428
6434
  setProperties(t, e) {
6429
6435
  for (const i in t) {
@@ -6558,7 +6564,7 @@ class Fr {
6558
6564
  return this.loader;
6559
6565
  }
6560
6566
  }
6561
- const vi = 5, wi = 3;
6567
+ const wi = 5, vi = 3;
6562
6568
  class Dr {
6563
6569
  constructor(t, e, i, n, r, o) {
6564
6570
  this.pool = /* @__PURE__ */ new Map(), this.blobs = /* @__PURE__ */ new Map(), this.inprogress = /* @__PURE__ */ new Map(), this.pendingUpdates = /* @__PURE__ */ new Map(), this.injector = null, this.container = t, this.positions = e, this.currentCssProperties = i, this.injector = n ?? null, this.contentProtectionConfig = r || {}, this.keyboardPeripheralsConfig = o || [];
@@ -6586,25 +6592,25 @@ class Dr {
6586
6592
  const a = new Promise(async (l, c) => {
6587
6593
  const h = [], u = [];
6588
6594
  this.positions.forEach((d, p) => {
6589
- (p > r + vi || p < r - vi) && (h.includes(d.href) || h.push(d.href)), p < r + wi && p > r - wi && (u.includes(d.href) || u.push(d.href));
6595
+ (p > r + wi || p < r - wi) && (h.includes(d.href) || h.push(d.href)), p < r + vi && p > r - vi && (u.includes(d.href) || u.push(d.href));
6590
6596
  }), h.forEach(async (d) => {
6591
6597
  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 }));
6592
6598
  }), this.currentBaseURL !== void 0 && t.baseURL !== this.currentBaseURL && (this.blobs.forEach((d) => {
6593
6599
  this.injector?.releaseBlobUrl?.(d), URL.revokeObjectURL(d);
6594
6600
  }), this.blobs.clear()), this.currentBaseURL = t.baseURL;
6595
6601
  const m = async (d) => {
6596
- if (n && (this.blobs.forEach((v) => {
6597
- this.injector?.releaseBlobUrl?.(v), URL.revokeObjectURL(v);
6602
+ if (n && (this.blobs.forEach((w) => {
6603
+ this.injector?.releaseBlobUrl?.(w), URL.revokeObjectURL(w);
6598
6604
  }), this.blobs.clear(), this.pendingUpdates.clear()), this.pendingUpdates.has(d) && this.pendingUpdates.get(d)?.inPool === !1) {
6599
- const v = this.blobs.get(d);
6600
- v && (this.injector?.releaseBlobUrl?.(v), URL.revokeObjectURL(v), this.blobs.delete(d), this.pendingUpdates.delete(d));
6605
+ const w = this.blobs.get(d);
6606
+ w && (this.injector?.releaseBlobUrl?.(w), URL.revokeObjectURL(w), this.blobs.delete(d), this.pendingUpdates.delete(d));
6601
6607
  }
6602
6608
  if (this.pool.has(d)) {
6603
- const v = this.pool.get(d);
6609
+ const w = this.pool.get(d);
6604
6610
  if (!this.blobs.has(d))
6605
- await v.destroy(), this.pool.delete(d), this.pendingUpdates.delete(d);
6611
+ await w.destroy(), this.pool.delete(d), this.pendingUpdates.delete(d);
6606
6612
  else {
6607
- await v.load(i);
6613
+ await w.load(i);
6608
6614
  return;
6609
6615
  }
6610
6616
  }
@@ -7412,12 +7418,12 @@ class Zr {
7412
7418
  ).build(!0);
7413
7419
  this.blobs.set(d, L);
7414
7420
  }
7415
- this.delayedShow.has(d) || this.delayedShow.set(d, new Promise((v, L) => {
7421
+ this.delayedShow.has(d) || this.delayedShow.set(d, new Promise((w, L) => {
7416
7422
  let Q = !1;
7417
7423
  const hn = window.setTimeout(async () => {
7418
7424
  this.delayedTimeout.set(d, 0);
7419
7425
  const cn = this.makeSpread(this.reAlign(p)), dn = this.spreadPosition(cn, b), Fe = this.pool.get(d);
7420
- await Fe.load(i, this.blobs.get(d)), this.peripherals.isScaled || await Fe.show(dn), this.delayedShow.delete(d), Q = !0, v();
7426
+ await Fe.load(i, this.blobs.get(d)), this.peripherals.isScaled || await Fe.show(dn), this.delayedShow.delete(d), Q = !0, w();
7421
7427
  }, $r);
7422
7428
  setTimeout(() => {
7423
7429
  !Q && this.delayedShow.has(d) && L(`Offscreen load timeout: ${d}`);
@@ -9637,17 +9643,17 @@ class ln extends Gi {
9637
9643
  }), !1, () => {
9638
9644
  });
9639
9645
  else if (a.startsWith("http://") || a.startsWith("https://") || a.startsWith("mailto:") || a.startsWith("tel:"))
9640
- this.listeners.handleLocator(new V({
9646
+ this.listeners.handleLocator(new B({
9641
9647
  href: a
9642
9648
  }).locator);
9643
9649
  else
9644
9650
  try {
9645
- this.goLink(new V({
9651
+ this.goLink(new B({
9646
9652
  href: Vt.join(Vt.dirname(this.currentLocation.href), a)
9647
9653
  }), !1, () => {
9648
9654
  });
9649
9655
  } catch (l) {
9650
- console.warn(`Couldn't go to link for ${a}: ${l}`), this.listeners.handleLocator(new V({
9656
+ console.warn(`Couldn't go to link for ${a}: ${l}`), this.listeners.handleLocator(new B({
9651
9657
  href: a
9652
9658
  }).locator);
9653
9659
  }
@@ -55,7 +55,7 @@
55
55
  body::-webkit-scrollbar {
56
56
  display: none; /* for Chrome, Safari, and Opera */
57
57
  }
58
- `,e.document.head.appendChild(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",D.moduleName,()=>{Oi(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",D.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(),z(this.wnd),r(!0)})}),t.register("go_id",D.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(),z(this.wnd),r(!0)})}),t.register("go_text",D.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=re.deserialize(n),l=Ye(this.wnd.document,new B({href:e.location.href,type:"text/html",text:a,locations:s?new A({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(),z(this.wnd),r(!0)})}),t.register("go_start",D.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",D.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",D.moduleName,(n,r)=>{z(this.wnd),r(!0)}),t.register("scroll_protection",D.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],D.moduleName,(n,r)=>r(!1)),t.register("focus",D.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",D.moduleName,(n,r)=>{const s=Et(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Fi)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};D.moduleName="scroll_snapper";let Rt=D;const W=class W extends ke{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 kt(Mi),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",W.moduleName,()=>{Oi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,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(),z(this.wnd),n(!0)})}),t.register("go_id",W.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(),z(this.wnd),n(!0)})}),t.register("go_text",W.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=re.deserialize(i),a=Ye(this.wnd.document,new B({href:e.location.href,type:"text/html",text:s,locations:r?new A({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(),z(this.wnd),n(!0)})}),t.register("go_start",W.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",W.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",W.moduleName,(i,n)=>{z(this.wnd),n(!0)}),t.register("scroll_protection",W.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,n)=>n(!1)),t.register("focus",W.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",W.moduleName,(i,n)=>{const r=Et(e,!0);t.send("first_visible_locator",r.serialize()),n(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.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}};W.moduleName="webpub_snapper";let Lt=W;class fr{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,h=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),c=this.isSuspiciousPattern(s),u=n>h||l||c;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 yr{constructor(e=Ni){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 Ii{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()||"",h=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&a&&(r={text:a,x:h.x,y:h.y,width:h.width,height:h.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 h=s.type,c=this.createActivityEvent(l,h,e,n);i(c)}})))}),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 we=class we extends ue{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 Ii,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=mr,i=e?{...t,...e}:t;this.bulkCopyProtector=new fr(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||Ni;this.selectionAnalyzer=new yr(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:Ti(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",we.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",we.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(we.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};we.moduleName="peripherals";let At=we;const He=class He extends ue{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-alpha.1",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",He.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",He.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}};He.moduleName="setup";let Qe=He;const Di="readium-viewport",Q=class Q extends Qe{onViewportWidthChanged(e){const t=e.target;Ce(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",Di),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",Q.moduleName,(n,r)=>{bt(e),r(!0)}),t.register("update_properties",Q.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,wi(e,n),r(!0)}),t.register("set_property",Q.moduleName,(n,r)=>{const s=n;Ce(e,s[0],s[1]),r(!0)}),t.register("remove_property",Q.moduleName,(n,r)=>{Ke(e,n),r(!0)}),t.register("activate",Q.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(Q.moduleName),e.document.head.querySelector(`#${Di}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};Q.moduleName="reflowable_setup";let Ot=Q;const Wi="readium-fixed-style",J=class J extends Qe{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=Wi,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",D.moduleName,()=>{Oi(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",D.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(),z(this.wnd),r(!0)})}),t.register("go_id",D.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(),z(this.wnd),r(!0)})}),t.register("go_text",D.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const a=re.deserialize(n),l=Ye(this.wnd.document,new B({href:e.location.href,type:"text/html",text:a,locations:s?new A({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(),z(this.wnd),r(!0)})}),t.register("go_start",D.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),t.register("go_end",D.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",D.moduleName,(n,r)=>{z(this.wnd),r(!0)}),t.register("scroll_protection",D.moduleName,(n,r)=>{this.enableScrollProtection(),r(!0)}),t.register(["go_next","go_prev"],D.moduleName,(n,r)=>r(!1)),t.register("focus",D.moduleName,(n,r)=>{this.reportProgress(),r(!0)}),t.register("first_visible_locator",D.moduleName,(n,r)=>{const s=Et(e,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(D.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&e.removeEventListener("scroll",this.handleScroll),e.document.getElementById(Fi)?.remove(),this.patternAnalyzer&&(this.patternAnalyzer.clear(),this.patternAnalyzer=null,this.isScrollProtectionEnabled=!1),t.log("ScrollSnapper Unmounted"),!0}};D.moduleName="scroll_snapper";let Rt=D;const W=class W extends ke{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 kt(Mi),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",W.moduleName,()=>{Oi(this.wnd);const i=this.doc().scrollTop;i>1?this.doc().scrollTop=i-1:this.doc().scrollTop=i+1,this.doc().scrollTop=i}),t.register("go_progression",W.moduleName,(i,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(),z(this.wnd),n(!0)})}),t.register("go_id",W.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(),z(this.wnd),n(!0)})}),t.register("go_text",W.moduleName,(i,n)=>{let r;Array.isArray(i)&&(i.length>1&&(r=i[1]),i=i[0]);const s=re.deserialize(i),a=Ye(this.wnd.document,new B({href:e.location.href,type:"text/html",text:s,locations:r?new A({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(),z(this.wnd),n(!0)})}),t.register("go_start",W.moduleName,(i,n)=>{if(this.doc().scrollTop===0)return n(!1);this.doc().scrollTop=0,this.reportProgress(),n(!0)}),t.register("go_end",W.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",W.moduleName,(i,n)=>{z(this.wnd),n(!0)}),t.register("scroll_protection",W.moduleName,(i,n)=>{this.enableScrollProtection(),n(!0)}),t.register(["go_next","go_prev"],W.moduleName,(i,n)=>n(!1)),t.register("focus",W.moduleName,(i,n)=>{this.reportProgress(),n(!0)}),t.register("first_visible_locator",W.moduleName,(i,n)=>{const r=Et(e,!0);t.send("first_visible_locator",r.serialize()),n(!0)}),t.log("WebPubSnapper Mounted"),!0}unmount(e,t){return t.unregisterAll(W.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}};W.moduleName="webpub_snapper";let Lt=W;class fr{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,h=Math.min(r*this.options.maxSelectionPercent,this.options.absoluteMaxChars),c=this.isSuspiciousPattern(s),u=n>h||l||c;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 yr{constructor(e=Ni){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 Ii{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()||"",h=(a&&s?.rangeCount?s.getRangeAt(0)?.getClientRects():null)?.[0];h&&a&&(r={text:a,x:h.x,y:h.y,width:h.width,height:h.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 h=s.type,c=this.createActivityEvent(l,h,e,n);i(c)}})))}),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 we=class we extends ue{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 Ii,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=mr,i=e?{...t,...e}:t;this.bulkCopyProtector=new fr(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||Ni;this.selectionAnalyzer=new yr(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:Ti(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",we.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",we.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(we.moduleName),this.configApplied=!1,t.log("Peripherals Unmounted"),!0}};we.moduleName="peripherals";let At=we;const He=class He extends ue{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-alpha.2",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",He.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",He.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}};He.moduleName="setup";let Qe=He;const Di="readium-viewport",Q=class Q extends Qe{onViewportWidthChanged(e){const t=e.target;Ce(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",Di),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",Q.moduleName,(n,r)=>{bt(e),r(!0)}),t.register("update_properties",Q.moduleName,(n,r)=>{n["--RS__viewportWidth"]=`${e.innerWidth}px`,wi(e,n),r(!0)}),t.register("set_property",Q.moduleName,(n,r)=>{const s=n;Ce(e,s[0],s[1]),r(!0)}),t.register("remove_property",Q.moduleName,(n,r)=>{Ke(e,n),r(!0)}),t.register("activate",Q.moduleName,(n,r)=>{this.unblock(e),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(e,t){return t.unregisterAll(Q.moduleName),e.document.head.querySelector(`#${Di}`)?.remove(),e.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(e,t)}};Q.moduleName="reflowable_setup";let Ot=Q;const Wi="readium-fixed-style",J=class J extends Qe{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=Wi,i.dataset.readium="true",i.textContent=`
59
59
  html, body {
60
60
  text-size-adjust: none;
61
61
  -ms-text-size-adjust: none;
@@ -398,9 +398,9 @@ onmessage = function(event) {
398
398
  transform: translateY(-50%);
399
399
  }
400
400
  }
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 Gr{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const Fe="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Fe,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new Br({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new Nr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new Vr({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new jr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new Gr({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const Ie="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ii,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ie,{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 Xr=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 dn extends Mt{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=Xr(i),this._preferences=new be(r.preferences),this._defaults=new en(r.defaults),this._settings=new It(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ut({zoom:this._settings.zoom})});const s=Mr(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new Ht({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 cn(this._contentProtection),this._suspiciousActivityListener=l=>{const h=l;this.listeners.contentProtection(h.detail.type,h.detail)},window.addEventListener(Fe,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const h=l.detail;this.listeners.peripheral(h)},window.addEventListener(Ie,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 Yi(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 Wt(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 It(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Wt(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===Be.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=B.deserialize(t);if(!i)break;this.currentLocation=new B({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 V({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 c=new URL(this.currentLocation.href);l=new URL(a,c).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const h=this.pub.readingOrder.findWithHref(l);h?this.goLink(h,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new V({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new V({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(et.keys()).filter(t=>_r.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(Fe,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ie,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,h)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),c=>l(c))}):n&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],c=>l(c))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_id",r,c=>l(c))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>l(c))}):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 B({href:t.href,type:t.type||"text/html",locations:new A({fragments:[],progression:n,position:this.currentIndex+1})})}}const $r=dn,Yr=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 un{constructor(e,t,i,n){this.pub=e,this.baseURL=t,this.item=i,this.injector=null,this.item=i,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 await 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,(await this.pub.get(this.item).link()).toURL(this.baseURL)||"",this.item.mediaType,e,this.cssProperties)}async buildImageFrame(){const e=await this.pub.get(this.item).link(),t=e.toURL(this.baseURL)||"",i=document.implementation.createHTMLDocument(this.item.title||this.item.href);if((e?.height||0)>0&&(e?.width||0)>0){const s=i.createElement("meta");s.name="viewport",s.content=`width=${e.width}, height=${e.height}`,s.dataset.readium="true",i.head.appendChild(s)}const n=document.createElement("img");n.src=t||"",n.alt=this.item.title||"",n.decoding="async",i.body.appendChild(n),this.injector&&await this.injector.injectForDocument(i,this.item);const r=i.createElement("style");return r.dataset.readium="true",r.textContent=`
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 Gr{constructor(e={}){this.onContextMenuBlocked=e.onContextMenuBlocked,this.contextMenuHandler=this.handleContextMenu.bind(this),document.addEventListener("contextmenu",this.contextMenuHandler,!0),window.addEventListener("unload",()=>this.destroy())}handleContextMenu(e){e.preventDefault(),e.stopPropagation();const t={type:"context_menu",timestamp:Date.now(),clientX:e.clientX,clientY:e.clientY,targetFrameSrc:""};return this.onContextMenuBlocked&&this.onContextMenuBlocked(t),!1}destroy(){this.contextMenuHandler&&(document.removeEventListener("contextmenu",this.contextMenuHandler,!0),this.contextMenuHandler=void 0)}}const Fe="readium:navigator:suspiciousActivity";class cn{dispatchSuspiciousActivity(e,t){const i=new CustomEvent(Fe,{detail:{type:e,timestamp:Date.now(),...t}});window.dispatchEvent(i)}constructor(e={}){e.monitorDevTools&&(this.devToolsDetector=new Br({onDetected:()=>{this.dispatchSuspiciousActivity("developer_tools",{targetFrameSrc:"",key:"",code:"",keyCode:-1,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1})}})),e.checkAutomation&&(this.automationDetector=new Nr({onDetected:t=>{this.dispatchSuspiciousActivity("automation_detected",{tool:t})}})),e.checkIFrameEmbedding&&(this.iframeEmbeddingDetector=new Vr({onDetected:t=>{this.dispatchSuspiciousActivity("iframe_embedding_detected",{isCrossOrigin:t})}})),e.protectPrinting?.disable&&(this.printProtector=new jr({...e.protectPrinting,onPrintAttempt:()=>{this.dispatchSuspiciousActivity("print",{})}})),e.disableContextMenu&&(this.contextMenuProtector=new Gr({onContextMenuBlocked:t=>{this.dispatchSuspiciousActivity("context_menu",t)}}))}destroy(){this.automationDetector?.destroy(),this.devToolsDetector?.destroy(),this.iframeEmbeddingDetector?.destroy(),this.printProtector?.destroy(),this.contextMenuProtector?.destroy()}}const Ie="readium:navigator:keyboardPeripheral";class hn{constructor(e={}){this.keyManager=new Ii,this.setupKeyboardPeripherals(e.keyboardPeripherals||[])}setupKeyboardPeripherals(e){if(e.length>0){const t=i=>{const n=new CustomEvent(Ie,{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 Xr=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 dn extends Mt{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=Xr(i),this._preferences=new be(r.preferences),this._defaults=new en(r.defaults),this._settings=new It(this._preferences,this._defaults,this.hasDisplayTransformability),this._css=new Ji({rsProperties:new Ki({experiments:this._settings.experiments||null}),userProperties:new Ut({zoom:this._settings.zoom})});const s=Mr(t.readingOrder.items),a=r.injectables||{rules:[],allowedDomains:[]};if(this._injector=new Ht({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 cn(this._contentProtection),this._suspiciousActivityListener=l=>{const h=l;this.listeners.contentProtection(h.detail.type,h.detail)},window.addEventListener(Fe,this._suspiciousActivityListener)),this._keyboardPeripherals.length>0&&(this._keyboardPeripheralsManager=new hn({keyboardPeripherals:this._keyboardPeripherals}),this._keyboardPeripheralListener=l=>{const h=l.detail;this.listeners.peripheral(h)},window.addEventListener(Ie,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 Yi(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 Wt(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 It(this._preferences,this._defaults,this.hasDisplayTransformability),this._preferencesEditor!==null&&(this._preferencesEditor=new Wt(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===Be.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=B.deserialize(t);if(!i)break;this.currentLocation=new B({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 V({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 c=new URL(this.currentLocation.href);l=new URL(a,c).href}else l=tt.join(tt.dirname(this.currentLocation.href),a);const h=this.pub.readingOrder.findWithHref(l);h?this.goLink(h,!1,()=>{}):(console.warn(`Internal link not found in readingOrder: ${l}`),this.listeners.handleLocator(new V({href:a}).locator))}catch(l){console.warn(`Couldn't resolve internal link for ${a}: ${l}`),this.listeners.handleLocator(new V({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(et.keys()).filter(t=>_r.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(Fe,this._suspiciousActivityListener),this._keyboardPeripheralListener&&window.removeEventListener(Ie,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,h)=>{this.framePool.currentFrames[0].msg.send("go_text",n?[e.text?.serialize(),n]:e.text?.serialize(),c=>l(c))}):n&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_text",["",n],c=>l(c))})),i){t(i);return}const r=typeof e.locations.htmlId=="function"&&e.locations.htmlId();if(r&&(i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_id",r,c=>l(c))})),i){t(i);return}const s=e?.locations?.progression;s&&s>0?i=await new Promise((l,h)=>{this.framePool.currentFrames[0].msg.send("go_progression",s,c=>l(c))}):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 B({href:t.href,type:t.type||"text/html",locations:new A({fragments:[],progression:n,position:this.currentIndex+1})})}}const $r=dn,Yr=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 un{constructor(e,t,i,n){this.pub=e,this.baseURL=t,this.item=i,this.injector=null,this.item=i,this.cssProperties=n.cssProperties,this.injector=n.injector??null}async build(e=!1){const t=await this.pub.get(this.item).link();if(t.mediaType.isHTML)return await this.buildHtmlFrame(e);if(t.mediaType.isBitmap||t.mediaType.equals(g.SVG))return await this.buildImageFrame();throw Error("Unsupported frame mediatype "+t.mediaType.string)}async buildHtmlFrame(e=!1){const t=this.pub.get(this.item),i=await t.link(),n=await t.readAsString();if(!n)throw new Error(`Failed reading item ${i.href}`);const r=new DOMParser().parseFromString(n,i.mediaType.string),s=r.querySelector("parsererror");if(s){const a=s.querySelector("div");throw new Error(`Failed parsing item ${i.href}: ${a?.textContent||s.textContent}`)}return this.injector&&await this.injector.injectForDocument(r,i),this.finalizeDOM(r,this.pub.baseURL,i.toURL(this.baseURL)||"",i.mediaType,e,this.cssProperties)}async buildImageFrame(){const e=await this.pub.get(this.item).link(),t=e.toURL(this.baseURL)||"",i=document.implementation.createHTMLDocument(e.title||e.href);if((e?.height||0)>0&&(e?.width||0)>0){const s=i.createElement("meta");s.name="viewport",s.content=`width=${e.width}, height=${e.height}`,s.dataset.readium="true",i.head.appendChild(s)}const n=document.createElement("img");n.src=t||"",n.alt=e.title||"",n.decoding="async",i.body.appendChild(n),this.injector&&await this.injector.injectForDocument(i,new V({href:"readium-image-frame.xhtml",type:g.XHTML.string}));const r=i.createElement("style");return r.dataset.readium="true",r.textContent=`
402
402
  html, body { width: 100%; height: 100%; margin: 0; padding: 0; font-size: 0; }
403
- img { margin: 0; padding: 0; border: 0; }`,i.head.appendChild(r),this.finalizeDOM(i,this.pub.baseURL,t,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?.()||[];t=t?.split("?")[0];const l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(c=>{c.setAttribute("fetchpriority","high"),c.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const c=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=c,document.documentElement.setAttribute("xml:lang",c))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=c)}if(i!==void 0){const c=e.createElement("base");c.href=i,c.dataset.readium="true",e.head.firstChild.before(c)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Yr(l),h.dataset.readium="true",e.head.firstChild.before(h),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 ge(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 ge(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&&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 fe(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,$.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 fe(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 mn=5,gn=3;class fn{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,h)=>h.locations.position||0>l?h.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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(c.includes(d.href)||c.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),c.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(_=>{this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const _=this.blobs.get(d);_&&(this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const _=this.pool.get(d);if(!this.blobs.has(d))await _.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await _.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const O=await new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,O)}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){h(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 yn{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 ge(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 ge(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===G.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===G.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&&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 fe(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 bn=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(bn||{}),vn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(vn||{});class Sn{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){$.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,$.OS.Android&&$.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 h={X:null,Y:null};return n.X<a?h.X=0:l<n.X?h.X=2:h.X=1,n.Y<r?h.Y=0:s<n.Y?h.Y=2:h.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:h}}}class qr{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 _n=6,Vt=1.02,wn=50;class Pn{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 Sn,this.attachEvents(),t&&(this.debugger=new qr)}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<Vt&&(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)>wn&&Math.abs(this.pan.overscrollY)<wn/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<Vt&&(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>=_n&&(s=_n),s<=Vt&&(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 h=-l.X/r;h+=l.X/this.scale,this.pinch.target.X+=h,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-l.Y/r;c+=l.Y/this.scale,this.pinch.target.Y+=c,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)}
403
+ img { margin: 0; padding: 0; border: 0; }`,i.head.appendChild(r),this.finalizeDOM(i,this.pub.baseURL,t,e.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?.()||[];t=t?.split("?")[0];const l=[...new Set([...t?[t]:[],...a])].filter(Boolean);if(s&&!r&&this.setProperties(s,e),e.body.querySelectorAll("img").forEach(c=>{c.setAttribute("fetchpriority","high"),c.setAttribute("referrerpolicy","origin")}),n.isHTML&&this.pub.metadata.languages?.[0]){const c=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=c,document.documentElement.setAttribute("xml:lang",c))}else n===g.HTML&&!document.documentElement.lang&&(document.documentElement.lang=c)}if(i!==void 0){const c=e.createElement("base");c.href=i,c.dataset.readium="true",e.head.firstChild.before(c)}const h=e.createElement("meta");return h.httpEquiv="Content-Security-Policy",h.content=Yr(l),h.dataset.readium="true",e.head.firstChild.before(h),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 ge(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 ge(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&&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 fe(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,$.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 fe(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 mn=5,gn=3;class fn{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,h)=>h.locations.position||0>l?h.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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+mn||p<r-mn)&&(c.includes(d.href)||c.push(d.href)),p<r+gn&&p>r-gn&&(u.includes(d.href)||u.push(d.href))}),c.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(_=>{this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_)}),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(d)&&this.pendingUpdates.get(d)?.inPool===!1){const _=this.blobs.get(d);_&&(this.injector?.releaseBlobUrl?.(_),URL.revokeObjectURL(_),this.blobs.delete(d),this.pendingUpdates.delete(d))}if(this.pool.has(d)){const _=this.pool.get(d);if(!this.blobs.has(d))await _.destroy(),this.pool.delete(d),this.pendingUpdates.delete(d);else{await _.load(i);return}}const p=e.readingOrder.findWithHref(d);if(!p)return;if(!this.blobs.has(d)){const O=await new un(e,this.currentBaseURL||"",p,{cssProperties:this.currentCssProperties,injector:this.injector}).build();this.blobs.set(d,O)}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){h(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 yn{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 ge(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 ge(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===G.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(e===G.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&&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 fe(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 bn=(o=>(o[o.Left=0]="Left",o[o.Center=1]="Center",o[o.Right=2]="Right",o))(bn||{}),vn=(o=>(o[o.Top=0]="Top",o[o.Middle=1]="Middle",o[o.Bottom=2]="Bottom",o))(vn||{});class Sn{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(e){$.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,$.OS.Android&&$.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 h={X:null,Y:null};return n.X<a?h.X=0:l<n.X?h.X=2:h.X=1,n.Y<r?h.Y=0:s<n.Y?h.Y=2:h.Y=1,{Target:e.target,Coord:t,Ratio:n,Division:h}}}class qr{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 _n=6,Vt=1.02,wn=50;class Pn{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 Sn,this.attachEvents(),t&&(this.debugger=new qr)}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<Vt&&(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)>wn&&Math.abs(this.pan.overscrollY)<wn/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<Vt&&(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>=_n&&(s=_n),s<=Vt&&(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 h=-l.X/r;h+=l.X/this.scale,this.pinch.target.X+=h,l.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let c=-l.Y/r;c+=l.Y/this.scale,this.pinch.target.Y+=c,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)}
404
404
  TY: ${this.pan.translateY.toFixed(2)}
405
405
  Zoom: ${this.scale.toFixed(2)}
406
406
  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,h=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)*h}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 st=(o=>(o.auto="auto",o.landscape="landscape",o.portrait="portrait",o))(st||{}),at=(o=>(o.auto="auto",o.both="both",o.none="none",o.landscape="landscape",o))(at||{});class Cn{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===G.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===G.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 En=8,kn=5,Kr=300,Jr=15e3,Zr=250,Qr=150,eo=500;class xn{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||at.auto,this.pub.metadata.effectiveReadingProgression!==U.rtl&&this.pub.metadata.effectiveReadingProgression!==U.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Cn(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 Pn(this),this.pub.readingOrder.items.forEach(a=>{const l=new yn(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===st.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===st.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))})},Zr)}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===at.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?Qr:eo}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?G.center:t.href===e[0].href?this.rtl?G.right:G.left:this.rtl?G.left:G.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,h)=>{const c=[],u=[];this.positions.forEach((d,p)=>{(p>r+En||p<r-En)&&(c.includes(d.href)||c.push(d.href)),p<r+kn&&p>r-kn&&(u.includes(d.href)||u.push(d.href))}),c.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 O=await new un(e,this.currentBaseURL||"",S,{injector:this.injector}).build(!0);this.blobs.set(d,O)}this.delayedShow.has(d)||this.delayedShow.set(d,new Promise((_,O)=>{let ne=!1;const go=window.setTimeout(async()=>{this.delayedTimeout.set(d,0);const fo=this.makeSpread(this.reAlign(p)),yo=this.spreadPosition(fo,S),Fn=this.pool.get(d);await Fn.load(i,this.blobs.get(d)),this.peripherals.isScaled||await Fn.show(yo),this.delayedShow.delete(d),ne=!0,_()},Kr);setTimeout(()=>{!ne&&this.delayedShow.has(d)&&O(`Offscreen load timeout: ${d}`)},Jr),this.delayedTimeout.set(d,go)}))}};try{await Promise.all(u.map(d=>m(d)))}catch(d){h(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 Se{constructor(e={}){this.backgroundColor=N(e.backgroundColor),this.blendFilter=C(e.blendFilter),this.constraint=w(e.constraint),this.columnCount=w(e.columnCount),this.darkenFilter=le(e.darkenFilter),this.deprecatedFontSize=C(e.deprecatedFontSize),this.fontFamily=N(e.fontFamily),this.fontSize=Y(e.fontSize,xe.range),this.fontSizeNormalize=C(e.fontSizeNormalize),this.fontOpticalSizing=C(e.fontOpticalSizing),this.fontWeight=Y(e.fontWeight,Z.range),this.fontWidth=Y(e.fontWidth,Re.range),this.hyphens=C(e.hyphens),this.invertFilter=le(e.invertFilter),this.invertGaijiFilter=le(e.invertGaijiFilter),this.iOSPatch=C(e.iOSPatch),this.iPadOSPatch=C(e.iPadOSPatch),this.letterSpacing=w(e.letterSpacing),this.ligatures=C(e.ligatures),this.lineHeight=w(e.lineHeight),this.linkColor=N(e.linkColor),this.noRuby=C(e.noRuby),this.pageGutter=w(e.pageGutter),this.paragraphIndent=w(e.paragraphIndent),this.paragraphSpacing=w(e.paragraphSpacing),this.scroll=C(e.scroll),this.scrollPaddingTop=w(e.scrollPaddingTop),this.scrollPaddingBottom=w(e.scrollPaddingBottom),this.scrollPaddingLeft=w(e.scrollPaddingLeft),this.scrollPaddingRight=w(e.scrollPaddingRight),this.selectionBackgroundColor=N(e.selectionBackgroundColor),this.selectionTextColor=N(e.selectionTextColor),this.textAlign=Ue(e.textAlign,K),this.textColor=N(e.textColor),this.textNormalization=C(e.textNormalization),this.visitedColor=N(e.visitedColor),this.wordSpacing=w(e.wordSpacing),this.optimalLineLength=w(e.optimalLineLength),this.maximalLineLength=w(e.maximalLineLength),this.minimalLineLength=w(e.minimalLineLength)}static serialize(e){const{...t}=e;return JSON.stringify(t)}static deserialize(e){try{const t=JSON.parse(e);return new Se(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 Se(t)}}class Rn{constructor(e){this.backgroundColor=N(e.backgroundColor)||null,this.blendFilter=C(e.blendFilter)??!1,this.constraint=w(e.constraint)||0,this.columnCount=w(e.columnCount)||null,this.darkenFilter=le(e.darkenFilter)??!1,this.deprecatedFontSize=C(e.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=N(e.fontFamily)||null,this.fontSize=Y(e.fontSize,xe.range)||1,this.fontSizeNormalize=C(e.fontSizeNormalize)??!1,this.fontOpticalSizing=C(e.fontOpticalSizing)??null,this.fontWeight=Y(e.fontWeight,Z.range)||null,this.fontWidth=Y(e.fontWidth,Re.range)||null,this.hyphens=C(e.hyphens)??null,this.invertFilter=le(e.invertFilter)??!1,this.invertGaijiFilter=le(e.invertGaijiFilter)??!1,this.iOSPatch=e.iOSPatch===!1?!1:(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile",this.iPadOSPatch=e.iPadOSPatch===!1?!1:L.OS.iPadOS&&L.iOSRequest==="desktop",this.letterSpacing=w(e.letterSpacing)||null,this.ligatures=C(e.ligatures)??null,this.lineHeight=w(e.lineHeight)||null,this.linkColor=N(e.linkColor)||null,this.noRuby=C(e.noRuby)??!1,this.pageGutter=nt(w(e.pageGutter),20),this.paragraphIndent=w(e.paragraphIndent)??null,this.paragraphSpacing=w(e.paragraphSpacing)??null,this.scroll=C(e.scroll)??!1,this.scrollPaddingTop=w(e.scrollPaddingTop)??null,this.scrollPaddingBottom=w(e.scrollPaddingBottom)??null,this.scrollPaddingLeft=w(e.scrollPaddingLeft)??null,this.scrollPaddingRight=w(e.scrollPaddingRight)??null,this.selectionBackgroundColor=N(e.selectionBackgroundColor)||null,this.selectionTextColor=N(e.selectionTextColor)||null,this.textAlign=Ue(e.textAlign,K)||null,this.textColor=N(e.textColor)||null,this.textNormalization=C(e.textNormalization)??!1,this.visitedColor=N(e.visitedColor)||null,this.wordSpacing=w(e.wordSpacing)||null,this.optimalLineLength=w(e.optimalLineLength)||65,this.maximalLineLength=nt(Qi(e.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=nt(Zi(e.minimalLineLength,this.optimalLineLength),40),this.experiments=Ft(e.experiments)||null}}const _e={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 Se({optimalLineLength:65})}updatePreference(e,t){this.preferences[e]=t}get backgroundColor(){return new T({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||_e.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:e=>{this.updatePreference("backgroundColor",e||null)}})}get blendFilter(){return new M({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 R({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:se.range,step:se.step})}get deprecatedFontSize(){return new M({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 R({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("fontSize",e||null)},supportedRange:xe.range,step:xe.step})}get fontSizeNormalize(){return new M({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 M({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 R({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 R({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:Re.range,step:Re.step})}get hyphens(){return new M({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 R({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:se.range,step:se.step})}get invertGaijiFilter(){return new R({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:se.range,step:se.step})}get iOSPatch(){return new M({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 M({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 R({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:Le.range,step:Le.step})}get ligatures(){return new M({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 R({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:Ae.range,step:Ae.step})}get linkColor(){return new T({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||_e.RS__linkColor,isEffective:this.layout!==v.fixed&&this.preferences.linkColor!==null,onChange:e=>{this.updatePreference("linkColor",e||null)}})}get maximalLineLength(){return new R({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("maximalLineLength",e)},supportedRange:ae.range,step:ae.step})}get minimalLineLength(){return new R({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("minimalLineLength",e)},supportedRange:ae.range,step:ae.step})}get noRuby(){return new M({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 R({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout!==v.fixed,onChange:e=>{this.updatePreference("optimalLineLength",e)},supportedRange:ae.range,step:ae.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 R({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:Oe.range,step:Oe.step})}get paragraphSpacing(){return new R({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:Te.range,step:Te.step})}get scroll(){return new M({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||_e.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||_e.RS__selectionTextColor,isEffective:this.layout!==v.fixed&&this.preferences.selectionTextColor!==null,onChange:e=>{this.updatePreference("selectionTextColor",e||null)}})}get textAlign(){return new Dt({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||_e.RS__textColor,isEffective:this.layout!==v.fixed&&this.preferences.textColor!==null,onChange:e=>{this.updatePreference("textColor",e||null)}})}get textNormalization(){return new M({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||_e.RS__visitedColor,isEffective:this.layout!==v.fixed&&this.preferences.visitedColor!==null,onChange:e=>{this.updatePreference("visitedColor",e||null)}})}get wordSpacing(){return new R({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:ze.range,step:ze.step})}}class Gt{constructor(e,t){this.backgroundColor=e.backgroundColor||t.backgroundColor||null,this.blendFilter=typeof e.blendFilter=="boolean"?e.blendFilter:t.blendFilter??null,this.columnCount=e.columnCount!==void 0?e.columnCount:t.columnCount!==void 0?t.columnCount:null,this.constraint=e.constraint||t.constraint,this.darkenFilter=typeof e.darkenFilter=="boolean"?e.darkenFilter:t.darkenFilter??null,this.deprecatedFontSize=typeof e.deprecatedFontSize=="boolean"?e.deprecatedFontSize:t.deprecatedFontSize??null,this.fontFamily=e.fontFamily||t.fontFamily||null,this.fontSize=e.fontSize!==void 0?e.fontSize:t.fontSize!==void 0?t.fontSize:null,this.fontSizeNormalize=typeof e.fontSizeNormalize=="boolean"?e.fontSizeNormalize:t.fontSizeNormalize??null,this.fontOpticalSizing=typeof e.fontOpticalSizing=="boolean"?e.fontOpticalSizing:t.fontOpticalSizing??null,this.fontWeight=e.fontWeight!==void 0?e.fontWeight:t.fontWeight!==void 0?t.fontWeight:null,this.fontWidth=e.fontWidth!==void 0?e.fontWidth:t.fontWidth!==void 0?t.fontWidth:null,this.hyphens=typeof e.hyphens=="boolean"?e.hyphens:t.hyphens??null,this.invertFilter=typeof e.invertFilter=="boolean"?e.invertFilter:t.invertFilter??null,this.invertGaijiFilter=typeof e.invertGaijiFilter=="boolean"?e.invertGaijiFilter:t.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||e.iOSPatch===!1?!1:e.iOSPatch===!0?(L.OS.iOS||L.OS.iPadOS)&&L.iOSRequest==="mobile":t.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||e.iPadOSPatch===!1?!1:e.iPadOSPatch===!0?L.OS.iPadOS&&L.iOSRequest==="desktop":t.iPadOSPatch,this.letterSpacing=e.letterSpacing!==void 0?e.letterSpacing:t.letterSpacing!==void 0?t.letterSpacing:null,this.ligatures=typeof e.ligatures=="boolean"?e.ligatures:t.ligatures??null,this.lineHeight=e.lineHeight!==void 0?e.lineHeight:t.lineHeight!==void 0?t.lineHeight:null,this.linkColor=e.linkColor||t.linkColor||null,this.maximalLineLength=e.maximalLineLength===null?null:e.maximalLineLength||t.maximalLineLength||null,this.minimalLineLength=e.minimalLineLength===null?null:e.minimalLineLength||t.minimalLineLength||null,this.noRuby=typeof e.noRuby=="boolean"?e.noRuby:t.noRuby??null,this.optimalLineLength=e.optimalLineLength||t.optimalLineLength,this.pageGutter=e.pageGutter!==void 0?e.pageGutter:t.pageGutter!==void 0?t.pageGutter:null,this.paragraphIndent=e.paragraphIndent!==void 0?e.paragraphIndent:t.paragraphIndent!==void 0?t.paragraphIndent:null,this.paragraphSpacing=e.paragraphSpacing!==void 0?e.paragraphSpacing:t.paragraphSpacing!==void 0?t.paragraphSpacing:null,this.scroll=typeof e.scroll=="boolean"?e.scroll:t.scroll??null,this.scrollPaddingTop=e.scrollPaddingTop!==void 0?e.scrollPaddingTop:t.scrollPaddingTop!==void 0?t.scrollPaddingTop:null,this.scrollPaddingBottom=e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:null,this.scrollPaddingLeft=e.scrollPaddingLeft!==void 0?e.scrollPaddingLeft:t.scrollPaddingLeft!==void 0?t.scrollPaddingLeft:null,this.scrollPaddingRight=e.scrollPaddingRight!==void 0?e.scrollPaddingRight:t.scrollPaddingRight!==void 0?t.scrollPaddingRight:null,this.selectionBackgroundColor=e.selectionBackgroundColor||t.selectionBackgroundColor||null,this.selectionTextColor=e.selectionTextColor||t.selectionTextColor||null,this.textAlign=e.textAlign||t.textAlign||null,this.textColor=e.textColor||t.textColor||null,this.textNormalization=typeof e.textNormalization=="boolean"?e.textNormalization:t.textNormalization??null,this.visitedColor=e.visitedColor||t.visitedColor||null,this.wordSpacing=e.wordSpacing!==void 0?e.wordSpacing:t.wordSpacing!==void 0?t.wordSpacing:null,this.experiments=t.experiments||null}}function lt(o){const e=getComputedStyle(o),t=parseFloat(e.paddingLeft||"0"),i=parseFloat(e.paddingRight||"0");return o.clientWidth-t-i}class Xt extends Ne{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 Ln extends Ne{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]=it[t].value}),e}}class An{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=lt(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 Xt(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(lt(this.containerParent)-this.constraint),r=this.getCompensatedMetrics(e,t),{zoomCompensation:s,optimal:a,minimal:l,maximal:h}=r,c=()=>n>=a&&h!==null?Math.min(Math.round(h*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&&h!==null){u=Math.floor(n/a);const b=Math.round(u*(h*s));m=Math.min(b,n)}else m=c();else if(i>1){const b=Math.round(i*(l!==null?l:a));if(n>=b)if(u=i,h===null)m=n;else{const d=Math.round(u*(h*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=c();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=c();return{colCount:u,effectiveContainerWidth:m,effectiveLineLength:Math.round(m/u/(e&&e>=1?e:1)*s)}}computeScrollLength(e,t){const i=Math.round(lt(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,h=i,c=Math.round(s*r);if(a===null)c=i;else{const u=Math.min(Math.round(a*r),i);c=t?u:Math.round(u*r)}return{colCount:l,effectiveContainerWidth:h,effectiveLineLength:c}}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 to=`/*!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@readium/navigator",
3
- "version": "2.4.0-alpha.2",
3
+ "version": "2.4.0-alpha.3",
4
4
  "type": "module",
5
5
  "description": "Next generation SDK for publications in Web Apps",
6
6
  "author": "readium",
@@ -55,8 +55,8 @@
55
55
  "typescript-plugin-css-modules": "^5.2.0",
56
56
  "user-agent-data-types": "^0.4.2",
57
57
  "vite": "^7.3.1",
58
- "@readium/shared": "2.1.5",
59
- "@readium/navigator-html-injectables": "2.3.0"
58
+ "@readium/navigator-html-injectables": "2.3.0",
59
+ "@readium/shared": "2.1.5"
60
60
  },
61
61
  "scripts": {
62
62
  "clean": "rimraf types dist",